Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Order>` that the streaming endpoint subscribes to
- [ ] `OrderResource.stream()`: returns `Multi<Order>` 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<Order>` that the streaming endpoint subscribes to
- [x] `OrderResource.stream()`: returns `Multi<Order>` 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

Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-reactive-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-reactive-pg-client</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-flyway</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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; }
}
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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<ReactiveOrder, Long> {
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -48,6 +52,26 @@ public ApiResponse<PageResponse<OrderResponse>> 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<OrderResponse> stream() {
return broadcaster.stream();
}

@GET
@Path("/{id}")
@PermissionsAllowed("ORDER:READ")
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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) {
}
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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<Long, Long> processor = BroadcastProcessor.<Long>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<OrderResponse> 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<Long> 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<OrderResponse> 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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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> orderCreatedEvent;

@Override
@Transactional
public PageResponse<OrderResponse> list(int page, int size, Long customerId, Long productId) {
Expand Down Expand Up @@ -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);
}

Expand Down
25 changes: 25 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Loading
Loading