Arcadia Editions Modulith: Spring Boot Java
Section titled “Arcadia Editions Modulith: Spring Boot Java”The six Arcadia Editions bounded contexts (orders checkout, catalog inventory, catalog products, payments processing, fulfillment shipping, notifications consumer) as one Java + Spring Boot modular monolith: one Spring Modulith module per context, in-process events with a transactional outbox.
- The structure is generated from the ZDL models with ZenWave SDK.
- The behavior of the place-order flow was implemented with zenwave-sdd: models reviewed by a human in the loop (HITL), implementation done by coding agents away from keyboard (AFK).
Source code: arcadia-editions-modulith-service-java. Models: arcadia-editions-modulith-api.
| Area | Technology |
|---|---|
| Language | Java 25 |
| Framework | Spring Boot 4.2.x |
| Modular monolith | Spring Modulith 2.2.x + JDBC event publication registry (no broker) |
| Persistence | Spring Data JPA + PostgreSQL |
| DDD / Architecture | jMolecules + ArchUnit |
| Code generation | ZenWave SDK 2.8.x, openapi-generator-maven-plugin |
Modules
Section titled “Modules”One module per bounded context. Only orders.checkout exposes an API to the outside (REST, generated from OpenAPI). The other modules react to events published in-process, and three steps call another module directly (startOrderCheckout, confirmOrder and expireReservation). catalog.products is not part of the place-order flow. The arrows come from @listener and @calls in the models.
Domain models
Section titled “Domain models”The models are not in the service repository. They live in arcadia-editions-modulith-api, one ZDL per bounded context, and are released as a Maven artifact (service-all) that zenwave-scripts.zw imports.
The aggregate
Section titled “The aggregate”Start with the data. This is the Order aggregate of Orders Checkout, with its lifecycle:
orders-checkout-domain-model.zdl: Order aggregate
@aggregate@lifecycle(field: status, initial: CREATED)entity Order(checkout_order) { orderId String required unique status OrderStatus required /** Customer snapshot taken at checkout (there is no customers bounded context yet). */ customerId String required customerEmail String required maxlength(254) paymentMethodId String required @json items OrderItem[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } totalAmount BigDecimal required currency String required maxlength(3) createdAt Instant confirmedAt Instant cancelledAt Instant cancellationReason String}Its rules and @invariant: the last-mile spec
Section titled “Its rules and @invariant: the last-mile spec”Structure is what the generator can build: entities, commands, events, state transitions, listeners. Behavior is the last mile. ZDL captures it in rules blocks, written in natural language. An @invariant must always hold for the aggregate. A plain rule is a policy of the service. These sentences are the spec a coding agent implements and tests against. These are the rules of Order:
orders-checkout-domain-model.zdl: rules (Order)
rules (Order) { @invariant orderTotal "totalAmount equals the sum of quantity * unitPrice over all items, in the order's currency" @invariant checkoutSnapshotFixed "customerId, customerEmail, paymentMethodId, items, shippingAddress, totalAmount and currency are fixed at checkout and never change" @invariant orderOnlyWithReservedStock "An Order exists only if its stock was reserved: StockUnavailable persists nothing" @invariant cancelledIsFinal "CANCELLED is terminal: no command takes an Order out of it" @invariant cancelledNeverConfirmed "A CANCELLED Order is never confirmed: a late authorization is answered with OrderConfirmationRejected" @invariant confirmationData "confirmedAt is set exactly when the Order reaches CONFIRMED and is never cleared" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Order is CANCELLED" singleCancellation "An Order is cancelled at most once: a redelivered cancellation is a no-op with no event"}Service-level rules describe how the commands collaborate with other modules:
orders-checkout-domain-model.zdl: service and rules
@rest("/orders")service OrdersCheckoutService for (Order) {
/** Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). */ @post("/start-checkout") @transition(to: CREATED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.reserveStock) startOrderCheckout(StartOrderCheckoutInput) Order withEvents [OrderCreated | StockUnavailable]
/** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. */ @listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @listener(zdl: CatalogInventoryZdl, event: StockReleased) @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelled
@get("/{id}") getOrder(id) Order?}
rules { reserveBeforePersist "startOrderCheckout reserves stock (InventoryService.reserveStock) before persisting the Order; all lines are reserved or none" confirmOnlyWithHeldStock "An Order is confirmed only if InventoryService.confirmStockReservation answers CONFIRMED: every line is still RESERVED" rejectedConfirmationVoids "A confirmation refused because the Order is CANCELLED or its stock is NOT_HELD emits OrderConfirmationRejected, so payments voids the authorization" cancellationOwner "OrdersCheckout is the only owner of OrderCancelled: it cancels only in reaction to StockReleased" cancellationReasonFromRelease "cancellationReason is the StockReleaseReason carried by StockReleased" orderCreatedCarriesAmount "OrderCreated.amount and currency are Order.totalAmount and currency: they are the amount payments authorizes"}The same pattern in Catalog Inventory, aggregate first and then its rules:
catalog-inventory-domain-model.zdl: StockReservation aggregate and rules
@aggregate@lifecycle(field: status, initial: RESERVED)entity StockReservation { reservationId String required unique /** One reservation per order line: an order has as many reservations as items. */ orderId String required sku String required quantity Integer required status ReservationStatus required reservedAt Instant required expiresAt Instant required confirmedAt Instant releasedAt Instant releaseReason StockReleaseReason}
rules (StockReservation) { @invariant oneReservationPerLine "One StockReservation per order line: (orderId, sku) is unique" @invariant positiveQuantity "quantity is at least 1" @invariant reservationWindow "expiresAt is reservedAt + 10 minutes" @invariant releasedIsFinal "RELEASED is terminal: a released line never goes back to RESERVED or CONFIRMED" @invariant confirmationData "confirmedAt is set exactly when the line reaches CONFIRMED" @invariant releaseData "releasedAt and releaseReason are set if and only if the line is RELEASED" expiryReleasesOnlyReserved "The reservation timer releases only RESERVED lines, with reason RESERVATION_EXPIRED; it never touches a CONFIRMED line" expiryOnlyWithoutPayment "The timer releases nothing once a payment exists for the order: payment owns the end" releaseReasonFromEventType "releaseReason comes from the type of the triggering event, never from its free-text reason"}catalog-inventory-domain-model.zdl: service rules
rules { @invariant noOversell "A line is reserved only if InventoryPosition.availableQuantity of its sku covers its quantity: stock is never oversold" allOrNothingReservation "reserveStock reserves every line of the order or none: if one sku is short, nothing is reserved and the answer is StockUnavailableResult" allOrNothingConfirmation "confirmStockReservation confirms every line of the order or none: NOT_HELD when any line is not RESERVED" @invariant reservedMatchesPosition "InventoryPosition.reservedQuantity of a sku is the sum of quantity over its RESERVED lines" @invariant soldMatchesPosition "InventoryPosition.soldQuantity of a sku includes the quantity of its CONFIRMED lines" reservationMovesStock "Reserving moves quantity from available to reserved; confirming moves it from reserved to sold; releasing returns it to available"}The rules of the whole flow, across contexts, are in place-order-flow.zfl.
All the models
Section titled “All the models”orders-checkout-domain-model.zdl
config { id "urn:com.arcadiaeditions:orders:checkout" version "0.0.0" title "Arcadia Editions - Orders Checkout" moduleBasePackage "com.arcadiaeditions.orders.checkout" persistence jpa layout CleanHexagonalProjectLayout
plugins { /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { idType integer idTypeFormat int64 openapiOverlayFiles "./orders-checkout-openapi-overlay.yml" targetFile "./orders-checkout-openapi.yml" } }}
apis { zdl client PaymentsProcessingZdl "./payments-processing-domain-model.zdl" zdl client CatalogInventoryZdl "./catalog-inventory-domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: CREATED)entity Order(checkout_order) { orderId String required unique status OrderStatus required /** Customer snapshot taken at checkout (there is no customers bounded context yet). */ customerId String required customerEmail String required maxlength(254) paymentMethodId String required @json items OrderItem[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } totalAmount BigDecimal required currency String required maxlength(3) createdAt Instant confirmedAt Instant cancelledAt Instant cancellationReason String}
rules (Order) { @invariant orderTotal "totalAmount equals the sum of quantity * unitPrice over all items, in the order's currency" @invariant checkoutSnapshotFixed "customerId, customerEmail, paymentMethodId, items, shippingAddress, totalAmount and currency are fixed at checkout and never change" @invariant orderOnlyWithReservedStock "An Order exists only if its stock was reserved: StockUnavailable persists nothing" @invariant cancelledIsFinal "CANCELLED is terminal: no command takes an Order out of it" @invariant cancelledNeverConfirmed "A CANCELLED Order is never confirmed: a late authorization is answered with OrderConfirmationRejected" @invariant confirmationData "confirmedAt is set exactly when the Order reaches CONFIRMED and is never cleared" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Order is CANCELLED" singleCancellation "An Order is cancelled at most once: a redelivered cancellation is a no-op with no event"}
enum OrderStatus { CREATED(1) CONFIRMED(2) CANCELLED(3)}
input StartOrderCheckoutInput { customerId String required customerEmail String required maxlength(254) paymentMethodId String required currency String required maxlength(3) items OrderItemInput[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } shippingAddress ShippingAddressInput required { name String required line1 String required line2 String city String required region String postalCode String required country String required }}
input ConfirmOrderInput { orderId String required}
input CancelOrderInput { orderId String required /** From StockReleased.reason (StockReleaseReason name). */ reason String required}
@rest("/orders")service OrdersCheckoutService for (Order) {
/** Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). */ @post("/start-checkout") @transition(to: CREATED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.reserveStock) startOrderCheckout(StartOrderCheckoutInput) Order withEvents [OrderCreated | StockUnavailable]
/** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. */ @listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @listener(zdl: CatalogInventoryZdl, event: StockReleased) @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelled
@get("/{id}") getOrder(id) Order?}
rules { reserveBeforePersist "startOrderCheckout reserves stock (InventoryService.reserveStock) before persisting the Order; all lines are reserved or none" confirmOnlyWithHeldStock "An Order is confirmed only if InventoryService.confirmStockReservation answers CONFIRMED: every line is still RESERVED" rejectedConfirmationVoids "A confirmation refused because the Order is CANCELLED or its stock is NOT_HELD emits OrderConfirmationRejected, so payments voids the authorization" cancellationOwner "OrdersCheckout is the only owner of OrderCancelled: it cancels only in reaction to StockReleased" cancellationReasonFromRelease "cancellationReason is the StockReleaseReason carried by StockReleased" orderCreatedCarriesAmount "OrderCreated.amount and currency are Order.totalAmount and currency: they are the amount payments authorizes"}
// @asyncapi({ channel: "order-created-event-v1", topic: "orders-checkout.order-created.event.avro.v1" })event OrderCreated { orderId String version Integer customerId String customerEmail String paymentMethodId String /** Order total (Order.totalAmount), named to match AuthorizePaymentInput. */ amount BigDecimal currency String}
// @asyncapi({ channel: "stock-unavailable-event-v1", topic: "orders-checkout.stock-unavailable.event.avro.v1" })event StockUnavailable { orderId String customerId String customerEmail String unavailableItems StockUnavailableItem[] { sku String requestedQuantity Integer availableQuantity Integer }}
// @asyncapi({ channel: "order-confirmed-event-v1", topic: "orders-checkout.order-confirmed.event.avro.v1" })event OrderConfirmed { orderId String version Integer customerId String confirmedAt Instant items OrderConfirmedItem[] { sku String quantity Integer } shippingAddress OrderConfirmedShippingAddress { name String line1 String line2 String city String region String postalCode String country String }}
// @asyncapi({ channel: "order-cancelled-event-v1", topic: "orders-checkout.order-cancelled.event.avro.v1" })event OrderCancelled { orderId String version Integer customerId String customerEmail String /** Order.cancellationReason */ reason String cancelledAt Instant}
/** The authorization arrived for an order that is cancelled or whose stock is no longer held; payments voids it. */// @asyncapi({ channel: "order-confirmation-rejected-event-v1", topic: "orders-checkout.order-confirmation-rejected.event.avro.v1" })event OrderConfirmationRejected { orderId String customerId String /** ORDER_CANCELLED or STOCK_NOT_HELD */ reason String rejectedAt Instant}catalog-inventory-domain-model.zdl
config { id "urn:com.arcadiaeditions:catalog:inventory" version "0.0.0" title "Arcadia Editions - Catalog Inventory" moduleBasePackage "com.arcadiaeditions.catalog.inventory" persistence jpa layout LayeredProjectLayout
plugins {// /** Generates an OpenAPI 3.0 specification from this ZDL model. */// ZDLToOpenAPIPlugin {// idType integer// idTypeFormat int64// targetFile "./catalog-inventory-openapi.yml"// } }}
apis { zdl client PaymentsProcessingZdl "./payments-processing-domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: RESERVED)entity StockReservation { reservationId String required unique /** One reservation per order line: an order has as many reservations as items. */ orderId String required sku String required quantity Integer required status ReservationStatus required reservedAt Instant required expiresAt Instant required confirmedAt Instant releasedAt Instant releaseReason StockReleaseReason}
rules (StockReservation) { @invariant oneReservationPerLine "One StockReservation per order line: (orderId, sku) is unique" @invariant positiveQuantity "quantity is at least 1" @invariant reservationWindow "expiresAt is reservedAt + 10 minutes" @invariant releasedIsFinal "RELEASED is terminal: a released line never goes back to RESERVED or CONFIRMED" @invariant confirmationData "confirmedAt is set exactly when the line reaches CONFIRMED" @invariant releaseData "releasedAt and releaseReason are set if and only if the line is RELEASED" expiryReleasesOnlyReserved "The reservation timer releases only RESERVED lines, with reason RESERVATION_EXPIRED; it never touches a CONFIRMED line" expiryOnlyWithoutPayment "The timer releases nothing once a payment exists for the order: payment owns the end" releaseReasonFromEventType "releaseReason comes from the type of the triggering event, never from its free-text reason"}
enum ReservationStatus { RESERVED(1) RELEASED(2) CONFIRMED(3)}
enum StockReleaseReason { PAYMENT_DECLINED(1) PAYMENT_RETRY_EXHAUSTED(2) PAYMENT_VOIDED(3) PAYMENT_VOID_FAILED(4) RESERVATION_EXPIRED(5)}
input ReserveStockInput { orderId String required items ReserveStockItemInput[] required minlength(1) { sku String required quantity Integer required min(1) }}
/** Confirms every reservation of the order. */input ConfirmStockReservationInput { orderId String required}
/** Releases every reservation of the order. */input ReleaseStockInput { orderId String required /** Set by the listener from the triggering event type; never from the event's free-text reason. */ reason StockReleaseReason required}
/** Expires every RESERVED reservation of the order. */input ExpireReservationInput { orderId String required}
enum ConfirmStockReservationOutcome { CONFIRMED(1) NOT_HELD(2)}
/** Exactly one of `confirmed` / `notHeld` is set, according to `outcome`. */output ConfirmStockReservationResult { outcome ConfirmStockReservationOutcome required confirmed StockReservationConfirmedResult notHeld StockReservationNotHeldResult}
output StockReservationConfirmedResult { orderId String confirmedAt Instant}
/** Some line of the order is not RESERVED (released by the timer). Nothing is confirmed. */output StockReservationNotHeldResult { orderId String}
enum ReserveStockOutcome { RESERVED(1) UNAVAILABLE(2)}
/** * Wrapper for the two ZFL responses of reserveStock (ZDL has no union return type). * Exactly one of `reserved` / `unavailable` is set, according to `outcome`. */output ReserveStockResult { outcome ReserveStockOutcome required reserved StockReservedResult unavailable StockUnavailableResult}
output StockReservedResult { orderId String expiresAt Instant reservations StockReservedLine[] { reservationId String sku String quantity Integer reservedAt Instant }}
output StockUnavailableResult { orderId String unavailableItems StockUnavailableLine[] { sku String requestedQuantity Integer availableQuantity Integer }}
//@rest("/inventory")service InventoryService for (StockReservation) {
// @post("/reservations/reserve") @transition(to: RESERVED) reserveStock(ReserveStockInput) ReserveStockResult
/** The type of the triggering event sets the reason. No-op, no event, when already RELEASED. */ @listener(zdl: PaymentsProcessingZdl, event: PaymentDeclined) @listener(zdl: PaymentsProcessingZdl, event: PaymentRetryExhausted) @listener(zdl: PaymentsProcessingZdl, event: PaymentVoided) @listener(zdl: PaymentsProcessingZdl, event: PaymentVoidFailed) @transition(from: [RESERVED, CONFIRMED], to: RELEASED) releaseStock(ReleaseStockInput) StockReservation[] withEvents StockReleased
/** * Reservation timer, 10 minutes after OrderCreated. No-op, no event, when no line of the order * is RESERVED. Releases them (RESERVATION_EXPIRED) only when payments answers NO_PAYMENT; * on STARTED, payment owns the end and nothing happens. */ @timer(api: SchedulerApi, channel: "reservation-expired-event-v1") @calls(zdl: PaymentsProcessingZdl, command: PaymentsProcessingService.getPaymentStatus) @transition(from: RESERVED, to: RELEASED) expireReservation(ExpireReservationInput) StockReservation[] withEvents StockReleased
// @post("/reservations/confirm") /** Returns CONFIRMED with no change when every line is already CONFIRMED (redelivery). */ @transition(from: RESERVED, to: CONFIRMED) confirmStockReservation(ConfirmStockReservationInput) ConfirmStockReservationResult withEvents StockReservationConfirmed}
rules { @invariant noOversell "A line is reserved only if InventoryPosition.availableQuantity of its sku covers its quantity: stock is never oversold" allOrNothingReservation "reserveStock reserves every line of the order or none: if one sku is short, nothing is reserved and the answer is StockUnavailableResult" allOrNothingConfirmation "confirmStockReservation confirms every line of the order or none: NOT_HELD when any line is not RESERVED" @invariant reservedMatchesPosition "InventoryPosition.reservedQuantity of a sku is the sum of quantity over its RESERVED lines" @invariant soldMatchesPosition "InventoryPosition.soldQuantity of a sku includes the quantity of its CONFIRMED lines" reservationMovesStock "Reserving moves quantity from available to reserved; confirming moves it from reserved to sold; releasing returns it to available"}
// @asyncapi({ channel: "stock-released-event-v1", topic: "catalog-inventory.stock-released.event.avro.v1" })event StockReleased { orderId String reason StockReleaseReason releasedAt Instant items StockReleasedItem[] { reservationId String sku String quantity Integer }}
/** Published on purpose (inventory projections); no step of place-order-flow consumes it. */// @asyncapi({ channel: "stock-reservation-confirmed-event-v1", topic: "catalog-inventory.stock-reservation-confirmed.event.avro.v1" })event StockReservationConfirmed { orderId String confirmedAt Instant items StockReservationConfirmedItem[] { reservationId String sku String quantity Integer }}
//--- backoffice ----
@aggregateentity InventoryPosition { sku String required unique availableQuantity Integer required reservedQuantity Integer required soldQuantity Integer required}
rules (InventoryPosition) { @invariant oneSkuOnePosition "One InventoryPosition per sku" @invariant nonNegativeQuantities "availableQuantity, reservedQuantity and soldQuantity are never negative" adjustmentKeepsNonNegative "adjustStock is refused when it would make availableQuantity negative" positiveIntake "receiveStock adds a positive quantity to availableQuantity" adjustmentHasReason "Every adjustment carries a StockAdjustmentReason and is published as StockAdjusted"}
input CreateInventoryPositionInput { sku String required initialQuantity Integer required}
input ReceiveStockInput { sku String required quantity Integer required reason String reference String}
input AdjustStockInput { sku String required quantityDelta Integer required reason StockAdjustmentReason required reference String}
enum StockAdjustmentReason { DAMAGED(1) LOST(2) FOUND(3) MANUAL_CORRECTION(4) RETURNED(5)}
@rest("/inventory")service InventoryBackofficeService for (InventoryPosition) {
@post("/positions") createInventoryPosition(CreateInventoryPositionInput) InventoryPosition
@post("/{sku}/stock-intakes") receiveStock(ReceiveStockInput) InventoryPosition withEvents StockReceived
@post("/{sku}/adjustments") adjustStock(AdjustStockInput) InventoryPosition withEvents StockAdjusted}
rules { @invariant limitedEdition "availableQuantity + reservedQuantity + soldQuantity of a sku never exceeds the editionSize of its Product" intakeOnlyThroughBackoffice "Stock enters or leaves the pool outside an order only through receiveStock and adjustStock"}
// @asyncapi({ channel: "stock-received-event-v1", topic: "catalog-inventory.stock-received.event.avro.v1" })event StockReceived { sku String quantity Integer availableQuantity Integer reservedQuantity Integer soldQuantity Integer reason String reference String receivedAt Instant}
// @asyncapi({ channel: "stock-adjusted-event-v1", topic: "catalog-inventory.stock-adjusted.event.avro.v1" })event StockAdjusted { sku String quantityDelta Integer availableQuantity Integer reservedQuantity Integer soldQuantity Integer reason StockAdjustmentReason reference String adjustedAt Instant}payments-processing-domain-model.zdl
config { id "urn:com.arcadiaeditions:payments:processing" version "0.0.0" title "Arcadia Editions - Payments Processing" moduleBasePackage "com.arcadiaeditions.payments.processing" persistence jpa layout HexagonalProjectLayout
plugins {// /** Generates an OpenAPI 3.0 specification from this ZDL model. */// ZDLToOpenAPIPlugin {// idType integer// idTypeFormat int64// targetFile "./payments-processing-openapi.yml"// } }}
apis { zdl client OrdersCheckoutZdl "./orders-checkout-domain-model.zdl" zdl client FulfillmentShippingZdl "./fulfillment-shipping-domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: AUTHORIZATION_REQUESTED)entity Payment { orderId String required unique customerId String required paymentMethodId String required /** Carried so PaymentCaptured can drive the order confirmation e-mail. */ customerEmail String required amount BigDecimal required currency String required status PaymentStatus required providerReference String attemptCount Integer required authorizedAt Instant declinedAt Instant failedAt Instant capturedAt Instant voidedAt Instant voidFailedAt Instant failureReason String}
rules (Payment) { @invariant onePaymentPerOrder "At most one Payment per order: authorizePayment never creates a second one, whatever the state of the first" @invariant amountFixed "amount, currency, paymentMethodId and orderId never change after creation" @invariant attemptBounds "attemptCount is between 1 and 3" @invariant attemptsOnlyGrow "attemptCount only grows, by one, and only on reauthorizePayment" @invariant terminalStates "DECLINED, RETRY_EXHAUSTED, CAPTURED, VOIDED and VOID_FAILED are terminal" @invariant capturedNeverVoided "A CAPTURED Payment is never voided: a void applies only to AUTHORIZED or CAPTURE_FAILED" @invariant captureOnlyAuthorized "Only an AUTHORIZED Payment is captured, for its whole amount" @invariant stateTimestamps "Each of authorizedAt, declinedAt, failedAt, capturedAt, voidedAt and voidFailedAt is set when the Payment enters that state" declineNotRetried "A hard decline is never retried: the customer must act" retryOnlyCurrentAttempt "retryPayment and reauthorizePayment act only when the Payment is FAILED and input.attemptCount equals attemptCount; otherwise no-op, no event" retryBackoff "Backoff before attempt 2 is 5 seconds, before attempt 3 is 15 seconds; the third failure is RETRY_EXHAUSTED" processorTimeout "A processor call that takes more than 30 seconds is a failure (PaymentFailed)" inFlightVisible "AUTHORIZATION_REQUESTED is committed before calling the processor, so an attempt in flight is visible to getPaymentStatus"}
enum PaymentStatus { AUTHORIZATION_REQUESTED(1) AUTHORIZED(2) DECLINED(3) FAILED(4) RETRY_EXHAUSTED(5) CAPTURED(6) CAPTURE_FAILED(7) VOIDED(8) /** The processor refused the void; ops release the hold by hand. Terminal. */ VOID_FAILED(9)}
input AuthorizePaymentInput { orderId String required customerId String required customerEmail String required amount BigDecimal required currency String required paymentMethodId String required}
input RetryPaymentInput { orderId String required /** PaymentFailed.attemptCount: the attempt that failed. */ attemptCount Integer required}
input ReauthorizePaymentInput { orderId String required /** PaymentRetried.attemptCount: equals the failed attempt; reauthorize increments it. */ attemptCount Integer required}
input GetPaymentStatusInput { orderId String required}
enum GetPaymentStatusOutcome { NO_PAYMENT(1) STARTED(2)}
/** Exactly one of `noPayment` / `started` is set, according to `outcome`. */output GetPaymentStatusResult { outcome GetPaymentStatusOutcome required noPayment NoPaymentResult started PaymentStartedResult}
output NoPaymentResult { orderId String}
output PaymentStartedResult { orderId String status PaymentStatus}
/** The payment is resolved by orderId (Payment.orderId is unique); fulfillment events carry no paymentId. */input CapturePaymentInput { orderId String required}
/** The payment is resolved by orderId (Payment.orderId is unique); fulfillment events carry no paymentId. */input VoidPaymentInput { orderId String required reason String required}
//@rest("/payments")service PaymentsProcessingService for (Payment) {
/** * Creation only: no-op when a Payment for orderId exists, in any state (supersedes P-01 D). * Saves AUTHORIZATION_REQUESTED (attemptCount = 1) and commits before calling the processor, * so getPaymentStatus sees a call in flight; then saves the outcome. * The processor call times out after 30 seconds and becomes PaymentFailed. */ @listener(zdl: OrdersCheckoutZdl, event: OrderCreated) @transition(to: AUTHORIZATION_REQUESTED) @transition(from: AUTHORIZATION_REQUESTED, to: [AUTHORIZED, DECLINED, FAILED]) authorizePayment(AuthorizePaymentInput) Payment withEvents [PaymentAuthorized | PaymentDeclined | PaymentFailed]
/** * No-op, no event, when there is no Payment (P-12 A), or unless FAILED and input.attemptCount == attemptCount. Saves AUTHORIZATION_REQUESTED with * attemptCount + 1 and commits before calling the processor, as authorizePayment (P-11 A); then saves the outcome. * The processor call times out after 30 seconds and becomes PaymentFailed. */ @listener(event: PaymentRetried) @transition(from: FAILED, to: AUTHORIZATION_REQUESTED) @transition(from: AUTHORIZATION_REQUESTED, to: [AUTHORIZED, DECLINED, FAILED]) reauthorizePayment(ReauthorizePaymentInput) Payment? withEvents [PaymentAuthorized | PaymentDeclined | PaymentFailed]
/** * No-op, no event, when there is no Payment (P-12 A), or unless FAILED and input.attemptCount == attemptCount. * Never increments attemptCount. * At most 3 attempts in all (authorize + reauthorize); backoff before the next attempt: 5 seconds * before attempt 2, 15 seconds before attempt 3. RETRY_EXHAUSTED at the limit. */ @listener(event: PaymentFailed) @transition(from: FAILED, to: [FAILED, RETRY_EXHAUSTED]) retryPayment(RetryPaymentInput) Payment? withEvents [PaymentRetried | PaymentRetryExhausted]
/** No-op, no event, when CAPTURED, CAPTURE_FAILED or VOIDED (redelivery). */ @listener(zdl: FulfillmentShippingZdl, event: FulfillmentScheduled) @transition(from: AUTHORIZED, to: [CAPTURED, CAPTURE_FAILED]) capturePayment(CapturePaymentInput) Payment withEvents [PaymentCaptured | PaymentCaptureFailed]
/** * FulfillmentFailed and PaymentCaptureFailed void after a failure downstream; * OrderConfirmationRejected voids an authorization that arrived after expiry or cancellation. * No-op, no event, when there is no Payment or it is not AUTHORIZED or CAPTURE_FAILED (redelivery). */ @listener(zdl: OrdersCheckoutZdl, event: OrderConfirmationRejected) @listener(zdl: FulfillmentShippingZdl, event: FulfillmentFailed) @listener(event: PaymentCaptureFailed) @transition(from: [AUTHORIZED, CAPTURE_FAILED], to: [VOIDED, VOID_FAILED]) voidPayment(VoidPaymentInput) Payment? withEvents [PaymentVoided | PaymentVoidFailed]
/** Read only, for the reservation timer. STARTED for any existing Payment. */ getPaymentStatus(GetPaymentStatusInput) GetPaymentStatusResult}
rules { authorizedAmountIsOrderTotal "The authorized amount and currency are those of OrderCreated, that is Order.totalAmount and currency" authorizeBeforeCapture "Funds are held at checkout (authorization) and moved only after fulfillment is scheduled (FulfillmentScheduled)" voidRatherThanRefund "When the order cannot be fulfilled after authorization, the hold is voided, never captured and refunded" voidFailedToOps "A refused void (PaymentVoidFailed) is left to ops, who release the hold by hand; the order is cancelled anyway" paymentByOrder "Every command resolves the Payment by orderId; no event of another context carries a paymentId" paymentStartedOwnsEnd "getPaymentStatus answers STARTED for any existing Payment, whatever its state: from then on the reservation timer does nothing"}
// @asyncapi({ channel: "payment-authorized-event-v1", topic: "payments-processing.payment-authorized.event.avro.v1" })event PaymentAuthorized { orderId String customerId String amount BigDecimal currency String providerReference String authorizedAt Instant}
// @asyncapi({ channel: "payment-declined-event-v1", topic: "payments-processing.payment-declined.event.avro.v1" })event PaymentDeclined { orderId String customerId String amount BigDecimal currency String reason String declinedAt Instant}
// @asyncapi({ channel: "payment-failed-event-v1", topic: "payments-processing.payment-failed.event.avro.v1" })event PaymentFailed { orderId String customerId String attemptCount Integer reason String failedAt Instant}
// @asyncapi({ channel: "payment-retried-event-v1", topic: "payments-processing.payment-retried.event.avro.v1" })event PaymentRetried { orderId String customerId String attemptCount Integer retriedAt Instant}
// @asyncapi({ channel: "payment-retry-exhausted-event-v1", topic: "payments-processing.payment-retry-exhausted.event.avro.v1" })event PaymentRetryExhausted { orderId String customerId String attemptCount Integer reason String exhaustedAt Instant}
// @asyncapi({ channel: "payment-captured-event-v1", topic: "payments-processing.payment-captured.event.avro.v1" })event PaymentCaptured { orderId String customerId String customerEmail String amount BigDecimal currency String providerReference String capturedAt Instant}
// @asyncapi({ channel: "payment-capture-failed-event-v1", topic: "payments-processing.payment-capture-failed.event.avro.v1" })event PaymentCaptureFailed { orderId String customerId String reason String failedAt Instant}
// @asyncapi({ channel: "payment-voided-event-v1", topic: "payments-processing.payment-voided.event.avro.v1" })event PaymentVoided { orderId String customerId String providerReference String reason String voidedAt Instant}
/** Published for ops (manual follow-up) and consumed by releaseStock. */// @asyncapi({ channel: "payment-void-failed-event-v1", topic: "payments-processing.payment-void-failed.event.avro.v1" })event PaymentVoidFailed { orderId String customerId String providerReference String reason String failedAt Instant}fulfillment-shipping-domain-model.zdl
config { id "urn:com.arcadiaeditions:fulfillment:shipping" version "0.0.0" title "Arcadia Editions - Fulfillment Shipping" moduleBasePackage "com.arcadiaeditions.fulfillment.shipping" persistence jpa layout SimpleDomainProjectLayout
plugins {// /** Generates an OpenAPI 3.0 specification from this ZDL model. */// ZDLToOpenAPIPlugin {// idType integer// idTypeFormat int64// targetFile "./fulfillment-shipping-openapi.yml"// } }}
apis { zdl client OrdersCheckoutZdl "./orders-checkout-domain-model.zdl" zdl client PaymentsProcessingZdl "./payments-processing-domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: SCHEDULED)entity Fulfillment { fulfillmentId String required unique orderId String required unique customerId String required status FulfillmentStatus required @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } @json items FulfillmentItem[] required minlength(1) { sku String required quantity Integer required } carrierCode String trackingNumber String scheduledAt Instant readyAt Instant failedAt Instant failureReason String /** Set from PaymentCaptured; markReadyToShip requires it. */ paymentCapturedAt Instant cancelledAt Instant cancellationReason String}
rules (Fulfillment) { @invariant oneFulfillmentPerOrder "At most one Fulfillment per order" @invariant readyRequiresCapture "A Fulfillment is READY_TO_SHIP only if paymentCapturedAt is set: nothing ships before money moves" @invariant terminalStates "FAILED and CANCELLED are terminal" @invariant failureData "failedAt and failureReason are set if and only if the Fulfillment is FAILED" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Fulfillment is CANCELLED" @invariant readyHasTracking "A READY_TO_SHIP Fulfillment has carrierCode, trackingNumber and readyAt" @invariant contentsFixed "items and shippingAddress never change after scheduling" paymentCapturedRecordedOnce "paymentCapturedAt is set once, only while SCHEDULED, and never cleared"}
enum FulfillmentStatus { SCHEDULED(1) READY_TO_SHIP(2) FAILED(3) CANCELLED(4)}
input ScheduleFulfillmentInput { orderId String required customerId String required shippingAddress ShippingAddressInput required items FulfillmentItemInput[] required}
input RecordPaymentCapturedInput { orderId String required /** PaymentCaptured.capturedAt */ capturedAt Instant required}
input CancelFulfillmentInput { orderId String required /** OrderCancelled.reason */ reason String required}
input ShippingAddressInput { name String required line1 String required line2 String city String required region String postalCode String required country String required}
input FulfillmentItemInput { sku String required quantity Integer required}
//@rest("/fulfillments")service FulfillmentShippingService for (Fulfillment) {
/** No-op, no event, when a Fulfillment exists for orderId (redelivery). */ @listener(zdl: OrdersCheckoutZdl, event: OrderConfirmed) @transition(to: [SCHEDULED, FAILED]) scheduleFulfillment(ScheduleFulfillmentInput) Fulfillment withEvents [FulfillmentScheduled | FulfillmentFailed]
/** * Money moved: the warehouse may now prepare the parcel. Sets paymentCapturedAt; no state change, * no event. No-op when there is no Fulfillment, it is not SCHEDULED, or paymentCapturedAt is set. */ @listener(zdl: PaymentsProcessingZdl, event: PaymentCaptured) recordPaymentCaptured(RecordPaymentCapturedInput) Fulfillment?
/** Warehouse action. Refused (no transition, no event) until paymentCapturedAt is set. */ @transition(from: SCHEDULED, to: READY_TO_SHIP) markReadyToShip(id) Fulfillment withEvents FulfillmentReadyToShip
/** No-op, no event, when there is no Fulfillment for orderId or it is FAILED or CANCELLED. */ @listener(zdl: OrdersCheckoutZdl, event: OrderCancelled) @transition(from: [SCHEDULED, READY_TO_SHIP], to: CANCELLED) cancelFulfillment(CancelFulfillmentInput) Fulfillment? withEvents FulfillmentCancelled}
rules { scheduleOnlyConfirmedOrders "A Fulfillment is scheduled only for a CONFIRMED order (OrderConfirmed)" contentsFromOrder "items and shippingAddress are those of the confirmed Order" cancelFollowsOrder "A cancelled order stops its Fulfillment: SCHEDULED or READY_TO_SHIP becomes CANCELLED and the warehouse is told (FulfillmentCancelled)" failureVoidsPayment "A Fulfillment that cannot be scheduled (FulfillmentFailed) makes payments void the authorization"}
// @asyncapi({ channel: "fulfillment-scheduled-event-v1", topic: "fulfillment-shipping.fulfillment-scheduled.event.avro.v1" })event FulfillmentScheduled { fulfillmentId String orderId String customerId String scheduledAt Instant}
// @asyncapi({ channel: "fulfillment-failed-event-v1", topic: "fulfillment-shipping.fulfillment-failed.event.avro.v1" })event FulfillmentFailed { fulfillmentId String orderId String customerId String reason String failedAt Instant}
// @asyncapi({ channel: "fulfillment-ready-to-ship-event-v1", topic: "fulfillment-shipping.fulfillment-ready-to-ship.event.avro.v1" })event FulfillmentReadyToShip { fulfillmentId String orderId String customerId String carrierCode String trackingNumber String readyAt Instant}
/** Published for the warehouse; no step of place-order-flow consumes it. */// @asyncapi({ channel: "fulfillment-cancelled-event-v1", topic: "fulfillment-shipping.fulfillment-cancelled.event.avro.v1" })event FulfillmentCancelled { fulfillmentId String orderId String customerId String reason String cancelledAt Instant}notifications-consumer-domain-model.zdl
config { id "urn:com.arcadiaeditions:notifications:consumer" version "0.0.0" title "Arcadia Editions - Notifications Consumer" moduleBasePackage "com.arcadiaeditions.notifications.consumer" persistence jpa layout LayeredProjectLayout
plugins {// /** Generates an OpenAPI 3.0 specification from this ZDL model. */// ZDLToOpenAPIPlugin {// idType integer// idTypeFormat int64// targetFile "./notifications-consumer-openapi.yml"// } }}
apis { zdl client PaymentsProcessingZdl "./payments-processing-domain-model.zdl" zdl client OrdersCheckoutZdl "./orders-checkout-domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: PENDING)entity Notification { notificationId String required unique customerId String required orderId String skus String[] type NotificationType required channel NotificationChannel required status NotificationStatus required subject String required body String required recipient String required createdAt Instant required sentAt Instant failedAt Instant failureReason String}
rules (Notification) { @invariant terminalStates "SENT and FAILED are terminal: a Notification is never sent again" @invariant sentData "sentAt is set if and only if the Notification is SENT" @invariant failureData "failedAt and failureReason are set if and only if the Notification is FAILED" @invariant contentFixed "recipient, subject and body never change after creation" @invariant orderBound "ORDER_CONFIRMATION and ORDER_CANCELLED notifications always carry orderId" @invariant unavailableSkus "A STOCK_UNAVAILABLE notification lists at least one sku" onePerOrderAndType "At most one Notification per (orderId, type): a redelivered event does not notify twice"}
enum NotificationType { ORDER_CONFIRMATION(1) STOCK_UNAVAILABLE(2) ORDER_CANCELLED(3)}
enum NotificationChannel { EMAIL(1) SMS(2) PUSH(3)}
enum NotificationStatus { PENDING(1) SENT(2) FAILED(3)}
input SendOrderConfirmationInput { orderId String required customerId String required customerEmail String required}
input SendStockUnavailableNotificationInput { orderId String required customerId String required customerEmail String required unavailableItems StockUnavailableItemInput[] required minlength(1) { sku String required requestedQuantity Integer availableQuantity Integer }}
input SendOrderCancelledNotificationInput { orderId String required customerId String required reason String required customerEmail String required}
//@rest("/notifications")service NotificationsConsumerService for (Notification) {
@listener(zdl: PaymentsProcessingZdl, event: PaymentCaptured) @transition(to: [SENT, FAILED]) sendOrderConfirmation(SendOrderConfirmationInput) Notification withEvents [OrderConfirmationSent | NotificationDeliveryFailed]
@listener(zdl: OrdersCheckoutZdl, event: StockUnavailable) @transition(to: [SENT, FAILED]) sendStockUnavailableNotification(SendStockUnavailableNotificationInput) Notification withEvents [StockUnavailableNotificationSent | NotificationDeliveryFailed]
@listener(zdl: OrdersCheckoutZdl, event: OrderCancelled) @transition(to: [SENT, FAILED]) sendOrderCancelledNotification(SendOrderCancelledNotificationInput) Notification withEvents [OrderCancelledNotificationSent | NotificationDeliveryFailed]}
rules { confirmationOnlyAfterCapture "The order confirmation is sent only after the payment is captured (PaymentCaptured), never at authorization" recipientIsCustomer "The recipient of every notification is the customerEmail given at checkout" cancellationTellsWhy "An order cancelled notification says why the order was cancelled" voidFailedWarnsHold "When the reason is PAYMENT_VOID_FAILED, the cancellation message says the hold may still show until it is released" failureNamesOutcome "NotificationDeliveryFailed.type says which business outcome the customer was not told"}
// @asyncapi({ channel: "order-confirmation-sent-event-v1", topic: "notifications-consumer.order-confirmation-sent.event.avro.v1" })event OrderConfirmationSent { notificationId String orderId String customerId String channel NotificationChannel recipient String sentAt Instant}
// @asyncapi({ channel: "stock-unavailable-notification-sent-event-v1", topic: "notifications-consumer.stock-unavailable-notification-sent.event.avro.v1" })event StockUnavailableNotificationSent { notificationId String orderId String customerId String skus String[] channel NotificationChannel recipient String sentAt Instant}
// @asyncapi({ channel: "order-cancelled-notification-sent-event-v1", topic: "notifications-consumer.order-cancelled-notification-sent.event.avro.v1" })event OrderCancelledNotificationSent { notificationId String orderId String customerId String reason String channel NotificationChannel recipient String sentAt Instant}
/** Ends place-order-flow as notificationFailed; `type` tells which business outcome the customer was not told. */// @asyncapi({ channel: "notification-delivery-failed-event-v1", topic: "notifications-consumer.notification-delivery-failed.event.avro.v1" })event NotificationDeliveryFailed { notificationId String orderId String customerId String skus String[] type NotificationType channel NotificationChannel recipient String reason String failedAt Instant}catalog-products-domain-model.zdl
config { id "urn:com.arcadiaeditions:catalog:products" version "0.0.0" title "Arcadia Editions - Product Catalog" moduleBasePackage "com.arcadiaeditions.catalog.products" persistence jpa layout SimpleDomainProjectLayout
plugins { /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { idType integer idTypeFormat int64 targetFile "./catalog-products-openapi.yml" } }}
@aggregate@lifecycle(field: status, initial: DRAFT)entity Product { sku String required unique name String required description String price BigDecimal required currency String required editionSize Integer required trackingMode InventoryTrackingMode required launchAt Instant status ProductStatus required}
rules (Product) { @invariant positiveEditionSize "editionSize is at least 1" @invariant nonNegativePrice "price is not negative" @invariant identityFixed "sku, editionSize and trackingMode never change after creation" @invariant retiredIsFinal "RETIRED is terminal: a retired Product is never edited or published again" editUnpublishes "Editing a PUBLISHED Product takes it back to DRAFT: it must be published again"}
enum ProductStatus { DRAFT(1) PUBLISHED(2) RETIRED(3)}
enum InventoryTrackingMode { QUANTITY(1) SERIALIZED(2)}
input CreateProductInput { sku String required name String required description String price BigDecimal required currency String required editionSize Integer required trackingMode InventoryTrackingMode required launchAt Instant}
input UpdateProductInput { name String description String price BigDecimal currency String launchAt Instant}
output ProductPublishedResponse { productId String sku String publishedAt Instant}
@rest("/products")service ProductCatalogService for (Product) {
@post @transition(to: DRAFT) createProduct(CreateProductInput) Product
@put("/{id}") @transition(from: [DRAFT, PUBLISHED], to: DRAFT) updateProduct(id, UpdateProductInput) Product
@post("/{id}/publish") @transition(from: DRAFT, to: PUBLISHED) publishProduct(id) Product withEvents ProductPublished
@post("/{id}/retire") @transition(from: [DRAFT, PUBLISHED], to: RETIRED) retireProduct(id) Product withEvents ProductRetired}
rules { onlyPublishedIsSold "Only a PUBLISHED Product can be ordered; DRAFT and RETIRED products are not on sale" noSaleBeforeLaunch "A Product with launchAt is not on sale before launchAt"}
// @asyncapi({ channel: "product-published-event-v1", topic: "catalog-products.product-published.event.avro.v1" })event ProductPublished { productId String sku String name String price BigDecimal currency String editionSize Integer trackingMode InventoryTrackingMode launchAt Instant publishedAt Instant}
// @asyncapi({ channel: "product-retired-event-v1", topic: "catalog-products.product-retired.event.avro.v1" })event ProductRetired { productId String sku String retiredAt Instant}Each model’s config sets the module’s moduleBasePackage and layout (this modulith mixes layouts on purpose), and its apis block declares the other modules it talks to as zdl clients:
orders-checkout-domain-model.zdl: config and apis
config { id "urn:com.arcadiaeditions:orders:checkout" version "0.0.0" title "Arcadia Editions - Orders Checkout" moduleBasePackage "com.arcadiaeditions.orders.checkout" persistence jpa layout CleanHexagonalProjectLayout
plugins { /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { idType integer idTypeFormat int64 openapiOverlayFiles "./orders-checkout-openapi-overlay.yml" targetFile "./orders-checkout-openapi.yml" } }}
apis { zdl client PaymentsProcessingZdl "./payments-processing-domain-model.zdl" zdl client CatalogInventoryZdl "./catalog-inventory-domain-model.zdl"}ZenWave scripts
Section titled “ZenWave scripts”zenwave-scripts.zw imports the released models and runs BackendApplicationDefaultPlugin once per module, then OpenAPIControllersPlugin and SpringWebTestClientPlugin for the Orders Checkout REST API. The shared common packages keep base classes in one place for all modules.
zenwave-scripts.zw
@import("com.arcadiaeditions.modulith.application.arcadia-editions-modulith:service-all:0.10.3")config {
basePackage "com.arcadiaeditions" layout.commonPackage "{{basePackage}}.common" layout.entitiesCommonPackage "{{commonPackage}}.domain" layout.domainEventsCommonPackage "{{commonPackage}}.domain.events" layout.coreImplementationCommonPackage "{{commonPackage}}" layout.coreImplementationMappersCommonPackage "{{commonPackage}}.mappers" layout.infrastructureRepositoryCommonPackage "{{commonPackage}}" layout.infrastructureEventsCommonPackage "{{commonPackage}}" layout.adaptersWebCommonPackage "{{commonPackage}}" layout.adaptersWebMappersCommonPackage "{{commonPackage}}.mappers" layout.adaptersCommandsCommonPackage "{{commonPackage}}.commands" layout.adaptersCommandsMappersCommonPackage "{{commonPackage}}.commands.mappers" layout.adaptersEventsCommonPackage "{{commonPackage}}.events" layout.adaptersEventsMappersCommonPackage "{{commonPackage}}.events.mappers"
useJSpecify true useJMolecules true useSpringModulith true implementEventListeners true includeEmitEventsImplementation true
plugins { /** Generates a Backend Application from the ZDL model. (Headless Core) */ BackendApplicationDefaultPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-inventory-domain-model.zdl" } BackendApplicationDefaultPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-products-domain-model.zdl" } BackendApplicationDefaultPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/fulfillment-shipping-domain-model.zdl" } BackendApplicationDefaultPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/notifications-consumer-domain-model.zdl" } BackendApplicationDefaultPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" } BackendApplicationDefaultPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/payments-processing-domain-model.zdl" }
/** Generates Spring MVC controllers from the OpenAPI specification (Web Adapters). */ OpenAPIControllersPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" openapiFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-openapi.yml" openApiModelNameSuffix DTO } SpringWebTestClientPlugin { zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" openapiFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-openapi.yml" openApiModelNameSuffix DTO } }}Open the file in the IDE with the ZenWave plugin and use the play button next to each plugin. Hovering the button shows the equivalent jbang zw -p <Plugin> ... command line.
Generated code
Section titled “Generated code”Inbound port from the service
Section titled “Inbound port from the service”Each ZDL service becomes an inbound port. Javadoc and the events of each command come from the model:
Given this service in the ZDL:
orders-checkout-domain-model.zdl
@rest("/orders")service OrdersCheckoutService for (Order) {
/** Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). */ @post("/start-checkout") @transition(to: CREATED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.reserveStock) startOrderCheckout(StartOrderCheckoutInput) Order withEvents [OrderCreated | StockUnavailable]
/** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. */ @listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @listener(zdl: CatalogInventoryZdl, event: StockReleased) @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelledBackendApplicationDefaultPlugin generates this inbound port, exposed as a Spring Modulith named interface:
OrdersCheckoutService.java
/** * Inbound Service Port for managing [Order]. */@org.springframework.modulith.NamedInterface("OrdersCheckoutService")@org.jspecify.annotations.NullMarked@org.jmolecules.architecture.hexagonal.PrimaryPortpublic interface OrdersCheckoutService {
/** * Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). * * With Events: [[OrderCreated, StockUnavailable]]. * */ public Order startOrderCheckout(StartOrderCheckoutInput input); /** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. * * With Events: [[OrderConfirmed, OrderConfirmationRejected]]. * */ public Order confirmOrder(ConfirmOrderInput input); /** * No-op, no event, on CANCELLED (redelivered StockReleased). * * With Events: [OrderCancelled]. * */ public Order cancelOrder(CancelOrderInput input);State transitions from @lifecycle and @transition
Section titled “State transitions from @lifecycle and @transition”Commands declare which states they move the aggregate between:
orders-checkout-domain-model.zdl
@listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @listener(zdl: CatalogInventoryZdl, event: StockReleased) @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelledand the generator writes the guards:
OrderTransitions.java
public final class OrderTransitions {
private OrderTransitions() {}
public static void ensureCanConfirmOrder(Order entity) { require("confirmOrder", entity, OrderStatus.CREATED); }
public static void ensureCanCancelOrder(Order entity) { require("cancelOrder", entity, OrderStatus.CREATED, OrderStatus.CONFIRMED); }
private static void require(String command, Order entity, OrderStatus... allowed) { var current = entity.getStatus(); for (var state : allowed) { if (current != null && current == state) { return; } } throw new InvalidStateTransitionException( entity.getClass().getSimpleName(), entity.getId(), null, command, current, Arrays.asList(allowed)); }In-process event listeners from @listener
Section titled “In-process event listeners from @listener”A command annotated with @listener reacts to an event of another module:
orders-checkout-domain-model.zdl
@listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]which becomes a Spring Modulith @ApplicationModuleListener calling the inbound port:
PaymentsProcessingEventsListener.java
/** * Internal domain event listeners for PaymentsProcessingZdl. * * This class is generated once and can be customized safely. */@Component@org.jmolecules.architecture.hexagonal.PrimaryAdapterpublic class PaymentsProcessingEventsListener { private final OrdersCheckoutService ordersCheckoutService; private final PaymentsProcessingEventsListenerMapper mapper = PaymentsProcessingEventsListenerMapper.INSTANCE;
public PaymentsProcessingEventsListener(OrdersCheckoutService ordersCheckoutService) { this.ordersCheckoutService = ordersCheckoutService; }
@ApplicationModuleListener public void onPaymentAuthorized(com.arcadiaeditions.payments.processing.domain.event.PaymentAuthorized event) { ordersCheckoutService.confirmOrder(mapper.asConfirmOrderInput(event)); }}Events are published through Spring’s ApplicationEventPublisher. With the Spring Modulith JDBC event publication registry, listeners run after the publishing transaction commits:
DefaultEventPublisher.java
@Component@org.jmolecules.architecture.hexagonal.SecondaryAdapterpublic class DefaultEventPublisher implements EventPublisher {
private final ApplicationEventPublisher applicationEventPublisher;
public DefaultEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; }
public void onOrderConfirmedItem(OrderConfirmedItem event) { applicationEventPublisher.publishEvent(event); }The last mile: behavior implemented against the rules
Section titled “The last mile: behavior implemented against the rules”The generator leaves service methods as TODOs. Here is confirmOrder after the AFK implementation: a no-op on redelivery, a rejection on CANCELLED or NOT_HELD stock, as the rules confirmOnlyWithHeldStock and rejectedConfirmationVoids say.
OrdersCheckoutServiceImpl.java: confirmOrder
public Order confirmOrder(ConfirmOrderInput input) {
log.debug("Request confirmOrder: {}", input);
var existing = orderRepository.findByOrderId(input.getOrderId()).orElseThrow(); if (existing.getStatus() == OrderStatus.CONFIRMED) { log.debug("confirmOrder redelivery, order already CONFIRMED: {}", input.getOrderId()); return existing; } if (existing.getStatus() == OrderStatus.CANCELLED) { reject(existing, "ORDER_CANCELLED"); return existing; } OrderTransitions.ensureCanConfirmOrder(existing); var stock = inventoryService.confirmStockReservation( new ConfirmStockReservationInput().setOrderId(existing.getOrderId())); if (stock.getOutcome() == ConfirmStockReservationOutcome.NOT_HELD) { reject(existing, "STOCK_NOT_HELD"); return existing; } existing.setStatus(OrderStatus.CONFIRMED); existing.setConfirmedAt(clock.instant()); var order = orderRepository.save(existing); // emit events var orderConfirmed = eventsMapper.asOrderConfirmed(order); eventPublisher.onOrderConfirmed(orderConfirmed); return order; }
private void reject(Order order, String reason) { var rejected = eventsMapper.asOrderConfirmationRejected(order); rejected.setReason(reason); rejected.setRejectedAt(clock.instant()); eventPublisher.onOrderConfirmationRejected(rejected); }The flow is covered end to end by PlaceOrderFlowTest, one scenario per outcome of the flow:
PlaceOrderFlowTest.java
/** * PlaceOrderFlow, end "completed": POST start-checkout follows the in-process events * (OrderCreated, PaymentAuthorized, OrderConfirmed, FulfillmentScheduled, PaymentCaptured) to OrderConfirmationSent. * place-order-flow.zfl:65-192, 262-266. End "stockGone": StockUnavailable to StockUnavailableNotificationSent, * place-order-flow.zfl:82-87, 199-202, 262-266. Not @Transactional: the module listeners run after commit. * StockUnavailable is published in the request (test) thread, so {@link ApplicationEvents} records it. * End "orderCancelled" by decline: OrderCreated, PaymentDeclined, StockReleased, OrderCancelled to * OrderCancelledNotificationSent, place-order-flow.zfl:108-116, 223-260, 262-266. * End "completed" after one retry: PaymentFailed, PaymentRetried, PaymentAuthorized to OrderConfirmationSent, * place-order-flow.zfl:118-140, 262-266. PaymentFailed and PaymentRetried are published in listener threads, which * {@link ApplicationEvents} does not record: {@link PaymentEventsRecorder} counts them. * End "orderCancelled" by retries exhausted: PaymentFailed and PaymentRetried until max-attempts (3), then * PaymentRetryExhausted, StockReleased, OrderCancelled to OrderCancelledNotificationSent, * place-order-flow.zfl:124-130, 223-260, 262-266. * End "orderCancelled" by fulfillment failure: OrderConfirmed, FulfillmentFailed, PaymentVoided, StockReleased, * OrderCancelled to OrderCancelledNotificationSent, place-order-flow.zfl:160-170, 204-260, 262-266. * End "orderCancelled" by capture failure: FulfillmentScheduled, PaymentCaptureFailed, PaymentVoided, StockReleased, * OrderCancelled, cancelFulfillment to FulfillmentCancelled (reason PAYMENT_VOIDED), OrderCancelledNotificationSent, * place-order-flow.zfl:190-200, 204-260, 262-266, 311-320. Repository state is * read with Awaitility: the terminal event can arrive before the last listener's transaction is visible. * End "orderCancelled" by void refused (T-59): OrderConfirmed, FulfillmentFailed, PaymentVoidFailed, StockReleased * (PAYMENT_VOID_FAILED), OrderCancelled once to OrderCancelledNotificationSent, Payment VOID_FAILED, * place-order-flow.zfl:236-266, 299-309, 322-345 (data.sql ORD-026). * End "notificationFailed" (both branches, NotificationDeliveryFailed): PaymentCaptured to sendOrderConfirmation * failed (type ORDER_CONFIRMATION, order stays CONFIRMED), place-order-flow.zfl:207-212, 337-345; OrderCancelled to * sendOrderCancelledNotification failed (type ORDER_CANCELLED, order stays CANCELLED), place-order-flow.zfl:322-345; * and StockUnavailable to sendStockUnavailableNotification failed (type STOCK_UNAVAILABLE, 409 answered, no Order or * StockReservation), place-order-flow.zfl:223-234, 336-345. * Retry loop (T-55), place-order-flow.zfl:124-146, 254-266: attempts are counted only by authorizePayment (1) and * reauthorizePayment (2, 3), the test backoff ({@link #BACKOFF_BEFORE_ATTEMPT_2}, {@link #BACKOFF_BEFORE_ATTEMPT_3}) * is waited before each reauthorization, and a redelivered PaymentFailed or PaymentRetried with a stale attemptCount * changes nothing (data.sql ORD-008, ORD-009, ORD-015, and the live order after its cancellation). */How to run
Section titled “How to run”Prerequisites: Java 25+, Maven 3.6+, Docker. Install the ZenWave CLI with JBang as explained in Getting Started.
git clone https://github.com/arcadia-editions/arcadia-editions-modulith-service-java.git
cd arcadia-editions-modulith-service-java
docker-compose up -d # local infrastructure (PostgreSQL)
mvn spring-boot:run
- SwaggerUI: http://localhost:8080/swagger-ui/index.html
- Actuator: http://localhost:8080/actuator
Tests:
mvn test # unit tests (*Test)
mvn verify # unit + integration tests (*IT, *IntegrationTest) and JaCoCo report
To regenerate after a model change, run the plugins in zenwave-scripts.zw, then mvn -DskipTests clean test-compile. Service implementations, listeners, mappers and tests are generated once and then belong to you: a normal run does not overwrite them, --force does.