Arcadia Editions Modulith: Quarkus (beta)
Section titled “Arcadia Editions Modulith: Quarkus (beta)”The same six bounded contexts and the same models as the Java and Kotlin moduliths, as one Java + Quarkus modular monolith. The code is generated with the zenwave-quarkus templates: JAX-RS, CDI, Hibernate ORM, MapStruct and Flyway.
There is no AsyncAPI and no Kafka. Modules talk through in-process CDI events (@Observes(during = AFTER_SUCCESS) + @Transactional(REQUIRES_NEW)), the Quarkus counterpart of Spring Modulith @ApplicationModuleListener, without an event publication registry.
Source code: arcadia-editions-modulith-service-quarkus. Models: arcadia-editions-modulith-api.
Modules
Section titled “Modules”One module per bounded context. Only orders.checkout exposes an API to the outside (REST, generated from OpenAPI as JAX-RS resources). The other modules react to CDI events fired 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 shared with the Spring moduliths: see the Java page.
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
Section titled “Its rules and @invariant”The rules and @invariants are framework-agnostic: the same natural-language spec drives the last mile in Spring Boot and in Quarkus. These are the rules of Order, then the service and its rules:
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"}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"}ZenWave scripts
Section titled “ZenWave scripts”The script imports quarkus-backend-application and sets Quarkus templates on each plugin. SpringWebTestClientPlugin with QuarkusHttpTestTemplates generates RestAssured @QuarkusTest HTTP tests.
zenwave-scripts.zw
@import("io.zenwave360.sdk:quarkus-backend-application:2.10.0-SNAPSHOT")@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"
useJMolecules true implementEventListeners true includeEmitEventsImplementation true
persistence jpa databaseType postgresql style imperative
plugins { /** Generates a Backend Application from the ZDL model. (Headless Core) */ BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-inventory-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-products-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/fulfillment-shipping-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/notifications-consumer-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/payments-processing-domain-model.zdl" }
/** Generates JAX-RS resources from the OpenAPI specification (Web Adapters). */ OpenAPIControllersPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.OpenAPIControllersQuarkusTemplates" 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 } /** Generates RestAssured @QuarkusTest HTTP tests from the OpenAPI specification. */ SpringWebTestClientPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.QuarkusHttpTestTemplates" 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 } }}zenwave-scripts.zw: Quarkus options and templates
useJMolecules true implementEventListeners true includeEmitEventsImplementation true
persistence jpa databaseType postgresql style imperative
plugins { /** Generates a Backend Application from the ZDL model. (Headless Core) */ BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.BackendApplicationQuarkusTemplates" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-inventory-domain-model.zdl" }zenwave-scripts.zw: JAX-RS resources and HTTP tests
/** Generates JAX-RS resources from the OpenAPI specification (Web Adapters). */ OpenAPIControllersPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.OpenAPIControllersQuarkusTemplates" 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 } /** Generates RestAssured @QuarkusTest HTTP tests from the OpenAPI specification. */ SpringWebTestClientPlugin { templates "new io.zenwave360.sdk.plugins.quarkus.QuarkusHttpTestTemplates" 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 }Generated code
Section titled “Generated code”In-process event listeners as CDI observers
Section titled “In-process event listeners as CDI observers”The same @listener in the ZDL:
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]becomes a CDI observer that runs after the publishing transaction commits, off the publishing thread:
PaymentsProcessingEventsListener.java
/** * Internal domain event listeners for PaymentsProcessingZdl. * * <p>Same contract as Spring Modulith {@code @ApplicationModuleListener}: each listener runs after the publishing * transaction commits ({@code AFTER_SUCCESS}; never on rollback; immediately when there is no transaction), off the * publishing thread and in its own transaction ({@link AsyncListeners}). A failure is logged and does not undo the * publisher's commit: delivery is at-most-once, use an outbox when a listener must not be lost. * * This class is generated once and can be customized safely. */@ApplicationScoped@org.jmolecules.architecture.hexagonal.PrimaryAdapterpublic class PaymentsProcessingEventsListener { private final AsyncListeners asyncListeners; private final OrdersCheckoutService ordersCheckoutService; private final PaymentsProcessingEventsListenerMapper mapper;
@Inject public PaymentsProcessingEventsListener( OrdersCheckoutService ordersCheckoutService, PaymentsProcessingEventsListenerMapper mapper, AsyncListeners asyncListeners) { this.asyncListeners = asyncListeners; this.ordersCheckoutService = ordersCheckoutService; this.mapper = mapper; }
public void onPaymentAuthorized( @Observes(during = TransactionPhase.AFTER_SUCCESS) com.arcadiaeditions.payments.processing.domain.event.PaymentAuthorized event) { asyncListeners.run( "PaymentsProcessingEventsListener.onPaymentAuthorized", event, () -> ordersCheckoutService.confirmOrder(mapper.asConfirmOrderInput(event))); }}Note the trade-off stated in the generated Javadoc: delivery is at-most-once. Use an outbox when a listener must not be lost.
Events are fired through CDI Event<T>:
DefaultEventPublisher.java
@ApplicationScoped@org.jmolecules.architecture.hexagonal.SecondaryAdapterpublic class DefaultEventPublisher implements EventPublisher {
private final Event<OrderConfirmedItem> orderConfirmedItem;
private final Event<OrderConfirmedShippingAddress> orderConfirmedShippingAddress;
private final Event<StockUnavailableItem> stockUnavailableItem;
private final Event<StockUnavailable> stockUnavailable;
private final Event<OrderConfirmationRejected> orderConfirmationRejected;
private final Event<OrderConfirmed> orderConfirmed;
private final Event<OrderCancelled> orderCancelled;
private final Event<OrderCreated> orderCreated;
@Inject public DefaultEventPublisher( Event<OrderConfirmedItem> orderConfirmedItem, Event<OrderConfirmedShippingAddress> orderConfirmedShippingAddress, Event<StockUnavailableItem> stockUnavailableItem, Event<StockUnavailable> stockUnavailable, Event<OrderConfirmationRejected> orderConfirmationRejected, Event<OrderConfirmed> orderConfirmed, Event<OrderCancelled> orderCancelled, Event<OrderCreated> orderCreated) {
this.orderConfirmedItem = orderConfirmedItem;
this.orderConfirmedShippingAddress = orderConfirmedShippingAddress;
this.stockUnavailableItem = stockUnavailableItem;
this.stockUnavailable = stockUnavailable;
this.orderConfirmationRejected = orderConfirmationRejected;
this.orderConfirmed = orderConfirmed;
this.orderCancelled = orderCancelled;
this.orderCreated = orderCreated; }
@Override public void onOrderConfirmedItem(OrderConfirmedItem event) { orderConfirmedItem.fire(event); }JAX-RS resources from OpenAPI
Section titled “JAX-RS resources from OpenAPI”OrdersCheckoutApiController.java
/** * JAX-RS resource for OrdersCheckout. */@ApplicationScoped@Path("/")public class OrdersCheckoutApiController {
private final OrdersCheckoutService ordersCheckoutService;
private final OrdersCheckoutDTOsMapper mapper;
private final Logger log = LoggerFactory.getLogger(getClass());
@Inject public OrdersCheckoutApiController(OrdersCheckoutService ordersCheckoutService, OrdersCheckoutDTOsMapper mapper) {
this.ordersCheckoutService = ordersCheckoutService;
this.mapper = mapper; }
@POST @Path("/orders/start-checkout") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startOrderCheckout(@Valid StartOrderCheckoutInputDTO reqBody) { log.debug("REST request to startOrderCheckout: {}", reqBody); var input = mapper.asStartOrderCheckoutInput(reqBody); var order = ordersCheckoutService.startOrderCheckout(input); var responseDTO = mapper.asOrderDTO(order); return Response.status(201).entity(responseDTO).build(); }How to run
Section titled “How to run”Prerequisites: Java 21+, Maven, Docker.
git clone https://github.com/arcadia-editions/arcadia-editions-modulith-service-quarkus.git
cd arcadia-editions-modulith-service-quarkus
./mvnw quarkus:dev # Dev Services (Postgres)
./mvnw test
- Swagger UI: http://localhost:8080/q/swagger-ui
With docker-compose instead of Dev Services:
docker compose up -d && ./mvnw quarkus:dev -Dquarkus.profile=dev,compose
The prod profile runs Flyway migrate-at-start with Hibernate validate, and reads DB_URL, DB_USER and DB_PASSWORD.
To regenerate, run one jbang zw call per plugin block of zenwave-scripts.zw (after mvn install of zenwave-quarkus). Existing files are kept; -f overwrites them. mvn generate-sources generates the OpenAPI DTOs into target/generated-sources/openapi.