From e7153189ed6965d230191d7a995e7b74033509c7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 01/14] build(deps): add Hibernate Reactive Panache and the reactive PostgreSQL client The two extensions sit next to the blocking JDBC stack. Both talk to the same PostgreSQL database, and Dev Services still provisions the container, so the tests need no manual container setup. Their versions come from the Quarkus BOM. The reactive slice of the project is deliberately small, one streaming endpoint, to show that blocking and reactive code coexist in one application. --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 641f0d6..5611ad9 100644 --- a/pom.xml +++ b/pom.xml @@ -52,6 +52,14 @@ io.quarkus quarkus-jdbc-postgresql + + io.quarkus + quarkus-hibernate-reactive-panache + + + io.quarkus + quarkus-reactive-pg-client + io.quarkus quarkus-flyway From 0ff06d9e91269efb97c6e3ee3bdcd12305259c85 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 02/14] build(config): give the reactive slice its own persistence unit and datasource A persistence unit is either blocking, over JDBC, or reactive, over the Vert.x client, never both. The existing entities stay in the default unit, and a named reactive unit maps only the package holding the streaming entity. Schema management stays off there too, because Flyway is the only owner of the schema. The named unit needs a named reactive datasource, which reuses the connection Dev Services computes for the default one, so no second empty database starts. In production the reactive client expects a postgresql:// URL and not the JDBC one, so it reads its own variable. --- src/main/resources/application.properties | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 6ec6ce6..a853018 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -55,3 +55,28 @@ smallrye.jwt.new-token.lifespan=3600 # missed invalidation can never serve stale data for long and memory use stays predictable. quarkus.cache.caffeine."product-cache".maximum-size=500 quarkus.cache.caffeine."product-cache".expire-after-write=10M + +# --- Persistence units: blocking ORM and Hibernate Reactive side by side ---------- +# A persistence unit is either blocking (JDBC) or reactive (Vert.x client), never both, so the +# reactive slice gets its own named unit. The default unit keeps every existing entity (package +# "entity"); the "reactive" unit only maps the read-only ReactiveOrder (package "reactive"). +quarkus.hibernate-orm.packages=com.edgareldy.quarkustutorial.entity +quarkus.hibernate-orm."reactive".datasource=streaming +quarkus.hibernate-orm."reactive".packages=com.edgareldy.quarkustutorial.reactive +quarkus.hibernate-orm."reactive".schema-management.strategy=none + +# The named unit needs its own reactive-only datasource (named "streaming"; not "reactive", which +# would collide with the reactive.* configuration group of the default datasource). It has no URL of +# its own: it reuses the default datasource's reactive connection. In dev and test Dev Services +# computes that connection for the default datasource (same container, already Flyway-migrated), so +# Dev Services must not start a second, empty database for the named one. Flyway keeps using the +# default JDBC datasource: it is the only schema owner. +quarkus.datasource."streaming".db-kind=postgresql +quarkus.datasource."streaming".jdbc=false +quarkus.datasource."streaming".devservices.enabled=false +quarkus.datasource."streaming".reactive.url=${quarkus.datasource.reactive.url} +quarkus.datasource."streaming".username=${quarkus.datasource.username} +quarkus.datasource."streaming".password=${quarkus.datasource.password} +# Packaged application: the reactive client wants a "postgresql://" URL, not the JDBC one, so it gets +# its own variable (docker-compose.yml provides it, same host and database as DB_URL). +%prod.quarkus.datasource.reactive.url=${DB_REACTIVE_URL:postgresql://localhost:5432/quarkus_tutorial} From aa88b1e5c0de6c4a423915cd1176f8ba601a26ab Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 03/14] build(docker): pass the reactive connection URL to the application The packaged application now needs a reactive URL in addition to the JDBC one, since the reactive client does not accept the jdbc: form. It points at the same host and database, and the user name and password are reused, so nothing new has to be set in the environment file. --- docker-compose.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docker-compose.yml b/docker-compose.yml index f64ba7f..c649194 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -36,6 +36,7 @@ services: condition: service_healthy environment: DB_URL: jdbc:postgresql://db:5432/${DB_NAME:-quarkus_tutorial} + DB_REACTIVE_URL: postgresql://db:5432/${DB_NAME:-quarkus_tutorial} DB_USER: ${DB_USER:-quarkus} DB_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD in .env} JWT_PUBLIC_KEY_LOCATION: /keys/publicKey.pem From e40ec3d18e1afbe5e89446d8ee5d0e0cb90f2831 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 04/14] feat(entity): add ReactiveOrder for the reactive persistence unit This read-only mapping of the orders table lives in its own package because it belongs to the reactive unit and not to the blocking one. Customer and product are mapped as plain id columns, so the blocking entities never have to be dragged into the reactive unit. It is never written: the blocking order service owns the writes and Flyway owns the schema. The entity only exists so the streaming endpoint can reload a committed order without blocking. --- .../reactive/ReactiveOrder.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/reactive/ReactiveOrder.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/reactive/ReactiveOrder.java b/src/main/java/com/edgareldy/quarkustutorial/reactive/ReactiveOrder.java new file mode 100644 index 0000000..0ff44ad --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/reactive/ReactiveOrder.java @@ -0,0 +1,46 @@ +package com.edgareldy.quarkustutorial.reactive; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.math.BigDecimal; + +/** + * Read-only mapping of the orders table for the reactive persistence unit, with plain id columns. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Hibernate ORM (blocking) and Hibernate Reactive cannot share one persistence unit: a unit is either +// blocking (JDBC) or reactive (Vert.x client). This entity therefore lives in its own package, bound to +// the "reactive" unit only, and maps customer_id/product_id as plain columns so that Customer and +// Product (which belong to the blocking unit) never have to be dragged into the reactive one. +// It is never written: Flyway owns the schema and the blocking OrderServiceImpl owns the writes. +@Entity(name = "ReactiveOrder") +@Table(name = "orders") +public class ReactiveOrder { + + @Id + private Long id; + + @Column(name = "customer_id", nullable = false, insertable = false, updatable = false) + private Long customerId; + + @Column(name = "product_id", nullable = false, insertable = false, updatable = false) + private Long productId; + + @Column(nullable = false, insertable = false, updatable = false) + private Integer quantity; + + @Column(nullable = false, insertable = false, updatable = false) + private BigDecimal total; + + public Long getId() { return id; } + public Long getCustomerId() { return customerId; } + public Long getProductId() { return productId; } + public Integer getQuantity() { return quantity; } + public BigDecimal getTotal() { return total; } +} From 540740d443886d61660378eb6033c6df3e1fde11 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 05/14] feat(repository): add the reactive order repository It follows the same repository pattern as the blocking side, taken from the reactive Panache variant: every method returns a Mutiny Uni, an asynchronous result of zero or one item, instead of a value. It is used only by the streaming endpoint, and the blocking repository and service keep serving everything else. --- .../OrderPanacheRepositoryReactive.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java new file mode 100644 index 0000000..6149502 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java @@ -0,0 +1,21 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.reactive.ReactiveOrder; +import io.quarkus.hibernate.reactive.panache.PanacheRepositoryBase; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Reactive Panache repository used only by the order streaming endpoint to reload a committed order. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same repository pattern as the blocking side, but from the reactive Panache variant: every method +// returns a Mutiny Uni (0 or 1 item, asynchronous) instead of a value, and runs on the Vert.x event +// loop through the "reactive" persistence unit. PanacheRepositoryBase is used (not PanacheRepository) +// because the id type is given explicitly. +@ApplicationScoped +public class OrderPanacheRepositoryReactive implements PanacheRepositoryBase { +} From 9d102f68418af5416f9534caaa87553dd960d914 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 06/14] feat(service): add the OrderCreatedEvent The event is a plain record carrying only the id of the order. Consumers reload the row after the commit, so the event never holds an entity that could be stale or attached to a closed session. --- .../service/event/OrderCreatedEvent.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java b/src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java new file mode 100644 index 0000000..de2ee65 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java @@ -0,0 +1,14 @@ +package com.edgareldy.quarkustutorial.service.event; + +/** + * Plain CDI event fired by the blocking order service once a new order has been persisted. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Only the id travels: the reactive side reloads the committed row itself, so it never publishes +// state that a rollback could still undo and never shares entity instances across persistence units. +public record OrderCreatedEvent(Long orderId) { +} From c24323044f647c99804e4a6dc344610f706c1577 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 07/14] feat(service): broadcast committed orders as a reactive stream The bean observes the order created event with the AFTER_SUCCESS transaction phase, so the observer only runs once the creating transaction commits and never for a rolled back order. It pushes the id into a hot broadcast processor, which delivers it to every current subscriber and replays nothing to late ones. Each subscription gets its own bounded buffer, so a slow client fails alone and order creation never waits for anyone. It also hops back onto the Vert.x context of the request before reloading the order through the reactive repository, since Hibernate Reactive must run on such a context. --- .../service/impl/OrderEventBroadcaster.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java new file mode 100644 index 0000000..666c2a6 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java @@ -0,0 +1,76 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.repository.OrderPanacheRepositoryReactive; +import com.edgareldy.quarkustutorial.service.event.OrderCreatedEvent; +import io.quarkus.hibernate.reactive.panache.Panache; +import io.smallrye.mutiny.Multi; +import io.smallrye.mutiny.Uni; +import io.smallrye.mutiny.operators.multi.processors.BroadcastProcessor; +import io.smallrye.mutiny.operators.multi.processors.SerializedProcessor; +import io.vertx.core.Context; +import io.vertx.core.Vertx; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.event.TransactionPhase; +import jakarta.inject.Inject; + +/** + * Bridges the blocking order creation to the reactive world: turns committed-order CDI events into a + * hot {@code Multi} of {@link OrderResponse} that any number of SSE clients can subscribe to. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class OrderEventBroadcaster { + + // Mutiny is Quarkus's reactive library: a Uni is an asynchronous result of 0 or 1 item, a Multi is + // an asynchronous stream of 0..n items. A BroadcastProcessor is both a Multi and a sink: items + // pushed with onNext are delivered to every current subscriber (a "hot" stream, nothing is + // replayed to late subscribers). serialized() makes concurrent onNext calls from different + // request threads safe. + private final SerializedProcessor processor = BroadcastProcessor.create().serialized(); + + @Inject + OrderPanacheRepositoryReactive orderRepository; + + /** + * Receives the event only after the creating transaction committed successfully. + * + * @param event the order created event + */ + // TransactionPhase.AFTER_SUCCESS defers this observer until the transaction that fired the event + // commits, and skips it entirely on rollback: an order that was rolled back is never broadcast. + void onOrderCreated(@Observes(during = TransactionPhase.AFTER_SUCCESS) OrderCreatedEvent event) { + processor.onNext(event.orderId()); + } + + /** + * @return a stream of the orders created from now on, one independent subscription per caller + */ + public Multi stream() { + // Hibernate Reactive needs a Vert.x context. The event is published from a blocking worker + // thread, so each subscription remembers the context it was opened on (the event loop of the + // SSE request) and hops back onto it before touching the database. + Context context = Vertx.currentContext(); + Multi ids = Multi.createFrom().publisher(processor) + // Per-subscriber buffer: a slow client fills its own buffer and is failed alone, + // order creation (the publisher) never waits for anyone. + .onOverflow().buffer(64); + if (context != null) { + ids = ids.emitOn(command -> context.runOnContext(ignored -> command.run())); + } + return ids.onItem().transformToUniAndConcatenate(this::load); + } + + private Uni load(Long id) { + // Opens a reactive session on the named "reactive" persistence unit for the duration of the + // lookup (the no-argument variant would look for the default unit, which is blocking). + return Panache.withSession("reactive", () -> orderRepository.findById(id)) + .map(order -> new OrderResponse(order.getId(), order.getCustomerId(), order.getProductId(), + order.getQuantity(), order.getTotal())); + } +} From 3291c6b29eb2f9a052357a801560d59a4c8d92b0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 08/14] feat(service): publish an event when an order is created After persisting the order, the blocking service fires a synchronous CDI event inside its transaction. It knows nothing about who listens, which keeps the imperative code untouched and lets the reactive side decide when to react: observers declared for the after-success phase only run once the transaction commits. --- .../quarkustutorial/service/impl/OrderServiceImpl.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java index 099e3de..0e2d867 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java @@ -12,8 +12,10 @@ import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.repository.ProductRepository; import com.edgareldy.quarkustutorial.service.OrderService; +import com.edgareldy.quarkustutorial.service.event.OrderCreatedEvent; import io.quarkus.panache.common.Page; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Event; import jakarta.inject.Inject; import jakarta.transaction.Transactional; import java.math.BigDecimal; @@ -44,6 +46,11 @@ public class OrderServiceImpl implements OrderService { @Inject ProductRepository productRepository; + // Synchronous CDI event, fired inside the transaction: observers declared with + // TransactionPhase.AFTER_SUCCESS (see OrderEventBroadcaster) only run once it commits. + @Inject + Event orderCreatedEvent; + @Override @Transactional public PageResponse list(int page, int size, Long customerId, Long productId) { @@ -84,6 +91,7 @@ public OrderResponse create(OrderRequest request) { order.setQuantity(request.quantity()); order.setTotal(total); orderRepository.persist(order); + orderCreatedEvent.fire(new OrderCreatedEvent(order.getId())); return toResponse(order); } From b1c9052e44d70c65f867eeadb764dabe1cf3f597 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 09/14] feat(resource): add the order SSE stream endpoint GET /api/v1/orders/stream returns a Mutiny Multi as Server-Sent Events: one long-lived response with one JSON event per new order. Quarkus REST subscribes and applies backpressure, so there is no manual thread handling. The success envelope does not apply to a stream, each element is a bare order response, and the same ORDER:READ permission protects it. The method is marked blocking because the token blacklist filter runs a JDBC query, which is forbidden on the event loop where a Multi endpoint would otherwise be dispatched. That only concerns the request pipeline, the stream itself stays reactive. --- .../resource/OrderResource.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java index af35818..a05e10e 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java @@ -5,6 +5,9 @@ import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; import com.edgareldy.quarkustutorial.service.OrderService; +import com.edgareldy.quarkustutorial.service.impl.OrderEventBroadcaster; +import io.smallrye.common.annotation.Blocking; +import io.smallrye.mutiny.Multi; import io.quarkus.security.PermissionsAllowed; import jakarta.inject.Inject; import jakarta.validation.Valid; @@ -21,6 +24,7 @@ import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; import org.jboss.resteasy.reactive.ResponseStatus; +import org.jboss.resteasy.reactive.RestStreamElementType; /** * Endpoints to list, read and place orders, with optional customer and product filters on the list. @@ -48,6 +52,26 @@ public ApiResponse> list( return ApiResponse.success(orderService.list(page, size, customerId, productId), "Orders"); } + @Inject + OrderEventBroadcaster broadcaster; + + // Server-Sent Events: one long-lived HTTP response, one event per new order. Returning a Mutiny + // Multi is enough, Quarkus REST subscribes, honours backpressure and writes each item as it arrives + // (no manual thread handling). The ApiResponse envelope does not apply to a stream of events, each + // element is a bare OrderResponse. The literal segment "stream" wins over the "/{id}" template. + @GET + @Path("/stream") + @Produces(MediaType.SERVER_SENT_EVENTS) + @RestStreamElementType(MediaType.APPLICATION_JSON) + // @Blocking only concerns the request pipeline: the JWT blacklist filter runs a JDBC query, which + // is forbidden on the event loop where a Multi endpoint would otherwise be dispatched. The stream + // itself stays fully reactive. + @Blocking + @PermissionsAllowed("ORDER:READ") + public Multi stream() { + return broadcaster.stream(); + } + @GET @Path("/{id}") @PermissionsAllowed("ORDER:READ") From 47a9e04fe371b0bf7e145ca9e5735d284624ffc3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 10/14] test(service): give the order service a mocked event in the unit tests Creating an order now fires an event, so the plain Mockito tests, which build the service without a container, need a mock of the event source to avoid a null pointer. Their assertions are unchanged. --- .../quarkustutorial/service/impl/OrderServiceImplTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java index efebf54..4d3883b 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java @@ -17,6 +17,8 @@ import com.edgareldy.quarkustutorial.repository.ProductRepository; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; +import com.edgareldy.quarkustutorial.service.event.OrderCreatedEvent; +import jakarta.enterprise.event.Event; import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.BeforeEach; @@ -39,13 +41,16 @@ class OrderServiceImplTest { private CustomerRepository customerRepository; private ProductRepository productRepository; private OrderServiceImpl service; + private Event orderCreatedEvent; @BeforeEach void setUp() { orderRepository = mock(OrderRepository.class); customerRepository = mock(CustomerRepository.class); productRepository = mock(ProductRepository.class); + orderCreatedEvent = mock(Event.class); service = new OrderServiceImpl(); + service.orderCreatedEvent = orderCreatedEvent; service.orderRepository = orderRepository; service.customerRepository = customerRepository; service.productRepository = productRepository; From f5e96e17d0e27c60ca4b9a64cc33fb1903602fbf Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 11/14] test(service): assert the broadcast with a Mutiny subscriber The tests subscribe with an AssertSubscriber and wait with a timeout, so the test thread is never blocked. They check that a committed order arrives with all its fields, that a rolled back one emits nothing, that two subscribers both receive it, and that a late subscriber gets no replay. The subscription runs in a duplicated Vert.x context marked safe, which is what Quarkus REST provides for each request and what Hibernate Reactive Panache requires. --- .../impl/OrderEventBroadcasterTest.java | 200 ++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java new file mode 100644 index 0000000..bf441cb --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java @@ -0,0 +1,200 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.entity.Product; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import com.edgareldy.quarkustutorial.service.OrderService; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import io.smallrye.mutiny.helpers.test.AssertSubscriber; +import io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle; +import io.smallrye.common.vertx.VertxContext; +import io.vertx.core.Context; +import io.vertx.core.Vertx; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.time.Duration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests the CDI to Mutiny bridge: committed orders reach every current subscriber, rolled back ones + * reach nobody, and late subscribers get no replay (hot stream). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest boots the real application (Dev Services PostgreSQL, blocking and reactive units). The +// AssertSubscriber from Mutiny's test helpers records the events of a Multi without blocking the test +// thread: awaitItems(n, timeout) polls with a deadline, so a missing event fails fast instead of hanging. +@QuarkusTest +class OrderEventBroadcasterTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + @Inject + OrderEventBroadcaster broadcaster; + + @Inject + OrderService orderService; + + @Inject + CategoryRepository categoryRepository; + + @Inject + CustomerRepository customerRepository; + + @Inject + ProductRepository productRepository; + + @Inject + EntityManager em; + + // The test thread has no Vert.x context, and stream() captures Vertx.currentContext() to hop back + // onto it before the reactive DB lookup. Hibernate Reactive also insists on a duplicated context (the per-request child context Quarkus REST + // creates), a plain root context fails with "not a duplicated context", and it must be flagged safe + // (isolated, one request only) or Panache refuses it. Subscribing from inside one reproduces what + // the SSE endpoint does on its event loop. + @Inject + Vertx vertx; + + private Long categoryId; + private Long customerId; + private Long productId; + + @BeforeEach + void setUp() { + QuarkusTransaction.requiringNew().run(() -> { + Category cat = new Category(); + cat.setCategoryName("stream-" + System.nanoTime()); + categoryRepository.persist(cat); + categoryId = cat.getId(); + Customer c = new Customer(); + c.setFirstName("Ada"); + c.setLastName("Lovelace"); + customerRepository.persist(c); + customerId = c.getId(); + Product p = new Product(); + p.setCategory(cat); + p.setProductName("P" + System.nanoTime()); + p.setUnitPrice(new BigDecimal("2.50")); + productRepository.persist(p); + productId = p.getId(); + }); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + em.createNativeQuery("delete from orders where customer_id = ?1").setParameter(1, customerId) + .executeUpdate(); + em.createNativeQuery("delete from customers where id = ?1").setParameter(1, customerId) + .executeUpdate(); + em.createNativeQuery("delete from products where id = ?1").setParameter(1, productId) + .executeUpdate(); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, categoryId) + .executeUpdate(); + }); + } + + private AssertSubscriber subscribe() { + AssertSubscriber subscriber = AssertSubscriber.create(Long.MAX_VALUE); + Context context = VertxContext.getOrCreateDuplicatedContext(vertx); + VertxContextSafetyToggle.setContextSafe(context, true); + context.runOnContext(ignored -> broadcaster.stream().subscribe().withSubscriber(subscriber)); + // Give the subscription time to reach the BroadcastProcessor before the order is created + // (a hot stream drops anything emitted before the subscriber is attached). + sleep(300); + return subscriber; + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private OrderResponse create() { + return orderService.create(new OrderRequest(customerId, productId, 3)); + } + + private void assertMatches(OrderResponse expected, OrderResponse received) { + assertEquals(expected.id(), received.id()); + assertEquals(customerId, received.customerId()); + assertEquals(productId, received.productId()); + assertEquals(3, received.quantity()); + assertEquals(0, new BigDecimal("7.50").compareTo(received.total())); + } + + @Test + void committedOrderIsEmittedToTheSubscriber() { + AssertSubscriber subscriber = subscribe(); + OrderResponse created = create(); + + subscriber.awaitItems(1, TIMEOUT); + assertEquals(1, subscriber.getItems().size()); + assertMatches(created, subscriber.getItems().get(0)); + subscriber.cancel(); + } + + @Test + void rolledBackCreationEmitsNothing() { + AssertSubscriber subscriber = subscribe(); + + assertThrows(BusinessRuleException.class, + () -> orderService.create(new OrderRequest(customerId, 999_999_999L, 1))); + + sleep(1000); + assertTrue(subscriber.getItems().isEmpty()); + subscriber.cancel(); + } + + @Test + void everyCurrentSubscriberReceivesTheEvent() { + AssertSubscriber first = subscribe(); + AssertSubscriber second = subscribe(); + OrderResponse created = create(); + + first.awaitItems(1, TIMEOUT); + second.awaitItems(1, TIMEOUT); + assertMatches(created, first.getItems().get(0)); + assertMatches(created, second.getItems().get(0)); + first.cancel(); + second.cancel(); + } + + @Test + void lateSubscriberDoesNotReceiveAnAlreadyCreatedOrder() { + AssertSubscriber early = subscribe(); + create(); + early.awaitItems(1, TIMEOUT); + + AssertSubscriber late = subscribe(); + sleep(1000); + assertTrue(late.getItems().isEmpty()); + + // The late subscriber is live, though: it gets the next order. + OrderResponse next = create(); + late.awaitItems(1, TIMEOUT); + assertEquals(1, late.getItems().size()); + assertEquals(next.id(), late.getItems().get(0).id()); + early.cancel(); + late.cancel(); + } +} From feb83cc448ece14c755000018b2faa89ccf7bea8 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 12/14] test(resource): cover the SSE endpoint over HTTP A JDK HTTP client opens the stream asynchronously, an order is then posted through the normal endpoint, and a data line with the new order must arrive within a timeout. The test also checks the event stream content type, the 401 without a token and the 403 without the read permission, and closes the stream at the end so no connection leaks. --- .../resource/OrderStreamResourceTest.java | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java new file mode 100644 index 0000000..4e316ef --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java @@ -0,0 +1,163 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.net.URI; +import java.net.URL; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * HTTP-level tests of the order Server-Sent Events endpoint: content type, authentication, + * permission and delivery of a newly created order as a {@code data:} event. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// RestAssured cannot consume an endless response, so the stream is opened with the JDK HttpClient in +// asynchronous mode (sendAsync + BodyHandlers.ofLines): the call returns once the headers arrive and +// the event lines are read on a separate thread. @TestHTTPResource injects the running test server URL +// (port from %test.quarkus.http.test-port). +@QuarkusTest +class OrderStreamResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String STREAM = "/api/v1/orders/stream"; + private static final String JSON = "application/json"; + + @TestHTTPResource("/") + URL root; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + private final List products = new ArrayList<>(); + private final List customers = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + customers.forEach(id -> em.createNativeQuery("delete from orders where customer_id = ?1") + .setParameter(1, id).executeUpdate()); + customers.forEach(id -> em.createNativeQuery("delete from customers where id = ?1") + .setParameter(1, id).executeUpdate()); + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1") + .setParameter(1, id).executeUpdate()); + categories.forEach(id -> em.createNativeQuery("delete from categories where id = ?1") + .setParameter(1, id).executeUpdate()); + }); + categories.clear(); + products.clear(); + customers.clear(); + support.cleanup(); + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("stream-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + private HttpRequest.Builder streamRequest(String token) { + return HttpRequest.newBuilder(URI.create(root.toString().replaceAll("/$", "") + STREAM)) + .header("Authorization", "Bearer " + token).header("Accept", "text/event-stream").GET(); + } + + @Test + void streamWithoutTokenIs401() { + given().accept("text/event-stream").when().get(STREAM).then().statusCode(401); + } + + @Test + void streamWithoutOrderReadIs403Problem() { + String token = tokenWith("ORDER:WRITE"); + given().auth().oauth2(token).accept("text/event-stream").when().get(STREAM) + .then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void createdOrderIsPushedAsADataEventWithEventStreamContentType() throws Exception { + Long category = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryName\":\"" + RbacTestSupport.unique("cat") + "\"}").when() + .post("/api/v1/categories").then().statusCode(201).extract().jsonPath().getLong("data.id"); + categories.add(category); + Long product = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryId\":" + category + ",\"productName\":\"P\",\"unitPrice\":2.50}") + .when().post("/api/v1/products").then().statusCode(201).extract().jsonPath().getLong("data.id"); + products.add(product); + Long customer = given().auth().oauth2(admin).contentType(JSON) + .body("{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\"}").when().post("/api/v1/customers") + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + customers.add(customer); + String reader = tokenWith("ORDER:READ"); + String writer = tokenWith("ORDER:WRITE"); + + HttpClient client = HttpClient.newHttpClient(); + HttpResponse> response = client + .sendAsync(streamRequest(reader).build(), HttpResponse.BodyHandlers.ofLines()) + .get(10, TimeUnit.SECONDS); + try { + assertEquals(200, response.statusCode()); + String contentType = response.headers().firstValue("Content-Type").orElse(""); + org.hamcrest.MatcherAssert.assertThat(contentType, startsWith("text/event-stream")); + + // Read on another thread: findFirst() blocks until a data line arrives. + CompletableFuture dataLine = CompletableFuture.supplyAsync( + () -> response.body().filter(line -> line.startsWith("data:")).findFirst().orElse(null)); + // The response headers are out, so the subscription is in place; a short pause covers the + // hop onto the reactive side before the order is committed. + Thread.sleep(500); + + Long orderId = given().auth().oauth2(writer).contentType(JSON) + .body("{\"customerId\":" + customer + ",\"productId\":" + product + ",\"quantity\":3}") + .when().post("/api/v1/orders").then().statusCode(201).extract().jsonPath() + .getLong("data.id"); + + String line = dataLine.get(10, TimeUnit.SECONDS); + assertNotNull(line); + JsonPath event = JsonPath.from(line.substring("data:".length()).trim()); + assertEquals(orderId, event.getLong("id")); + assertEquals(customer, event.getLong("customerId")); + assertEquals(product, event.getLong("productId")); + assertEquals(3, event.getInt("quantity")); + assertEquals(0, new java.math.BigDecimal("7.50").compareTo(new java.math.BigDecimal(event.getString("total")))); + } finally { + // Closing the line stream cancels the HTTP response subscription and drops the connection, + // so the server side subscriber is released and nothing leaks into other tests. + response.body().close(); + } + } +} From 29dea799bad29501a0f170bc7cd352860d16da6f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 13/14] docs(readme): check off feature/reactive-endpoints The five tasks are ticked: the reactive dependencies and persistence unit, the reactive repository, the CDI event bridged into a Multi, the SSE endpoint, and the tests. --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7fcb6ee..b8f6951 100644 --- a/README.md +++ b/README.md @@ -421,11 +421,11 @@ Quarkus lets imperative (blocking, Panache-based) and reactive (Mutiny-based) co ### Tasks -- [ ] `quarkus-hibernate-reactive-panache`, `quarkus-reactive-pg-client` added alongside the existing blocking `quarkus-jdbc-postgresql` stack - both drivers coexist against the same PostgreSQL database, Dev Services provisions the container either way -- [ ] `OrderPanacheRepositoryReactive` (`PanacheRepositoryBase` from the reactive variant), used only by the streaming endpoint - the rest of `feature/orders`' blocking repository and service stay untouched -- [ ] A CDI event or a `Multi`-backed broadcast: `OrderServiceImpl.create` (blocking) publishes a plain CDI event after a successful commit; a reactive listener adapts that into a `Multi` that the streaming endpoint subscribes to -- [ ] `OrderResource.stream()`: returns `Multi` with `@Produces(MediaType.SERVER_SENT_EVENTS)` - no manual thread management, Mutiny's operators handle backpressure -- [ ] Tests: a `Multi` assertion subscriber (`AssertSubscriber`) verifying an event arrives on the stream after a `POST /api/v1/orders`, run without blocking the test thread +- [x] `quarkus-hibernate-reactive-panache`, `quarkus-reactive-pg-client` added alongside the existing blocking `quarkus-jdbc-postgresql` stack - both drivers coexist against the same PostgreSQL database, Dev Services provisions the container either way +- [x] `OrderPanacheRepositoryReactive` (`PanacheRepositoryBase` from the reactive variant), used only by the streaming endpoint - the rest of `feature/orders`' blocking repository and service stay untouched +- [x] A CDI event or a `Multi`-backed broadcast: `OrderServiceImpl.create` (blocking) publishes a plain CDI event after a successful commit; a reactive listener adapts that into a `Multi` that the streaming endpoint subscribes to +- [x] `OrderResource.stream()`: returns `Multi` with `@Produces(MediaType.SERVER_SENT_EVENTS)` - no manual thread management, Mutiny's operators handle backpressure +- [x] Tests: a `Multi` assertion subscriber (`AssertSubscriber`) verifying an event arrives on the stream after a `POST /api/v1/orders`, run without blocking the test thread ## Order of work From 455553e4104826a9b0133ce108bfa6bd93aa76b9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:05:32 +0400 Subject: [PATCH 14/14] fix(service): keep the order stream alive when one reload fails Each broadcast id is reloaded from the database before it is sent. A missing row or a transient error used to fail that step and terminate the whole subscription, so a client would silently lose every later order until it reconnected. A missing row is now skipped, and a failed reload is logged and dropped, so one bad element costs one event and not the connection. --- .../service/impl/OrderEventBroadcaster.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java index 666c2a6..1e1036f 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java @@ -14,6 +14,7 @@ import jakarta.enterprise.event.Observes; import jakarta.enterprise.event.TransactionPhase; import jakarta.inject.Inject; +import org.jboss.logging.Logger; /** * Bridges the blocking order creation to the reactive world: turns committed-order CDI events into a @@ -34,6 +35,8 @@ public class OrderEventBroadcaster { // request threads safe. private final SerializedProcessor processor = BroadcastProcessor.create().serialized(); + private static final Logger LOG = Logger.getLogger(OrderEventBroadcaster.class); + @Inject OrderPanacheRepositoryReactive orderRepository; @@ -70,7 +73,11 @@ private Uni load(Long id) { // Opens a reactive session on the named "reactive" persistence unit for the duration of the // lookup (the no-argument variant would look for the default unit, which is blocking). return Panache.withSession("reactive", () -> orderRepository.findById(id)) - .map(order -> new OrderResponse(order.getId(), order.getCustomerId(), order.getProductId(), - order.getQuantity(), order.getTotal())); + // A missing row (null) is simply skipped by the stream, and a failed reload is logged and + // dropped: one bad element must not terminate the whole subscription for that client. + .onItem().ifNotNull().transform(order -> new OrderResponse(order.getId(), order.getCustomerId(), + order.getProductId(), order.getQuantity(), order.getTotal())) + .onFailure().invoke(e -> LOG.warnf(e, "Could not reload order %d for the stream", id)) + .onFailure().recoverWithNull(); } }