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 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 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 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; } +} 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 { +} 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") 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) { +} 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..1e1036f --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java @@ -0,0 +1,83 @@ +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; +import org.jboss.logging.Logger; + +/** + * 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(); + + private static final Logger LOG = Logger.getLogger(OrderEventBroadcaster.class); + + @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)) + // 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(); + } +} 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); } 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} 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(); + } + } +} 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(); + } +} 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;