From e73d1594c349540055d6008101e882219db239de Mon Sep 17 00:00:00 2001 From: Rami Mohamed Date: Sun, 6 Sep 2026 23:25:35 +0400 Subject: [PATCH 1/2] docs: design payment instruction state events --- ...-09-06-payment-instruction-state-events.md | 104 ++++++++++++++++++ ...payment-instruction-state-events-design.md | 87 +++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 docs/superpowers/plans/2026-09-06-payment-instruction-state-events.md create mode 100644 docs/superpowers/specs/2026-09-06-payment-instruction-state-events-design.md diff --git a/docs/superpowers/plans/2026-09-06-payment-instruction-state-events.md b/docs/superpowers/plans/2026-09-06-payment-instruction-state-events.md new file mode 100644 index 0000000..b16ad1f --- /dev/null +++ b/docs/superpowers/plans/2026-09-06-payment-instruction-state-events.md @@ -0,0 +1,104 @@ +# Payment Instruction State Events Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add a transactional PostgreSQL outbox and bounded at-least-once Kafka publisher for payment-instruction state events. + +**Architecture:** Extend the existing application service transaction to persist one immutable event payload for each accepted instruction state. Keep the outbox behind an outbound port, use JDBC/Flyway for PostgreSQL, and isolate Kafka delivery in a scheduled adapter with leased batch claims and durable retry state. + +**Tech Stack:** Java 21, Spring Boot 4, Spring JDBC transactions, Flyway PostgreSQL migrations, Spring Kafka, Jackson, JUnit 5, AssertJ, Testcontainers PostgreSQL. + +**Spec:** `docs/superpowers/specs/2026-09-06-payment-instruction-state-events-design.md` + +## Global Constraints + +- Use topic `payment.instruction.state.v1` and event type `PaymentInstructionStateChanged.v1`. +- Payload status is exactly `PENDING`, `COMPLETED`, or `FAILED`. +- Reuse the persisted `eventId` and serialized payload on every retry. +- Create and terminal transition plus outbox insert must share one database transaction. +- Do not mutate accounts or ledger, add provider credentials, add public routes, or add extra CI jobs. +- Keep tests focused on load-bearing persistence and publication behavior. +- Add the organization AsyncAPI contract in a separate `.github` PR; do not embed a conflicting schema in this service. + +--- + +### Task 1: Add the event and outbox application boundaries + +**Files:** +- Create: `src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionStateEvent.java` +- Create: `src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutbox.java` +- Create: `src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionStateEventFactory.java` +- Modify: `src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionRepository.java` +- Modify: `src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionSaveResult.java` +- Test: `src/test/java/com/digitalbank/paymentservice/application/service/PaymentInstructionServiceTest.java` + +**Interfaces:** +- `PaymentInstructionStateEvent` exposes `eventId`, `eventType`, `schemaVersion`, `producer`, `occurredAt`, `aggregateId`, `correlationId`, `causationId`, `instructionId`, `idempotencyKey`, `amount`, `currency`, `status`, and nullable `failureReason`, plus serialized payload and header values. +- `PaymentInstructionOutbox.save(PaymentInstructionStateEvent event)` is the transactional outbound port; the JDBC adapter implements it later. +- `PaymentInstructionRepository.saveIfAbsent` accepts the instruction and a PENDING event; `transition` returns a result that distinguishes a real state change from an idempotent replay. + +- [ ] **Step 1: Write the failing service tests** for one PENDING event on a new instruction, one terminal event on a real transition, and no duplicate event on equivalent create or repeated terminal replay. +- [ ] **Step 2: Run the focused test** with `./mvnw --batch-mode --no-transfer-progress -Dtest=PaymentInstructionServiceTest test`; confirm it fails because the new event/outbox contract is absent. +- [ ] **Step 3: Implement the immutable event record, event factory, and repository transition result** using the approved envelope and deterministic causation fallback. +- [ ] **Step 4: Update the service transaction** to build an event once per real mutation and call the outbox port only after the corresponding instruction write succeeds in the same transaction. +- [ ] **Step 5: Run the focused test** again and confirm all service tests pass. +- [ ] **Step 6: Commit** with `git add src/main/java src/test/java && git commit -m "feat: define payment instruction state events"`. + +### Task 2: Add PostgreSQL outbox persistence and atomic integration + +**Files:** +- Create: `src/main/resources/db/migration/V2__create_payment_instruction_outbox.sql` +- Create: `src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionOutbox.java` +- Create: `src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PaymentInstructionOutboxRecord.java` +- Modify: `src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionRepository.java` +- Modify: `src/test/java/com/digitalbank/paymentservice/PaymentInstructionApiIT.java` + +**Interfaces:** +- The adapter implements `PaymentInstructionOutbox` and provides `claimBatch`, `markPublished`, and `markFailedOrRetry` for the publisher. +- The migration creates immutable event identity and payload columns, a unique `(instruction_id, event_status)` key, and indexed eligible-row lookup. + +- [ ] **Step 1: Write the failing PostgreSQL integration assertions** that creation leaves exactly one PENDING outbox row with matching instruction fields and that completion/failure leaves exactly one matching terminal row. +- [ ] **Step 2: Run `./mvnw --batch-mode --no-transfer-progress -Dtest=PaymentInstructionApiIT test`** and confirm the new SQL assertions fail because the table/adapter is absent. +- [ ] **Step 3: Implement the Flyway migration** with check constraints for event and publication fields, unique identity, and retry/lease indexes. +- [ ] **Step 4: Implement the JDBC outbox adapter** with serialized payload storage, PostgreSQL `FOR UPDATE SKIP LOCKED` claims, leases, and durable publication/error updates. +- [ ] **Step 5: Wire the existing JDBC instruction repository and service transaction** so a failed outbox insert rolls back the instruction mutation. +- [ ] **Step 6: Run the focused integration test** and confirm atomic creation, terminal transition, and replay behavior pass. +- [ ] **Step 7: Commit** with `git add src/main src/test && git commit -m "feat: persist payment instruction outbox events"`. + +### Task 3: Add bounded Kafka publication + +**Files:** +- Create: `src/main/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisher.java` +- Create: `src/main/java/com/digitalbank/paymentservice/configuration/PaymentEventProperties.java` +- Modify: `pom.xml` +- Modify: `src/main/resources/application.properties` +- Modify: `src/main/java/com/digitalbank/paymentservice/PaymentServiceApplication.java` +- Test: `src/test/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisherTest.java` + +**Interfaces:** +- `PaymentInstructionEventPublisher.publishBatch()` claims at most `batch-size` eligible records, sends each `ProducerRecord` to the configured topic, and marks each outcome through the outbox adapter. +- Kafka record key is `aggregateId`; required headers are `event-id`, `correlation-id`, `causation-id`, `producer`, `schema-version`, and `occurred-at`. +- Defaults are topic `payment.instruction.state.v1`, batch size `25`, max attempts `5`, fixed retry backoff `PT5S`, and lease `PT30S`; all are externalizable under `payment.events.*`. + +- [ ] **Step 1: Write the failing publisher tests** for successful publication with exact topic/key/headers/payload, retry after a sender failure, and durable final failure at max attempts. +- [ ] **Step 2: Run `./mvnw --batch-mode --no-transfer-progress -Dtest=PaymentInstructionEventPublisherTest test`** and confirm it fails because the publisher is absent. +- [ ] **Step 3: Add `spring-kafka`, typed properties, scheduling enablement, and safe defaults** without adding provider or Kafka credentials to the repository. +- [ ] **Step 4: Implement the publisher** with bounded claim size, blocking send result handling, lease-safe updates, and bounded error text. +- [ ] **Step 5: Run the focused publisher test** and confirm all publication cases pass. +- [ ] **Step 6: Commit** with `git add pom.xml src/main src/test && git commit -m "feat: publish payment instruction state events"`. + +### Task 4: Document operations and verify the whole service + +**Files:** +- Modify: `README.md` +- Modify: `AGENTS.md` +- Test: existing Maven integration suite and Helm chart + +- [ ] **Step 1: Add concise operational documentation** for the topic, outbox retry visibility, externalized publisher settings, and SIT evidence query; state that account/ledger/provider/public-route behavior remains out of scope. +- [ ] **Step 2: Run `./mvnw --batch-mode --no-transfer-progress test`**. +- [ ] **Step 3: Run `./mvnw --batch-mode --no-transfer-progress verify -DskipUnitTests=true`** for integration/package verification. +- [ ] **Step 4: Run `helm lint helm --strict --values helm/values-sit.yaml` and render the chart with `helm template`**. +- [ ] **Step 5: Run `git diff --check` and scan the diff for forbidden account/ledger mutations, credentials, public routes, and CI changes.** +- [ ] **Step 6: Commit** with `git add README.md AGENTS.md && git commit -m "docs: document payment state event operations"`. +- [ ] **Step 7: Create the separate `.github` contract worktree/PR** from `.github` `origin/main`, add the exact approved AsyncAPI contract, run its existing validation, push, and open a normal non-draft PR. Link it explicitly from the service PR. +- [ ] **Step 8: Request review of the service diff, fix Critical/Important findings, then push the service branch and open a normal non-draft PR linked to `.github#250` and `.github#31`; do not merge either PR. diff --git a/docs/superpowers/specs/2026-09-06-payment-instruction-state-events-design.md b/docs/superpowers/specs/2026-09-06-payment-instruction-state-events-design.md new file mode 100644 index 0000000..edbbf78 --- /dev/null +++ b/docs/superpowers/specs/2026-09-06-payment-instruction-state-events-design.md @@ -0,0 +1,87 @@ +# Payment Instruction State Events Design + +**Issue:** `.github#250` under `.github#31` + +## Goal + +Publish durable, versioned payment-instruction state events for `PENDING`, +`COMPLETED`, and `FAILED` without changing account or ledger state, adding +provider integrations, or adding public payment routes. + +## Contract + +The organization contract will be added in a separate `.github` pull request. +The service publishes one Kafka topic: + +```text +payment.instruction.state.v1 +``` + +Every message uses the event type `PaymentInstructionStateChanged.v1` and the +following JSON payload envelope: + +```json +{ + "eventId": "uuid", + "eventType": "PaymentInstructionStateChanged.v1", + "schemaVersion": "1.0.0", + "producer": "payment-service", + "occurredAt": "2026-09-06T19:00:00Z", + "aggregateId": "payment-instruction-uuid", + "correlationId": "trace-or-workflow-id", + "causationId": "stable-command-or-transition-id", + "instructionId": "payment-instruction-uuid", + "idempotencyKey": "client-idempotency-key", + "amount": "125.50", + "currency": "AED", + "status": "PENDING", + "failureReason": null +} +``` + +`failureReason` is present only for `FAILED` events. Required Kafka headers use +kebab-case and repeat `event-id`, `correlation-id`, `causation-id`, `producer`, +`schema-version`, and `occurred-at`. `aggregateId` is the Kafka partition key. +`eventId` is generated once for a state transition, persisted with the outbox +payload, and reused for every delivery retry. + +The existing lifecycle API does not carry a causal command identifier. Until a +dedicated command-header contract is introduced, creation uses the normalized +idempotency key as `causationId`; a terminal transition uses +`:`. The instruction's existing correlation ID is +preserved unchanged. + +## Persistence And Atomicity + +Flyway adds `payment_instruction_outbox` with one row per instruction state, +enforced by a unique `(instruction_id, event_status)` constraint. The row +stores the serialized JSON payload plus the common header values and publisher +control data: attempts, next-attempt time, lease expiry, publication time, and +last error. `PENDING`, `COMPLETED`, and `FAILED` are business event statuses; +publication status is represented by `published_at` and retry metadata. + +`PaymentInstructionService` owns the application transaction. On creation it +persists the instruction and PENDING outbox record together. On a real terminal +transition it updates the instruction and inserts exactly one terminal outbox +record together. Idempotent replays return the existing state and do not create +another outbox row. A failed outbox insert rolls back the instruction mutation. + +## Publication + +The publisher is a Spring scheduled adapter backed by `KafkaTemplate`. It claims at most the configured batch size using PostgreSQL row locks +and a time-bounded lease, increments the attempt count before sending, and +publishes the stored payload and headers. Success sets `published_at`; failure +sets `last_error` and a bounded retry time, or leaves the row durably marked +failed once `max-attempts` is reached. Lease expiry makes an abandoned claim +eligible again, preserving at-least-once delivery. A crash after Kafka accepts +the record and before the success update may duplicate delivery, but never +creates a second business transition and always reuses the same event ID. + +## Testing And Scope + +Focused tests cover the application transaction/outbox behavior against the +existing PostgreSQL Testcontainers pattern and publisher success/retry/final +failure using a test sender. Existing API, unit, Maven, and Helm checks remain +the quality gates. No account, ledger, provider credential, public route, +redundant CI job, or direct synchronous downstream call is introduced. From bf37b430b70b3bad487c23e8f7b77f4bc76f731e Mon Sep 17 00:00:00 2001 From: Rami Mohamed Date: Mon, 7 Sep 2026 00:09:06 +0400 Subject: [PATCH 2/2] feat: publish payment instruction state events --- AGENTS.md | 5 +- README.md | 14 +- pom.xml | 8 + .../PaymentServiceApplication.java | 5 + .../PaymentInstructionEventPublisher.java | 89 +++++++++ .../InMemoryPaymentInstructionRepository.java | 17 +- .../PostgresPaymentInstructionOutbox.java | 178 ++++++++++++++++++ .../PostgresPaymentInstructionRepository.java | 7 +- .../port/out/PaymentInstructionOutbox.java | 24 +++ .../out/PaymentInstructionOutboxRecord.java | 7 + .../out/PaymentInstructionRepository.java | 3 +- .../out/PaymentInstructionStateEvent.java | 23 +++ .../PaymentInstructionTransitionResult.java | 5 + .../service/PaymentInstructionService.java | 30 ++- .../PaymentInstructionStateEventFactory.java | 98 ++++++++++ .../configuration/PaymentEventProperties.java | 72 +++++++ .../PaymentKafkaConfiguration.java | 42 +++++ .../PaymentTimeConfiguration.java | 8 + .../domain/model/PaymentInstruction.java | 9 + .../model/PaymentInstructionRequest.java | 3 + src/main/resources/application.properties | 8 + .../V2__create_payment_instruction_outbox.sql | 54 ++++++ .../PaymentInstructionApiIT.java | 118 +++++++++++- .../PaymentInstructionEventPublisherTest.java | 166 ++++++++++++++++ .../PaymentInstructionServiceTest.java | 101 +++++++++- src/test/resources/application.properties | 1 + 26 files changed, 1071 insertions(+), 24 deletions(-) create mode 100644 src/main/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisher.java create mode 100644 src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionOutbox.java create mode 100644 src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutbox.java create mode 100644 src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutboxRecord.java create mode 100644 src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionStateEvent.java create mode 100644 src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionTransitionResult.java create mode 100644 src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionStateEventFactory.java create mode 100644 src/main/java/com/digitalbank/paymentservice/configuration/PaymentEventProperties.java create mode 100644 src/main/java/com/digitalbank/paymentservice/configuration/PaymentKafkaConfiguration.java create mode 100644 src/main/resources/db/migration/V2__create_payment_instruction_outbox.sql create mode 100644 src/test/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisherTest.java diff --git a/AGENTS.md b/AGENTS.md index e1fceee..d678997 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,8 @@ - Owns service bootstrap, Config Client, health probes, OpenAPI metadata, packaging, and deployment. - Owns the transport-neutral payment instruction lifecycle foundation and its idempotency/correlation boundary. -- Does not own customer data, account balances, ledger postings, transfer saga orchestration, Kafka behavior, persistence, or secrets. +- Owns durable payment instruction persistence, the transactional payment state outbox, and bounded Kafka publication. +- Does not own customer data, account balances, ledger postings, transfer saga orchestration, provider integrations, or secrets. - Do not add public payment routes without a supporting issue and API contract work. ## Commands @@ -32,7 +33,7 @@ helm lint helm --strict --values helm/values-sit.yaml Use unit tests for isolated application/domain behavior when those layers exist. Use integration tests for HTTP and infrastructure-backed behavior. Keep `./mvnw verify` green before merge. -The payment instruction foundation currently uses an in-memory output adapter for lifecycle tests. Do not mistake it for production persistence; durable payment state and external payment-provider integration require separately tracked work. +The payment instruction lifecycle uses PostgreSQL in production and an in-memory adapter in unit tests. The transactional state outbox and Kafka publisher are part of the current payment instruction event slice; external payment-provider integration requires separately tracked work. ## Architecture diff --git a/README.md b/README.md index 3190372..0a2bb87 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Payment Service -Payment Service is the Digital Bank Java platform foundation for future payment rail workflows. This repository contains a deployable Spring Boot service plus an authenticated internal payment instruction lifecycle API; payment rail business logic, Kafka behavior, and public gateway routes remain intentionally out of scope. +Payment Service is the Digital Bank Java platform foundation for future payment rail workflows. This repository contains a deployable Spring Boot service, an authenticated internal payment instruction lifecycle API, and durable publication of governed payment instruction state events; payment rail business logic and public gateway routes remain intentionally out of scope. ## Implemented State @@ -11,10 +11,11 @@ Payment Service is the Digital Bank Java platform foundation for future payment - Non-root container image and hardened Helm deployment. - Default SIT service port `8085`. - Internal payment instruction lifecycle endpoints at `/internal/v1/payment-instructions`. +- PostgreSQL-backed transactional outbox and bounded at-least-once Kafka publication for `payment.instruction.state.v1`. ## Boundaries -This service will later own payment workflow coordination and payment rail integration boundaries. It does not currently own customer data, account balances, ledger postings, transfer saga orchestration, Kafka topics, or provider credentials. +This service will later own payment workflow coordination and payment rail integration boundaries. It does not currently own customer data, account balances, ledger postings, transfer saga orchestration, or provider credentials. Its Kafka producer publishes only payment instruction state facts; the governed AsyncAPI contract is maintained in the organization `.github` repository. Payment rail integrations must remain behind outbound ports and adapters when that work is approved and tracked. Do not add provider credentials or payment data to this repository. @@ -24,7 +25,7 @@ The application exposes an internal HTTP adapter over the transport-neutral paym The application boundary also normalizes the idempotency key, amount, currency, and description before comparing retries. An equivalent retry returns the original instruction identity, while reuse of the same idempotency key with a different business request is rejected. Correlation IDs are retained for tracing and are deliberately excluded from the idempotency comparison, so a retried request may have a new trace context. -Payment instructions are stored in PostgreSQL through a Flyway-managed schema. Idempotency keys are unique in the database, so equivalent retries converge across replicas and restarts; the canonical request fields are compared before a replay is returned, and a changed payload returns `409 Conflict`. Payment-provider adapters, Kafka publication, and transaction saga orchestration are intentionally deferred to their planned stories. +Payment instructions are stored in PostgreSQL through a Flyway-managed schema. Idempotency keys are unique in the database, so equivalent retries converge across replicas and restarts; the canonical request fields are compared before a replay is returned, and a changed payload returns `409 Conflict`. Creation and real terminal transitions insert one durable outbox record in the same database transaction. The publisher sends the stored payload and governed headers with a bounded leased retry loop, preserving event identity across retries. Payment-provider adapters and transaction saga orchestration remain out of scope. All payment instruction endpoints require a bearer JWT with the `payment.internal` scope. Missing or invalid authentication returns `401 Unauthorized`; an authenticated caller without that scope returns `403 Forbidden`. Both responses use `application/problem+json`. Health, service metadata, and the generated OpenAPI document remain public. @@ -54,6 +55,13 @@ Config Server supplies the effective runtime configuration. The service reposito | `spring.security.oauth2.resourceserver.jwt.jwk-set-uri` | JWT JWK set URI | Optional when issuer discovery is available | | `auth.jwt.secret` | Base64 HMAC secret shared with Auth Service in SIT | none | | `auth.jwt.issuer` | HMAC token issuer used in SIT | none | +| `PAYMENT_EVENTS_TOPIC` | Kafka topic for payment instruction state events | `payment.instruction.state.v1` | +| `PAYMENT_EVENTS_BATCH_SIZE` | Maximum events claimed per publisher poll | `25` | +| `PAYMENT_EVENTS_MAX_ATTEMPTS` | Maximum broker failure attempts before durable publication failure | `5` | +| `PAYMENT_EVENTS_RETRY_BACKOFF` | Delay before retrying a failed publication | `PT5S` | +| `PAYMENT_EVENTS_LEASE` | Claim lease for an in-flight publication batch | `PT30S` | +| `PAYMENT_EVENTS_SEND_TIMEOUT` | Maximum wait for one Kafka send | `PT5S` | +| `PAYMENT_EVENTS_POLL_DELAY_MS` | Publisher poll delay in milliseconds | `1000` | The application fallback port is `8085`, and the Helm chart sets `SERVER_PORT` from `service.port` so the process, probes, and Service remain aligned even before a service-specific Config Repo entry is added. The SIT chart injects the `payment_service` JDBC URL and reads PostgreSQL credentials from the existing `postgres` Secret (`POSTGRES_USER` and `POSTGRES_PASSWORD`). Credentials remain outside Git. diff --git a/pom.xml b/pom.xml index 8a9b3b7..af3b5c3 100644 --- a/pom.xml +++ b/pom.xml @@ -41,6 +41,10 @@ org.springframework.boot spring-boot-starter-webmvc + + org.springframework.boot + spring-boot-starter-json + org.springframework.boot spring-boot-starter-security @@ -62,6 +66,10 @@ org.springframework.boot spring-boot-starter-jdbc + + org.springframework.kafka + spring-kafka + org.springframework.boot spring-boot-starter-flyway diff --git a/src/main/java/com/digitalbank/paymentservice/PaymentServiceApplication.java b/src/main/java/com/digitalbank/paymentservice/PaymentServiceApplication.java index dca4665..ef6cf43 100644 --- a/src/main/java/com/digitalbank/paymentservice/PaymentServiceApplication.java +++ b/src/main/java/com/digitalbank/paymentservice/PaymentServiceApplication.java @@ -1,11 +1,14 @@ package com.digitalbank.paymentservice; +import com.digitalbank.paymentservice.configuration.PaymentEventProperties; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.security.SecurityScheme; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableScheduling; @OpenAPIDefinition( info = @@ -15,6 +18,8 @@ description = "Authenticated internal payment instruction APIs for future payment rail workflows.")) @SecurityScheme(name = "bearer-jwt", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT") +@EnableScheduling +@EnableConfigurationProperties(PaymentEventProperties.class) @SpringBootApplication public class PaymentServiceApplication { diff --git a/src/main/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisher.java b/src/main/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisher.java new file mode 100644 index 0000000..43a631f --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisher.java @@ -0,0 +1,89 @@ +package com.digitalbank.paymentservice.adapter.out.kafka; + +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutbox; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutboxRecord; +import com.digitalbank.paymentservice.configuration.PaymentEventProperties; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +public class PaymentInstructionEventPublisher { + + private final PaymentInstructionOutbox outbox; + private final KafkaTemplate kafkaTemplate; + private final PaymentEventProperties properties; + private final Clock clock; + + public PaymentInstructionEventPublisher( + PaymentInstructionOutbox outbox, + KafkaTemplate kafkaTemplate, + PaymentEventProperties properties, + Clock clock) { + this.outbox = outbox; + this.kafkaTemplate = kafkaTemplate; + this.properties = properties; + this.clock = clock; + } + + @Scheduled(fixedDelayString = "${payment.events.poll-delay-ms:1000}") + public void publishScheduled() { + publishBatch(); + } + + public void publishBatch() { + var now = clock.instant(); + var claimed = outbox.claimBatch(now, properties.getBatchSize(), properties.getLease()); + for (var record : claimed) { + publish(record); + } + } + + private void publish(PaymentInstructionOutboxRecord record) { + try { + var event = record.event(); + var kafkaRecord = + new ProducerRecord(properties.getTopic(), event.aggregateId(), event.payload()); + addHeaders(kafkaRecord, event.headers()); + kafkaTemplate.send(kafkaRecord).get(properties.getSendTimeout().toMillis(), TimeUnit.MILLISECONDS); + outbox.markPublished(event.eventId(), record.claimId(), clock.instant()); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + markFailure(record, exception); + } catch (ExecutionException | TimeoutException | RuntimeException exception) { + markFailure(record, exception); + } + } + + private void markFailure(PaymentInstructionOutboxRecord record, Throwable exception) { + var event = record.event(); + outbox.markFailedOrRetry( + event.eventId(), + record.claimId(), + record.attempts() + 1, + properties.getMaxAttempts(), + clock.instant(), + properties.getRetryBackoff(), + errorMessage(exception)); + } + + private static void addHeaders(ProducerRecord record, Map headers) { + headers.forEach((name, value) -> record.headers().add(name, value.getBytes(StandardCharsets.UTF_8))); + } + + private static String errorMessage(Throwable exception) { + var cause = exception instanceof ExecutionException && exception.getCause() != null + ? exception.getCause() + : exception; + var message = cause.getMessage(); + var value = cause.getClass().getSimpleName() + (message == null ? "" : ": " + message); + return value.length() <= 2000 ? value : value.substring(0, 2000); + } +} diff --git a/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/InMemoryPaymentInstructionRepository.java b/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/InMemoryPaymentInstructionRepository.java index c8ac302..f152883 100644 --- a/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/InMemoryPaymentInstructionRepository.java +++ b/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/InMemoryPaymentInstructionRepository.java @@ -2,6 +2,7 @@ import com.digitalbank.paymentservice.application.port.out.PaymentInstructionRepository; import com.digitalbank.paymentservice.application.port.out.PaymentInstructionSaveResult; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionTransitionResult; import com.digitalbank.paymentservice.domain.exception.PaymentInstructionNotFoundException; import com.digitalbank.paymentservice.domain.model.PaymentInstruction; import com.digitalbank.paymentservice.domain.model.PaymentInstructionId; @@ -38,14 +39,20 @@ public PaymentInstruction save(PaymentInstruction instruction) { } @Override - public PaymentInstruction transition( + public PaymentInstructionTransitionResult transition( PaymentInstructionId instructionId, UnaryOperator transition) { - var updated = instructions.compute(instructionId, (ignored, current) -> { - if (current == null) { + var current = instructions.get(instructionId); + if (current == null) { + throw new PaymentInstructionNotFoundException(instructionId); + } + var updated = instructions.compute(instructionId, (ignored, existing) -> { + if (existing == null) { return null; } - return transition.apply(current); + return transition.apply(existing); }); - return Optional.ofNullable(updated).orElseThrow(() -> new PaymentInstructionNotFoundException(instructionId)); + return new PaymentInstructionTransitionResult( + Optional.ofNullable(updated).orElseThrow(() -> new PaymentInstructionNotFoundException(instructionId)), + !updated.equals(current)); } } diff --git a/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionOutbox.java b/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionOutbox.java new file mode 100644 index 0000000..4151e6e --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionOutbox.java @@ -0,0 +1,178 @@ +package com.digitalbank.paymentservice.adapter.out.persistence; + +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutbox; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutboxRecord; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionStateEvent; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +class PostgresPaymentInstructionOutbox implements PaymentInstructionOutbox { + + private static final String SELECT_COLUMNS = """ + outbox.event_id, outbox.event_type, outbox.schema_version, outbox.producer, outbox.occurred_at, outbox.aggregate_id, + outbox.correlation_id, outbox.causation_id, outbox.instruction_id, outbox.idempotency_key, outbox.amount, outbox.currency, + outbox.event_status, outbox.failure_reason, outbox.payload::text as payload, outbox.attempt_count, outbox.claim_id, outbox.claim_until + """; + + private final JdbcTemplate jdbcTemplate; + + PostgresPaymentInstructionOutbox(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + @Transactional + public void save(PaymentInstructionStateEvent event) { + jdbcTemplate.update( + """ + insert into payment_instruction_outbox ( + event_id, instruction_id, aggregate_id, event_type, schema_version, producer, + occurred_at, correlation_id, causation_id, idempotency_key, amount, currency, + event_status, failure_reason, payload, next_attempt_at, created_at +) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, cast(? as numeric), ?, ?, ?, ?::jsonb, ?, ?) + """, + event.eventId(), + UUID.fromString(event.instructionId()), + UUID.fromString(event.aggregateId()), + event.eventType(), + event.schemaVersion(), + event.producer(), + Timestamp.from(event.occurredAt()), + event.correlationId(), + event.causationId(), + event.idempotencyKey(), + event.amount(), + event.currency(), + event.status(), + event.failureReason(), + event.payload(), + Timestamp.from(event.occurredAt()), + Timestamp.from(event.occurredAt())); + } + + @Override + @Transactional + public List claimBatch(Instant now, int batchSize, Duration lease) { + var claimId = UUID.randomUUID(); + var claimUntil = now.plus(lease); + return jdbcTemplate.query( + """ + with candidates as ( + select event_id + from payment_instruction_outbox + where publication_status = 'PENDING' + and next_attempt_at <= ? + and (claim_until is null or claim_until < ?) + order by created_at, event_id + for update skip locked + limit ? + ) + update payment_instruction_outbox outbox + set claim_id = ?, claim_until = ? + from candidates + where outbox.event_id = candidates.event_id + returning + """ + SELECT_COLUMNS, + this::mapClaimed, + Timestamp.from(now), + Timestamp.from(now), + batchSize, + claimId, + Timestamp.from(claimUntil)); + } + + @Override + @Transactional + public void markPublished(UUID eventId, UUID claimId, Instant publishedAt) { + jdbcTemplate.update(""" + update payment_instruction_outbox + set publication_status = 'PUBLISHED', + attempt_count = attempt_count + 1, + published_at = ?, + claim_id = null, + claim_until = null + where event_id = ? + and claim_id = ? + and publication_status = 'PENDING' + """, Timestamp.from(publishedAt), eventId, claimId); + } + + @Override + @Transactional + public void markFailedOrRetry( + UUID eventId, + UUID claimId, + int attempts, + int maxAttempts, + Instant now, + Duration retryBackoff, + String error) { + var terminal = attempts >= maxAttempts; + jdbcTemplate.update( + """ + update payment_instruction_outbox + set publication_status = ?, + attempt_count = ?, + next_attempt_at = ?, + last_error = ?, + claim_id = null, + claim_until = null + where event_id = ? + and claim_id = ? + and publication_status = 'PENDING' + """, + terminal ? "FAILED" : "PENDING", + attempts, + Timestamp.from(terminal ? now : now.plus(retryBackoff)), + error, + eventId, + claimId); + } + + private PaymentInstructionOutboxRecord mapClaimed(ResultSet resultSet, int rowNumber) throws SQLException { + var eventId = resultSet.getObject("event_id", UUID.class); + var claimId = resultSet.getObject("claim_id", UUID.class); + var event = new PaymentInstructionStateEvent( + eventId, + resultSet.getString("event_type"), + resultSet.getString("schema_version"), + resultSet.getString("producer"), + resultSet.getTimestamp("occurred_at").toInstant(), + resultSet.getObject("aggregate_id", UUID.class).toString(), + resultSet.getString("correlation_id"), + resultSet.getString("causation_id"), + resultSet.getObject("instruction_id", UUID.class).toString(), + resultSet.getString("idempotency_key"), + resultSet.getBigDecimal("amount").toPlainString(), + resultSet.getString("currency"), + resultSet.getString("event_status"), + resultSet.getString("failure_reason"), + resultSet.getString("payload"), + Map.of( + "event-id", eventId.toString(), + "correlation-id", resultSet.getString("correlation_id"), + "causation-id", resultSet.getString("causation_id"), + "producer", resultSet.getString("producer"), + "schema-version", resultSet.getString("schema_version"), + "occurred-at", + resultSet + .getTimestamp("occurred_at") + .toInstant() + .toString())); + return new PaymentInstructionOutboxRecord( + event, + resultSet.getInt("attempt_count"), + claimId, + resultSet.getTimestamp("claim_until").toInstant()); + } +} diff --git a/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionRepository.java b/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionRepository.java index 5ebe4a9..b56e79e 100644 --- a/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionRepository.java +++ b/src/main/java/com/digitalbank/paymentservice/adapter/out/persistence/PostgresPaymentInstructionRepository.java @@ -2,6 +2,7 @@ import com.digitalbank.paymentservice.application.port.out.PaymentInstructionRepository; import com.digitalbank.paymentservice.application.port.out.PaymentInstructionSaveResult; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionTransitionResult; import com.digitalbank.paymentservice.domain.exception.PaymentInstructionNotFoundException; import com.digitalbank.paymentservice.domain.model.PaymentInstruction; import com.digitalbank.paymentservice.domain.model.PaymentInstructionId; @@ -97,7 +98,7 @@ public PaymentInstruction save(PaymentInstruction instruction) { @Override @Transactional - public PaymentInstruction transition( + public PaymentInstructionTransitionResult transition( PaymentInstructionId instructionId, UnaryOperator transition) { var current = queryOne( "select " + SELECT_COLUMNS + " from payment_instructions where id = ? for update", @@ -105,7 +106,7 @@ public PaymentInstruction transition( .orElseThrow(() -> new PaymentInstructionNotFoundException(instructionId)); var updated = transition.apply(current); if (updated.equals(current)) { - return current; + return new PaymentInstructionTransitionResult(current, false); } jdbcTemplate.update( @@ -118,7 +119,7 @@ public PaymentInstruction transition( updated.failureReason(), Timestamp.from(updated.updatedAt()), instructionId.value()); - return updated; + return new PaymentInstructionTransitionResult(updated, true); } private Optional findByIdempotencyKey(String idempotencyKey) { diff --git a/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutbox.java b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutbox.java new file mode 100644 index 0000000..1d6fee6 --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutbox.java @@ -0,0 +1,24 @@ +package com.digitalbank.paymentservice.application.port.out; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface PaymentInstructionOutbox { + + void save(PaymentInstructionStateEvent event); + + List claimBatch(Instant now, int batchSize, Duration lease); + + void markPublished(UUID eventId, UUID claimId, Instant publishedAt); + + void markFailedOrRetry( + UUID eventId, + UUID claimId, + int attempts, + int maxAttempts, + Instant now, + Duration retryBackoff, + String error); +} diff --git a/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutboxRecord.java b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutboxRecord.java new file mode 100644 index 0000000..f5c6a58 --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionOutboxRecord.java @@ -0,0 +1,7 @@ +package com.digitalbank.paymentservice.application.port.out; + +import java.time.Instant; +import java.util.UUID; + +public record PaymentInstructionOutboxRecord( + PaymentInstructionStateEvent event, int attempts, UUID claimId, Instant claimUntil) {} diff --git a/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionRepository.java b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionRepository.java index c770a44..f80e6dd 100644 --- a/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionRepository.java +++ b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionRepository.java @@ -13,5 +13,6 @@ public interface PaymentInstructionRepository { PaymentInstruction save(PaymentInstruction instruction); - PaymentInstruction transition(PaymentInstructionId instructionId, UnaryOperator transition); + PaymentInstructionTransitionResult transition( + PaymentInstructionId instructionId, UnaryOperator transition); } diff --git a/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionStateEvent.java b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionStateEvent.java new file mode 100644 index 0000000..8da7037 --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionStateEvent.java @@ -0,0 +1,23 @@ +package com.digitalbank.paymentservice.application.port.out; + +import java.time.Instant; +import java.util.Map; +import java.util.UUID; + +public record PaymentInstructionStateEvent( + UUID eventId, + String eventType, + String schemaVersion, + String producer, + Instant occurredAt, + String aggregateId, + String correlationId, + String causationId, + String instructionId, + String idempotencyKey, + String amount, + String currency, + String status, + String failureReason, + String payload, + Map headers) {} diff --git a/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionTransitionResult.java b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionTransitionResult.java new file mode 100644 index 0000000..86d128e --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/application/port/out/PaymentInstructionTransitionResult.java @@ -0,0 +1,5 @@ +package com.digitalbank.paymentservice.application.port.out; + +import com.digitalbank.paymentservice.domain.model.PaymentInstruction; + +public record PaymentInstructionTransitionResult(PaymentInstruction instruction, boolean transitioned) {} diff --git a/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionService.java b/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionService.java index eae45f4..ba8ee04 100644 --- a/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionService.java +++ b/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionService.java @@ -6,6 +6,7 @@ import com.digitalbank.paymentservice.application.port.in.FailPaymentInstructionInputPort; import com.digitalbank.paymentservice.application.port.in.GetPaymentInstructionInputPort; import com.digitalbank.paymentservice.application.port.in.PaymentInstructionResult; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutbox; import com.digitalbank.paymentservice.application.port.out.PaymentInstructionRepository; import com.digitalbank.paymentservice.domain.exception.PaymentInstructionIdempotencyConflictException; import com.digitalbank.paymentservice.domain.exception.PaymentInstructionNotFoundException; @@ -14,6 +15,7 @@ import java.time.Clock; import java.util.Objects; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service public class PaymentInstructionService @@ -23,14 +25,23 @@ public class PaymentInstructionService FailPaymentInstructionInputPort { private final PaymentInstructionRepository repository; + private final PaymentInstructionOutbox outbox; + private final PaymentInstructionStateEventFactory eventFactory; private final Clock clock; - public PaymentInstructionService(PaymentInstructionRepository repository, Clock clock) { + public PaymentInstructionService( + PaymentInstructionRepository repository, + Clock clock, + PaymentInstructionOutbox outbox, + PaymentInstructionStateEventFactory eventFactory) { this.repository = Objects.requireNonNull(repository, "Payment instruction repository is required"); this.clock = Objects.requireNonNull(clock, "Clock is required"); + this.outbox = Objects.requireNonNull(outbox, "Payment instruction outbox is required"); + this.eventFactory = Objects.requireNonNull(eventFactory, "Payment instruction state event factory is required"); } @Override + @Transactional public PaymentInstructionResult register(CreatePaymentInstructionCommand command) { Objects.requireNonNull(command, "Payment instruction command is required"); var request = command.request(); @@ -45,6 +56,7 @@ public PaymentInstructionResult register(CreatePaymentInstructionCommand command return PaymentInstructionResult.from(saved.instruction(), true); } + outbox.save(eventFactory.create(saved.instruction())); return PaymentInstructionResult.from(saved.instruction(), false); } @@ -58,14 +70,22 @@ public PaymentInstructionResult get(PaymentInstructionId instructionId) { } @Override + @Transactional public PaymentInstructionResult complete(PaymentInstructionId instructionId) { - return PaymentInstructionResult.from( - repository.transition(instructionId, instruction -> instruction.complete(clock.instant())), false); + var transition = repository.transition(instructionId, instruction -> instruction.complete(clock.instant())); + if (transition.transitioned()) { + outbox.save(eventFactory.create(transition.instruction())); + } + return PaymentInstructionResult.from(transition.instruction(), false); } @Override + @Transactional public PaymentInstructionResult fail(PaymentInstructionId instructionId, String reason) { - return PaymentInstructionResult.from( - repository.transition(instructionId, instruction -> instruction.fail(reason, clock.instant())), false); + var transition = repository.transition(instructionId, instruction -> instruction.fail(reason, clock.instant())); + if (transition.transitioned()) { + outbox.save(eventFactory.create(transition.instruction())); + } + return PaymentInstructionResult.from(transition.instruction(), false); } } diff --git a/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionStateEventFactory.java b/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionStateEventFactory.java new file mode 100644 index 0000000..27b2eec --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/application/service/PaymentInstructionStateEventFactory.java @@ -0,0 +1,98 @@ +package com.digitalbank.paymentservice.application.service; + +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionStateEvent; +import com.digitalbank.paymentservice.domain.model.PaymentInstruction; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import org.springframework.stereotype.Component; + +@Component +public class PaymentInstructionStateEventFactory { + + static final String EVENT_TYPE = "PaymentInstructionStateChanged.v1"; + static final String SCHEMA_VERSION = "1.0.0"; + static final String PRODUCER = "payment-service"; + + private final ObjectMapper objectMapper; + + public PaymentInstructionStateEventFactory(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public PaymentInstructionStateEvent create(PaymentInstruction instruction) { + var eventId = UUID.randomUUID(); + var occurredAt = instruction.updatedAt(); + var aggregateId = instruction.id().value().toString(); + var status = instruction.status().name(); + var causationId = + status.equals("PENDING") ? instruction.request().idempotencyKey() : aggregateId + ":" + status; + var amount = instruction.request().amount().toPlainString(); + var payload = payload(eventId, occurredAt, aggregateId, instruction, causationId, amount, status); + var headers = Map.of( + "event-id", + eventId.toString(), + "correlation-id", + instruction.correlationId(), + "causation-id", + causationId, + "producer", + PRODUCER, + "schema-version", + SCHEMA_VERSION, + "occurred-at", + occurredAt.toString()); + return new PaymentInstructionStateEvent( + eventId, + EVENT_TYPE, + SCHEMA_VERSION, + PRODUCER, + occurredAt, + aggregateId, + instruction.correlationId(), + causationId, + aggregateId, + instruction.request().idempotencyKey(), + amount, + instruction.request().currency(), + status, + instruction.failureReason(), + payload, + headers); + } + + private String payload( + UUID eventId, + Instant occurredAt, + String aggregateId, + PaymentInstruction instruction, + String causationId, + String amount, + String status) { + var payload = new LinkedHashMap(); + payload.put("eventId", eventId); + payload.put("eventType", EVENT_TYPE); + payload.put("schemaVersion", SCHEMA_VERSION); + payload.put("producer", PRODUCER); + payload.put("occurredAt", occurredAt); + payload.put("aggregateId", aggregateId); + payload.put("correlationId", instruction.correlationId()); + payload.put("causationId", causationId); + payload.put("instructionId", aggregateId); + payload.put("idempotencyKey", instruction.request().idempotencyKey()); + payload.put("amount", amount); + payload.put("currency", instruction.request().currency()); + payload.put("status", status); + if (instruction.failureReason() != null) { + payload.put("failureReason", instruction.failureReason()); + } + try { + return objectMapper.writeValueAsString(payload); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("Could not serialize payment instruction state event", exception); + } + } +} diff --git a/src/main/java/com/digitalbank/paymentservice/configuration/PaymentEventProperties.java b/src/main/java/com/digitalbank/paymentservice/configuration/PaymentEventProperties.java new file mode 100644 index 0000000..2c883c3 --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/configuration/PaymentEventProperties.java @@ -0,0 +1,72 @@ +package com.digitalbank.paymentservice.configuration; + +import java.time.Duration; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "payment.events") +public class PaymentEventProperties { + + private String topic = "payment.instruction.state.v1"; + private int batchSize = 25; + private int maxAttempts = 5; + private Duration retryBackoff = Duration.ofSeconds(5); + private Duration lease = Duration.ofSeconds(30); + private Duration sendTimeout = Duration.ofSeconds(5); + private long pollDelayMs = 1_000; + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public int getBatchSize() { + return batchSize; + } + + public void setBatchSize(int batchSize) { + this.batchSize = batchSize; + } + + public int getMaxAttempts() { + return maxAttempts; + } + + public void setMaxAttempts(int maxAttempts) { + this.maxAttempts = maxAttempts; + } + + public Duration getRetryBackoff() { + return retryBackoff; + } + + public void setRetryBackoff(Duration retryBackoff) { + this.retryBackoff = retryBackoff; + } + + public Duration getLease() { + return lease; + } + + public void setLease(Duration lease) { + this.lease = lease; + } + + public Duration getSendTimeout() { + return sendTimeout; + } + + public void setSendTimeout(Duration sendTimeout) { + this.sendTimeout = sendTimeout; + } + + public long getPollDelayMs() { + return pollDelayMs; + } + + public void setPollDelayMs(long pollDelayMs) { + this.pollDelayMs = pollDelayMs; + } +} diff --git a/src/main/java/com/digitalbank/paymentservice/configuration/PaymentKafkaConfiguration.java b/src/main/java/com/digitalbank/paymentservice/configuration/PaymentKafkaConfiguration.java new file mode 100644 index 0000000..c7beda7 --- /dev/null +++ b/src/main/java/com/digitalbank/paymentservice/configuration/PaymentKafkaConfiguration.java @@ -0,0 +1,42 @@ +package com.digitalbank.paymentservice.configuration; + +import java.util.HashMap; +import java.util.Map; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; + +@Configuration +public class PaymentKafkaConfiguration { + + @Bean + ProducerFactory paymentProducerFactory(Environment environment) { + var properties = new HashMap(); + properties.put( + ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, + environment.getProperty("spring.kafka.bootstrap-servers", "localhost:9092")); + properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); + properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); + properties.putAll(boundProperties(environment, "spring.kafka.properties")); + properties.putAll(boundProperties(environment, "spring.kafka.producer.properties")); + return new DefaultKafkaProducerFactory<>(properties); + } + + @Bean + KafkaTemplate paymentKafkaTemplate(ProducerFactory paymentProducerFactory) { + return new KafkaTemplate<>(paymentProducerFactory); + } + + private static Map boundProperties(Environment environment, String prefix) { + return new HashMap<>(Binder.get(environment) + .bind(prefix, Bindable.mapOf(String.class, Object.class)) + .orElse(Map.of())); + } +} diff --git a/src/main/java/com/digitalbank/paymentservice/configuration/PaymentTimeConfiguration.java b/src/main/java/com/digitalbank/paymentservice/configuration/PaymentTimeConfiguration.java index 2d7e259..df3982c 100644 --- a/src/main/java/com/digitalbank/paymentservice/configuration/PaymentTimeConfiguration.java +++ b/src/main/java/com/digitalbank/paymentservice/configuration/PaymentTimeConfiguration.java @@ -1,6 +1,8 @@ package com.digitalbank.paymentservice.configuration; +import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Clock; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -11,4 +13,10 @@ public class PaymentTimeConfiguration { Clock paymentClock() { return Clock.systemUTC(); } + + @Bean + @ConditionalOnMissingBean(ObjectMapper.class) + ObjectMapper paymentObjectMapper() { + return new ObjectMapper().findAndRegisterModules(); + } } diff --git a/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstruction.java b/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstruction.java index 754b4d8..13bff76 100644 --- a/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstruction.java +++ b/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstruction.java @@ -45,6 +45,7 @@ public PaymentInstruction fail(String reason, Instant now) { return this; } requirePending(); + reason = requireFailureReason(reason); return new PaymentInstruction( id, request, correlationId, PaymentInstructionStatus.FAILED, reason, createdAt, now); } @@ -61,4 +62,12 @@ private static String requireText(String value, String message) { } return value.trim(); } + + private static String requireFailureReason(String value) { + var reason = requireText(value, "Failure reason is required"); + if (reason.length() > 500) { + throw new IllegalArgumentException("Failure reason must be at most 500 characters"); + } + return reason; + } } diff --git a/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstructionRequest.java b/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstructionRequest.java index 8785c23..0ebc3e9 100644 --- a/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstructionRequest.java +++ b/src/main/java/com/digitalbank/paymentservice/domain/model/PaymentInstructionRequest.java @@ -13,6 +13,9 @@ public record PaymentInstructionRequest(String idempotencyKey, BigDecimal amount throw new IllegalArgumentException("Payment amount must be positive"); } amount = amount.stripTrailingZeros(); + if (amount.scale() > 4) { + throw new IllegalArgumentException("Payment amount must have no more than four decimal places"); + } currency = requireText(currency, "Payment currency is required").toUpperCase(Locale.ROOT); if (!currency.matches("[A-Z]{3}")) { throw new IllegalArgumentException("Payment currency must be a three-letter code"); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index dc03769..4d76ee2 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -20,3 +20,11 @@ server.port=${SERVER_PORT:8085} management.endpoints.web.exposure.include=health,info management.endpoint.health.probes.enabled=true + +payment.events.topic=${PAYMENT_EVENTS_TOPIC:payment.instruction.state.v1} +payment.events.batch-size=${PAYMENT_EVENTS_BATCH_SIZE:25} +payment.events.max-attempts=${PAYMENT_EVENTS_MAX_ATTEMPTS:5} +payment.events.retry-backoff=${PAYMENT_EVENTS_RETRY_BACKOFF:PT5S} +payment.events.lease=${PAYMENT_EVENTS_LEASE:PT30S} +payment.events.send-timeout=${PAYMENT_EVENTS_SEND_TIMEOUT:PT5S} +payment.events.poll-delay-ms=${PAYMENT_EVENTS_POLL_DELAY_MS:1000} diff --git a/src/main/resources/db/migration/V2__create_payment_instruction_outbox.sql b/src/main/resources/db/migration/V2__create_payment_instruction_outbox.sql new file mode 100644 index 0000000..a955c92 --- /dev/null +++ b/src/main/resources/db/migration/V2__create_payment_instruction_outbox.sql @@ -0,0 +1,54 @@ +create table payment_instruction_outbox ( + event_id uuid not null, + instruction_id uuid not null, + aggregate_id uuid not null, + event_type varchar(100) not null, + schema_version varchar(20) not null, + producer varchar(100) not null, + occurred_at timestamp with time zone not null, + correlation_id text not null, + causation_id text not null, + idempotency_key text not null, + amount numeric(19, 4) not null, + currency varchar(3) not null, + event_status varchar(30) not null, + failure_reason text, + payload jsonb not null, + publication_status varchar(20) not null default 'PENDING', + attempt_count integer not null default 0, + next_attempt_at timestamp with time zone not null, + claim_id uuid, + claim_until timestamp with time zone, + published_at timestamp with time zone, + last_error text, + created_at timestamp with time zone not null, + constraint pk_payment_instruction_outbox primary key (event_id), + constraint fk_payment_instruction_outbox_instruction foreign key (instruction_id) + references payment_instructions (id), + constraint uq_payment_instruction_outbox_instruction_status unique (instruction_id, event_status), + constraint ck_payment_instruction_outbox_event_type check (event_type = 'PaymentInstructionStateChanged.v1'), + constraint ck_payment_instruction_outbox_schema_version check (schema_version = '1.0.0'), + constraint ck_payment_instruction_outbox_producer check (producer = 'payment-service'), + constraint ck_payment_instruction_outbox_correlation_non_blank check (length(btrim(correlation_id)) > 0), + constraint ck_payment_instruction_outbox_causation_non_blank check (length(btrim(causation_id)) > 0), + constraint ck_payment_instruction_outbox_idempotency_non_blank check (length(btrim(idempotency_key)) > 0), + constraint ck_payment_instruction_outbox_amount_positive check (amount > 0), + constraint ck_payment_instruction_outbox_currency_format check (currency ~ '^[A-Z]{3}$'), + constraint ck_payment_instruction_outbox_event_status check (event_status in ('PENDING', 'COMPLETED', 'FAILED')), + constraint ck_payment_instruction_outbox_failure_reason check ( + (event_status = 'FAILED' and failure_reason is not null and length(btrim(failure_reason)) > 0) + or (event_status <> 'FAILED' and failure_reason is null) + ), + constraint ck_payment_instruction_outbox_publication_status check (publication_status in ('PENDING', 'PUBLISHED', 'FAILED')), + constraint ck_payment_instruction_outbox_attempt_count check (attempt_count >= 0), + constraint ck_payment_instruction_outbox_claim_pair check ((claim_id is null) = (claim_until is null)), + constraint ck_payment_instruction_outbox_published_at check ( + (publication_status = 'PUBLISHED' and published_at is not null) + or (publication_status <> 'PUBLISHED' and published_at is null) + ), + constraint ck_payment_instruction_outbox_timestamps check (occurred_at <= created_at) +); + +create index ix_payment_instruction_outbox_eligible + on payment_instruction_outbox (next_attempt_at, created_at) + where publication_status = 'PENDING'; diff --git a/src/test/java/com/digitalbank/paymentservice/PaymentInstructionApiIT.java b/src/test/java/com/digitalbank/paymentservice/PaymentInstructionApiIT.java index 28e68af..de61255 100644 --- a/src/test/java/com/digitalbank/paymentservice/PaymentInstructionApiIT.java +++ b/src/test/java/com/digitalbank/paymentservice/PaymentInstructionApiIT.java @@ -3,8 +3,10 @@ import static org.assertj.core.api.Assertions.assertThat; import com.digitalbank.paymentservice.application.port.in.CreatePaymentInstructionCommand; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutbox; import com.digitalbank.paymentservice.application.port.out.PaymentInstructionRepository; import com.digitalbank.paymentservice.application.service.PaymentInstructionService; +import com.digitalbank.paymentservice.application.service.PaymentInstructionStateEventFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.math.BigDecimal; @@ -13,6 +15,8 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.Set; import java.util.UUID; @@ -24,6 +28,7 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.postgresql.PostgreSQLContainer; @@ -49,6 +54,113 @@ class PaymentInstructionApiIT { @Autowired private PaymentInstructionRepository paymentInstructionRepository; + @Autowired + private PaymentInstructionOutbox paymentInstructionOutbox; + + @Autowired + private PaymentInstructionStateEventFactory paymentInstructionStateEventFactory; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Test + void persistsOnePendingOutboxEventWithTheInstructionPayload() { + var idempotencyKey = "payment-outbox-pending-" + UUID.randomUUID(); + var result = paymentInstructionService.register(new CreatePaymentInstructionCommand( + idempotencyKey, "correlation-outbox-pending", new BigDecimal("125.50"), "aed", "Outbox payment")); + + var rows = jdbcTemplate.queryForList( + "select event_id, event_type, correlation_id, causation_id, event_status, payload " + + "from payment_instruction_outbox where instruction_id = ?", + result.instructionId().value()); + + assertThat(rows).singleElement().satisfies(row -> { + assertThat(row.get("event_id")).isNotNull(); + assertThat(row.get("event_type")).isEqualTo("PaymentInstructionStateChanged.v1"); + assertThat(row.get("correlation_id")).isEqualTo("correlation-outbox-pending"); + assertThat(row.get("causation_id")).isEqualTo(idempotencyKey); + assertThat(row.get("event_status")).isEqualTo("PENDING"); + assertThat(row.get("payload").toString()) + .contains( + "PaymentInstructionStateChanged.v1", + result.instructionId().value().toString()); + }); + } + + @Test + void persistsExactlyOneEventForEachTerminalOutcome() { + var completed = paymentInstructionService.register(new CreatePaymentInstructionCommand( + "payment-outbox-completed-" + UUID.randomUUID(), + "correlation-outbox-completed", + new BigDecimal("10.00"), + "USD", + "Completed outbox payment")); + paymentInstructionService.complete(completed.instructionId()); + + var failed = paymentInstructionService.register(new CreatePaymentInstructionCommand( + "payment-outbox-failed-" + UUID.randomUUID(), + "correlation-outbox-failed", + new BigDecimal("20.00"), + "USD", + "Failed outbox payment")); + paymentInstructionService.fail(failed.instructionId(), "provider rejected payment"); + + assertThat(eventStatuses(completed.instructionId().value())).containsExactly("PENDING", "COMPLETED"); + assertThat(eventStatuses(failed.instructionId().value())).containsExactly("PENDING", "FAILED"); + var failedPayload = jdbcTemplate.queryForObject( + "select payload from payment_instruction_outbox where instruction_id = ? and event_status = 'FAILED'", + String.class, + failed.instructionId().value()); + assertThat(read(failedPayload).path("status").asText()).isEqualTo("FAILED"); + assertThat(read(failedPayload).path("failureReason").asText()).isEqualTo("provider rejected payment"); + assertThat(jdbcTemplate.queryForObject( + "select count(*) from payment_instruction_outbox where instruction_id = ? and event_status = 'FAILED'", + Integer.class, + failed.instructionId().value())) + .isEqualTo(1); + } + + @Test + void claimsPendingEventAndRecordsPublication() { + var instruction = paymentInstructionService.register(new CreatePaymentInstructionCommand( + "payment-outbox-publication-" + UUID.randomUUID(), + "correlation-outbox-publication", + new BigDecimal("30.00"), + "USD", + "Publication tracking")); + + var claimed = paymentInstructionOutbox.claimBatch(Instant.now(), 100, Duration.ofSeconds(30)); + var record = claimed.stream() + .filter(candidate -> candidate + .event() + .instructionId() + .equals(instruction.instructionId().value().toString())) + .findFirst() + .orElseThrow(); + + assertThat(record.attempts()).isZero(); + assertThat(record.claimId()).isNotNull(); + paymentInstructionOutbox.markPublished(record.event().eventId(), record.claimId(), Instant.now()); + + assertThat(jdbcTemplate.queryForMap( + "select publication_status, attempt_count, claim_id " + + "from payment_instruction_outbox where instruction_id = ?", + instruction.instructionId().value())) + .containsEntry("publication_status", "PUBLISHED") + .containsEntry("attempt_count", 1) + .containsEntry("claim_id", null); + } + + private List eventStatuses(UUID instructionId) { + return jdbcTemplate + .queryForList( + "select event_status from payment_instruction_outbox where instruction_id = ? order by created_at", + String.class, + instructionId) + .stream() + .toList(); + } + @Test void createsPaymentInstructionAndReplaysEquivalentRequest() throws Exception { var requestBody = """ @@ -273,7 +385,11 @@ void equivalentRetryFromFreshServiceInstanceReadsTheDurableInstruction() { key, "correlation-first", new BigDecimal("25.00"), "USD", "Durable payment"); var first = paymentInstructionService.register(command); - var freshService = new PaymentInstructionService(paymentInstructionRepository, Clock.systemUTC()); + var freshService = new PaymentInstructionService( + paymentInstructionRepository, + Clock.systemUTC(), + paymentInstructionOutbox, + paymentInstructionStateEventFactory); var replay = freshService.register(new CreatePaymentInstructionCommand( key, "correlation-retry", new BigDecimal("25.0"), "usd", "Durable payment")); diff --git a/src/test/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisherTest.java b/src/test/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisherTest.java new file mode 100644 index 0000000..b00608e --- /dev/null +++ b/src/test/java/com/digitalbank/paymentservice/adapter/out/kafka/PaymentInstructionEventPublisherTest.java @@ -0,0 +1,166 @@ +package com.digitalbank.paymentservice.adapter.out.kafka; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutbox; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutboxRecord; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionStateEvent; +import com.digitalbank.paymentservice.configuration.PaymentEventProperties; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.junit.jupiter.api.Test; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; + +class PaymentInstructionEventPublisherTest { + + private static final Instant NOW = Instant.parse("2026-09-06T19:00:00Z"); + + @Test + void publishesClaimedEventWithStableContractHeadersAndBoundedBatch() { + var outbox = new TestOutbox(List.of(record(0))); + var kafkaTemplate = new RecordingKafkaTemplate(); + var properties = new PaymentEventProperties(); + properties.setBatchSize(1); + var publisher = new PaymentInstructionEventPublisher( + outbox, kafkaTemplate, properties, Clock.fixed(NOW, ZoneOffset.UTC)); + + publisher.publishBatch(); + + var sent = kafkaTemplate.records.getFirst(); + assertThat(sent.topic()).isEqualTo("payment.instruction.state.v1"); + assertThat(sent.key()).isEqualTo(outbox.event.aggregateId()); + assertThat(sent.value()).isEqualTo(outbox.event.payload()); + assertThat(sent.headers().lastHeader("event-id").value()) + .isEqualTo(outbox.event.eventId().toString().getBytes()); + assertThat(sent.headers().lastHeader("correlation-id").value()).isEqualTo("correlation-001".getBytes()); + assertThat(sent.headers().lastHeader("causation-id").value()).isEqualTo("command-001".getBytes()); + assertThat(sent.headers().lastHeader("producer").value()).isEqualTo("payment-service".getBytes()); + assertThat(sent.headers().lastHeader("schema-version").value()).isEqualTo("1.0.0".getBytes()); + assertThat(sent.headers().lastHeader("occurred-at").value()) + .isEqualTo(NOW.toString().getBytes()); + assertThat(outbox.published).containsExactly(outbox.event.eventId()); + } + + @Test + void retriesBrokerFailureAndMarksTheEventFailedAfterTheBoundedAttempts() { + var first = record(0); + var second = new PaymentInstructionOutboxRecord(first.event(), 1, UUID.randomUUID(), NOW.plusSeconds(30)); + var outbox = new TestOutbox(List.of(first, second)); + var kafkaTemplate = new RecordingKafkaTemplate(); + kafkaTemplate.failure = new IllegalStateException("broker unavailable"); + var properties = new PaymentEventProperties(); + properties.setMaxAttempts(2); + properties.setRetryBackoff(Duration.ZERO); + var publisher = new PaymentInstructionEventPublisher( + outbox, kafkaTemplate, properties, Clock.fixed(NOW, ZoneOffset.UTC)); + + publisher.publishBatch(); + publisher.publishBatch(); + + assertThat(outbox.failureAttempts).containsExactly(1, 2); + assertThat(outbox.failureMaxAttempts).containsExactly(2, 2); + assertThat(outbox.failureErrors).allMatch(error -> error.contains("broker unavailable")); + assertThat(kafkaTemplate.records).hasSize(2).allSatisfy(sent -> assertThat(sent.value()) + .isEqualTo(first.event().payload())); + assertThat(kafkaTemplate.records) + .extracting(sent -> sent.headers().lastHeader("event-id").value()) + .containsOnly(first.event().eventId().toString().getBytes()); + } + + private static PaymentInstructionOutboxRecord record(int attempts) { + var id = UUID.randomUUID(); + var event = new PaymentInstructionStateEvent( + id, + "PaymentInstructionStateChanged.v1", + "1.0.0", + "payment-service", + NOW, + "instruction-001", + "correlation-001", + "command-001", + "instruction-001", + "idempotency-001", + "10.00", + "USD", + "PENDING", + null, + "{\"eventId\":\"" + id + "\"}", + Map.of( + "event-id", id.toString(), + "correlation-id", "correlation-001", + "causation-id", "command-001", + "producer", "payment-service", + "schema-version", "1.0.0", + "occurred-at", NOW.toString())); + return new PaymentInstructionOutboxRecord(event, attempts, UUID.randomUUID(), NOW.plusSeconds(30)); + } + + private static final class TestOutbox implements PaymentInstructionOutbox { + + private final PaymentInstructionStateEvent event; + private final List records; + private final List published = new ArrayList<>(); + private final List failureAttempts = new ArrayList<>(); + private final List failureMaxAttempts = new ArrayList<>(); + private final List failureErrors = new ArrayList<>(); + private int claims; + + private TestOutbox(List records) { + this.records = records; + this.event = records.get(0).event(); + } + + @Override + public void save(PaymentInstructionStateEvent event) {} + + @Override + public List claimBatch(Instant now, int batchSize, Duration lease) { + return claims < records.size() ? List.of(records.get(claims++)) : List.of(); + } + + @Override + public void markPublished(UUID eventId, UUID claimId, Instant publishedAt) { + published.add(eventId); + } + + @Override + public void markFailedOrRetry( + UUID eventId, + UUID claimId, + int attempts, + int maxAttempts, + Instant now, + Duration retryBackoff, + String error) { + failureAttempts.add(attempts); + failureMaxAttempts.add(maxAttempts); + failureErrors.add(error); + } + } + + private static final class RecordingKafkaTemplate extends KafkaTemplate { + + private final List> records = new ArrayList<>(); + private RuntimeException failure; + + private RecordingKafkaTemplate() { + super(new DefaultKafkaProducerFactory<>(Map.of("bootstrap.servers", "unused:9092"))); + } + + @Override + public CompletableFuture> send(ProducerRecord record) { + records.add(record); + return failure == null ? CompletableFuture.completedFuture(null) : CompletableFuture.failedFuture(failure); + } + } +} diff --git a/src/test/java/com/digitalbank/paymentservice/application/service/PaymentInstructionServiceTest.java b/src/test/java/com/digitalbank/paymentservice/application/service/PaymentInstructionServiceTest.java index 3862642..40f7266 100644 --- a/src/test/java/com/digitalbank/paymentservice/application/service/PaymentInstructionServiceTest.java +++ b/src/test/java/com/digitalbank/paymentservice/application/service/PaymentInstructionServiceTest.java @@ -6,15 +6,21 @@ import com.digitalbank.paymentservice.adapter.out.persistence.InMemoryPaymentInstructionRepository; import com.digitalbank.paymentservice.application.port.in.CreatePaymentInstructionCommand; import com.digitalbank.paymentservice.application.port.in.PaymentInstructionResult; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionOutbox; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionStateEvent; +import com.digitalbank.paymentservice.application.port.out.PaymentInstructionTransitionResult; import com.digitalbank.paymentservice.domain.exception.PaymentInstructionIdempotencyConflictException; import com.digitalbank.paymentservice.domain.exception.PaymentInstructionNotFoundException; import com.digitalbank.paymentservice.domain.model.PaymentInstructionId; import com.digitalbank.paymentservice.domain.model.PaymentInstructionStatus; import java.math.BigDecimal; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.List; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; @@ -29,8 +35,61 @@ class PaymentInstructionServiceTest { private static final Instant NOW = Instant.parse("2026-08-30T10:15:30Z"); - private final PaymentInstructionService service = - new PaymentInstructionService(new InMemoryPaymentInstructionRepository(), Clock.fixed(NOW, ZoneOffset.UTC)); + private final CapturingOutbox outbox = new CapturingOutbox(); + private final PaymentInstructionStateEventFactory eventFactory = new PaymentInstructionStateEventFactory( + new com.fasterxml.jackson.databind.ObjectMapper().findAndRegisterModules()); + private final PaymentInstructionService service = new PaymentInstructionService( + new InMemoryPaymentInstructionRepository(), Clock.fixed(NOW, ZoneOffset.UTC), outbox, eventFactory); + + @Test + void creationWritesOnePendingStateEventWithGovernedMetadata() { + var result = service.register(command("payment-event-001", "AED", "125.50")); + + assertThat(outbox.events()).singleElement().satisfies(event -> { + assertThat(event.eventId()).isNotNull(); + assertThat(event.eventType()).isEqualTo("PaymentInstructionStateChanged.v1"); + assertThat(event.schemaVersion()).isEqualTo("1.0.0"); + assertThat(event.producer()).isEqualTo("payment-service"); + assertThat(event.occurredAt()).isEqualTo(NOW); + assertThat(event.aggregateId()) + .isEqualTo(result.instructionId().value().toString()); + assertThat(event.instructionId()) + .isEqualTo(result.instructionId().value().toString()); + assertThat(event.correlationId()).isEqualTo("correlation-001"); + assertThat(event.causationId()).isEqualTo("payment-event-001"); + assertThat(event.idempotencyKey()).isEqualTo("payment-event-001"); + assertThat(event.amount()).isEqualTo("125.5"); + assertThat(event.currency()).isEqualTo("AED"); + assertThat(event.status()).isEqualTo("PENDING"); + assertThat(event.failureReason()).isNull(); + assertThat(event.payload()) + .contains( + "PaymentInstructionStateChanged.v1", + result.instructionId().value().toString()); + }); + } + + @Test + void terminalTransitionWritesOneTerminalStateEventAndReplayDoesNotDuplicateIt() { + var created = service.register(command("payment-event-002", "USD", "10.00")); + + service.complete(created.instructionId()); + service.complete(created.instructionId()); + + assertThat(outbox.events()) + .extracting(PaymentInstructionStateEvent::status) + .containsExactly("PENDING", "COMPLETED"); + assertThat(outbox.events().get(1).causationId()) + .isEqualTo(created.instructionId().value() + ":COMPLETED"); + } + + @Test + void equivalentCreateReplayDoesNotWriteAnotherStateEvent() { + service.register(command("payment-event-003", "USD", "10.00")); + service.register(command("payment-event-003", "USD", "10.00")); + + assertThat(outbox.events()).hasSize(1); + } @Test void repeatedEquivalentRequestReturnsOriginalInstructionAsReplay() { @@ -131,7 +190,8 @@ void concurrentEquivalentRequestsCreateOneInstruction() throws Exception { @Test void concurrentCompletionAndFailureAllowOnlyOneTerminalTransition() throws Exception { var repository = new CoordinatedTransitionRepository(); - var racingService = new PaymentInstructionService(repository, Clock.fixed(NOW, ZoneOffset.UTC)); + var racingService = + new PaymentInstructionService(repository, Clock.fixed(NOW, ZoneOffset.UTC), outbox, eventFactory); var created = racingService.register(command("payment-race", "USD", "10.00")); repository.coordinate(created.instructionId()); var barrier = new CyclicBarrier(2); @@ -194,6 +254,39 @@ private static CreatePaymentInstructionCommand command(String key, String curren key, "correlation-001", new BigDecimal(amount), currency, "customer payment"); } + private static final class CapturingOutbox implements PaymentInstructionOutbox { + + private final List events = new ArrayList<>(); + + @Override + public synchronized void save(PaymentInstructionStateEvent event) { + events.add(event); + } + + @Override + public List claimBatch( + Instant now, int batchSize, Duration lease) { + return List.of(); + } + + @Override + public void markPublished(UUID eventId, UUID claimId, Instant publishedAt) {} + + @Override + public void markFailedOrRetry( + UUID eventId, + UUID claimId, + int attempts, + int maxAttempts, + Instant now, + Duration retryBackoff, + String error) {} + + synchronized List events() { + return List.copyOf(events); + } + } + private static final class CoordinatedTransitionRepository extends InMemoryPaymentInstructionRepository { private volatile PaymentInstructionId coordinatedInstructionId; @@ -220,7 +313,7 @@ void releaseTransitions() { } @Override - public com.digitalbank.paymentservice.domain.model.PaymentInstruction transition( + public PaymentInstructionTransitionResult transition( PaymentInstructionId instructionId, java.util.function.UnaryOperator transition) { diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 13d48dd..3dda239 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -1,2 +1,3 @@ spring.application.name=payment-service spring.cloud.config.enabled=false +payment.events.poll-delay-ms=600000