diff --git a/AGENTS.md b/AGENTS.md index 5acb100..ccd621e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ src/main/java/community/solace/spring/cloud/requestreply/ │ ├── logging/LoggerAutoConfiguration.java │ └── messageinterceptor/ # Noop*Interceptor beans + MessageInterceptorAutoConfiguration ├── env/ # ${replyTopicWithWildcards|...} property source -├── util/ # MessageChunker, CheckedExceptionWrapper +├── util/ # MessageChunker, CheckedExceptionWrapper, MessageTimeToLive └── exception/ # RequestReplyException src/main/resources/META-INF/ ├── spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports # auto-config registration @@ -118,7 +118,9 @@ Invariants the wrappers must preserve: to close the stream, - forward a matching `applicationException` as an error reply (`errorMessage` header) which the requester surfaces as `RemoteErrorException` (or an errored `Flux`), -- copy any headers listed in `copyHeadersOnWrap`. +- copy any headers listed in `copyHeadersOnWrap`, +- set `solace_timeToLive` on every reply, the terminal and error replies included, to the request's + time‑to‑live (see §6). **Reply routing:** for each `bindingMapping`, `RequestReplyFunctionRegistrar` registers a `Consumer>` bean named after the binding, wired to `-in-0`, delegating to @@ -154,7 +156,9 @@ contexts (see §6). If a bean with the binding name already exists, do not overr - **Header access goes through the ordered parser chain**, never by reading a hard‑coded header key inline. To support a new binder or header convention, add a parser bean and order it with `@Order` (lower = higher priority). Header name constants live in `SpringHeaderParser` (`totalReplies`, `replyIndex`, - `groupedMessages`, `groupedContentType`, `errorMessage`) — reuse them. + `groupedMessages`, `groupedContentType`, `errorMessage`) — reuse them. The one exception is the Solace + message lifetime (`solace_timeToLive`, `solace_expiration`): it is Solace‑only on the write side, so a + pluggable read side would buy nothing, and `MessageTimeToLive` reads and writes it directly. - **Correlation ids** are generated as a random UUID unless the request already carries one. - **Reply‑to uniqueness:** reply topics should be process‑unique. Use `${replyTopicWithWildcards|uuid}` (generated once at process start) — not `${random.uuid}` (new value per reference). The requester listens @@ -163,6 +167,14 @@ contexts (see §6). If a bean with the binding name already exists, do not overr messages bypass dedup. The unknown/streaming growth bound is read as a **JVM system property** `spring.cloud.stream.requestreply.dedup.maxBitsWhenUnknown` (via `Integer.getInteger`, default 100000) — it is **not** a Spring `@ConfigurationProperties` value, so it is set with `-D`, not `application.yaml`. +- **Message time‑to‑live follows the timeout.** The requester stamps the timeout as `solace_timeToLive`; a + reply takes the request's time‑to‑live unchanged. A responder cannot know what is left of it: a message + arrives with the time‑to‑live its sender set, and JCSMP does not send the end of life (`expiration`) it + derives from it. `MessageTimeToLive` is the one place that reads and writes it, and it keeps three rules: + stay between 1 ms and ten years (Solace reads 0 as "never expire", and JCSMP refuses to send more than ten + years); never overwrite a lifetime the message already carries; and never set a time‑to‑live and + `solace_expiration` together. On a reply it is set after every other header, `additionalHeaders` + included, so that it sees a lifetime the caller set. - **Grouping thresholds** are load‑bearing constants: flush at 1 MB, at 10 000 messages, or after the group timeout (default 200 ms). Changing them affects broker behaviour and interop — do so deliberately and document it. diff --git a/CHANGELOG.md b/CHANGELOG.md index 793adc3..6cffa3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] +### Added +- The request/reply timeout is now also the Solace time-to-live (`solace_timeToLive`) of the messages, so a request nobody answered in time, or a reply that comes too late, no longer waits on a persistent queue to be processed after the requester gave up. A request gets the timeout, kept between 1 ms and ten years; a reply built by the `wrap*` helpers gets the time-to-live of the request. A message that already carries `solace_timeToLive` or `solace_expiration` keeps its own lifetime, because the two must never both be set. ([#84](https://github.com/solacecommunity/spring-cloud-stream-request-reply/issues/84)) + +### Changed +- Requests and replies now expire on a queue that respects the time-to-live. An application that relied on a responder working through requests after the requester gave up has to pass `solace_timeToLive` = `0L` in `additionalHeaders`, which sends a request that never expires. An expired message moves to the queue's dead message queue if there is one, because the Solace binder marks messages DMQ-eligible by default. ([#84](https://github.com/solacecommunity/spring-cloud-stream-request-reply/issues/84)) +- A `solace_timeToLive` in a binding's producer `defaultHeader` is now overridden by the library's time-to-live; set it in `additionalHeaders` or an interceptor instead. ([#84](https://github.com/solacecommunity/spring-cloud-stream-request-reply/issues/84)) + ## [6.1.5] - 2026-11-13 ### Changed - Updated spring-boot-starter-solace-client-config from 3.1.4 to 3.1.5 diff --git a/README.md b/README.md index 21e9d6a..5797c81 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ to the caller. - Non‑blocking variants returning `CompletableFuture` or reactive `Flux`. - **Request / multi‑reply**: receive zero to N answers for one request. - Per‑request **timeouts** and automatic cleanup of in‑flight bookkeeping. +- The timeout is also the Solace **time‑to‑live** of the request and its replies, so neither waits on a queue + long after the requester gave up. - Automatic **correlation id** generation and reply‑to routing. - Helper methods (`wrap`, `wrapList`, `wrapFlux`) for the responder side that set the reply headers for you and can **forward selected exceptions** back to the requester. @@ -199,6 +201,39 @@ Every method takes a `Duration timeoutPeriod`. The request is sent and the reply executor; if no (final) reply arrives in time the pending request is aborted and a `TimeoutException` is raised. Bookkeeping for the request is always cleaned up on success, error or timeout. +### Message time‑to‑live + +A request that is not answered within the timeout, and a reply that arrives after it, are of no use to +anyone. The library therefore sets the Solace time‑to‑live (`solace_timeToLive`): + +- on the **request**, to the timeout, kept within what Solace accepts: a timeout below 1 ms is sent as + 1 ms, because 0 means "never expire", and one above ten years as ten years, because JCSMP refuses to + send a longer one; +- on every **reply** built by the `wrap*` helpers, to the time‑to‑live of the request. A reply therefore + lives at most one timeout after it was sent. A request without a time‑to‑live gets replies without one. + +A time‑to‑live you set yourself wins: on a request `Message`, in `additionalHeaders`, or copied onto the +reply with `copyHeadersOnWrap`. A time‑to‑live and an expiration must never both be set, so a message that +carries `solace_expiration` gets no time‑to‑live. To send a request that never expires, pass +`solace_timeToLive` = `0L` in `additionalHeaders`. A `solace_timeToLive` in the binding's producer +`defaultHeader` no longer applies, because the Solace binder lets a message header win over a default; set +it in `additionalHeaders` or an interceptor instead. + +A message interceptor runs last and sees the time‑to‑live the library set; it may change or remove it. +An interceptor that sets `solace_expiration` has to remove `solace_timeToLive`. + +A request `Message` that arrived over Solace carries `solace_timeToLive` and `solace_expiration` already, +0 if its sender set none. Sent on as a request, it keeps that lifetime instead of taking the timeout; +remove both headers to get the timeout. + +`additionalHeaders` given to `wrap` apply to the replies the wrapped function returns, not to the error +reply of a forwarded exception, which always takes the request's time‑to‑live. + +The broker only expires guaranteed messages, and only on a queue that respects the time‑to‑live +(`respect-ttl`). It discards an expired message, or moves it to the queue's dead message queue if there +is one: the Solace binder marks messages DMQ‑eligible by default (`solace_dmqEligible`). On a direct +message the time‑to‑live has no effect. + ### Single vs. multi response - **Single response** — you expect exactly one answer. Use `requestAndAwaitReply*` (blocking) or @@ -573,7 +608,8 @@ See [`examples/customized_logging`](examples/customized_logging) for a full appl [`examples/customized_reply_to_header_response`](examples/customized_reply_to_header_response). Both interfaces receive the binding name so you can behave differently per binding. If you do not -provide your own, no‑op implementations are auto‑configured. +provide your own, no‑op implementations are auto‑configured. The message an interceptor receives already +carries the time‑to‑live the library set (see [Message time‑to‑live](#message-timetolive)). ### Extending to other binders diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyService.java b/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyService.java index faa552f..0bdd610 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyService.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyService.java @@ -21,7 +21,7 @@ public interface RequestReplyService { * @param request the request to be sent * @param requestDestination the topic name to send the request to. Example: my.supper.topic * @param expectedClass the class the response shall be mapped to. - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ default A requestAndAwaitReplyToTopic( @@ -41,7 +41,7 @@ default A requestAndAwaitReplyToTopic( * @param request the request to be sent * @param requestDestination the topic name to send the request to. Example: my.supper.topic * @param expectedClass the class the response shall be mapped to. - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @param additionalHeaders additional headers to be added to the request message * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ @@ -61,7 +61,7 @@ A requestAndAwaitReplyToTopic( * @param request the request to be sent * @param bindingName the message channel name to send the request to. Example: requestReplyRepliesDemoTibrv * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ default A requestAndAwaitReplyToBinding( @@ -81,7 +81,7 @@ default A requestAndAwaitReplyToBinding( * @param request the request to be sent * @param bindingName the message channel name to send the request to. Example: requestReplyRepliesDemoTibrv * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @param additionalHeaders additional headers to be added to the request message * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ @@ -103,7 +103,7 @@ A requestAndAwaitReplyToBinding( * @param request the request to be sent * @param bindingName the message channel name to send the request to. Example: requestReplyRepliesDemoTibrv * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ default CompletableFuture requestReplyToBinding( @@ -125,7 +125,7 @@ default CompletableFuture requestReplyToBinding( * @param request the request to be sent * @param bindingName the message channel name to send the request to. Example: requestReplyRepliesDemoTibrv * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @param additionalHeaders additional headers to be added to the request message * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ @@ -147,7 +147,7 @@ CompletableFuture requestReplyToBinding( * @param request the request to be sent * @param requestDestination the topic name to send the request to. Example: my.supper.topic * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ default CompletableFuture requestReplyToTopic( @@ -169,7 +169,7 @@ default CompletableFuture requestReplyToTopic( * @param request the request to be sent * @param requestDestination the topic name to send the request to. Example: my.supper.topic * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @param additionalHeaders additional headers to be added to the request message * @return a {@link CompletableFuture} which can be used to await and retrieve the response */ @@ -191,7 +191,7 @@ CompletableFuture requestReplyToTopic( * @param request the request to be sent * @param bindingName the message channel name to send the request to. Example: requestReplyRepliesDemoTibrv * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @return a {@link Flux} which can be used to receive responses */ default Flux requestReplyToBindingReactive( @@ -213,7 +213,7 @@ default Flux requestReplyToBindingReactive( * @param request the request to be sent * @param bindingName the message channel name to send the request to. Example: requestReplyRepliesDemoTibrv * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @param additionalHeaders additional headers to be added to the request message * @return a {@link Flux} which can be used to receive responses */ @@ -236,7 +236,7 @@ Flux requestReplyToBindingReactive( * @param request the request to be sent * @param requestDestination the topic name to send the request to. Example: my.supper.topic * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @return a {@link Flux} which can be used to receive responses */ default Flux requestReplyToTopicReactive( @@ -258,7 +258,7 @@ default Flux requestReplyToTopicReactive( * @param request the request to be sent * @param requestDestination the topic name to send the request to. Example: my.supper.topic * @param expectedClass the class the response shall be mapped to - * @param timeoutPeriod the timeout when to give up waiting for a response + * @param timeoutPeriod the timeout when to give up waiting for a response, also set as the Solace time-to-live of the request unless it carries a lifetime of its own * @param additionalHeaders additional headers to be added to the request message * @return a {@link Flux} which can be used to receive responses */ diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyServiceImpl.java b/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyServiceImpl.java index ef9df79..fb212ff 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyServiceImpl.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/RequestReplyServiceImpl.java @@ -42,6 +42,7 @@ import org.slf4j.event.Level; import static community.solace.spring.cloud.requestreply.util.CheckedExceptionWrapper.throwingUnchecked; +import static community.solace.spring.cloud.requestreply.util.MessageTimeToLive.setTimeToLiveIfAbsent; /** * The RequestReplyService takes care of asynchronous request and reply messages, relating one to the other and allowing to wrap both as a synchronous call. @@ -344,6 +345,7 @@ private CompletableFuture requestReply( messageBuilder.setHeader(header.getKey(), header.getValue()); } } + setTimeToLiveIfAbsent(messageBuilder, timeoutPeriod); Message toSend = requestSendingInterceptor.interceptRequestSendingMessage(messageBuilder.build(), bindingName); diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyMessageHeaderSupportService.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyMessageHeaderSupportService.java index 86b7cec..b0c40ce 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyMessageHeaderSupportService.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyMessageHeaderSupportService.java @@ -38,6 +38,8 @@ import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; +import static community.solace.spring.cloud.requestreply.util.MessageTimeToLive.copyTimeToLiveIfAbsent; + @Service public class RequestReplyMessageHeaderSupportService { @@ -151,7 +153,7 @@ public String getErrorMessage(Message message) { /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID and target + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -167,7 +169,7 @@ public final > Function, Messa /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID and target + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -186,7 +188,7 @@ public final > Function, Messa /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID and target + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -214,6 +216,7 @@ public final > Function, Messa mb.setHeader(header.getKey(), header.getValue()); } } + copyTimeToLiveIfAbsent(request, mb); return this.replyWrappingInterceptor.interceptReplyWrappingPayloadMessage(mb.build(), bindingName); } catch (Exception e) { @@ -234,7 +237,7 @@ public final > Function, Messa /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID and target + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -333,7 +336,7 @@ private List> wrapListGroupedResponses(Message request, Lis /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID and target + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -347,7 +350,7 @@ public final Function>, Flux>> wrapFlux(BiCons /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID and target + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -433,6 +436,7 @@ private void transferAndAdoptHeaders(Message request, MessageBuilder void transferAndAdoptHeaders(Message request, diff --git a/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java b/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java new file mode 100644 index 0000000..7ae4573 --- /dev/null +++ b/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java @@ -0,0 +1,81 @@ +package community.solace.spring.cloud.requestreply.util; + +import java.time.Duration; +import java.util.Map; + +import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; + +/** + * Gives a request or a reply the Solace time-to-live after which the broker discards it, so that it does not wait on + * a queue long after the requester stopped waiting for it. The only place that reads and writes the Solace lifetime + * headers. + */ +public final class MessageTimeToLive { + /** + * The Solace header with the milliseconds after which the broker discards the message; 0 means never. + */ + public static final String TIME_TO_LIVE = "solace_timeToLive"/*SolaceHeaders.TIME_TO_LIVE*/; + /** + * The Solace header with the time at which the message expires; never set together with {@link #TIME_TO_LIVE}. + */ + public static final String EXPIRATION = "solace_expiration"/*SolaceHeaders.EXPIRATION*/; + + /** + * Solace reads a time-to-live of 0 as "never expire", so a lifetime below a millisecond is written as this. + */ + private static final Duration SHORTEST_TIME_TO_LIVE = Duration.ofMillis(1); + /** + * JCSMP rejects a longer time-to-live with an {@link IllegalArgumentException} when the message is sent. + */ + private static final Duration LONGEST_TIME_TO_LIVE = Duration.ofDays(3650); + + private MessageTimeToLive() { + } + + /** + * Sets the time-to-live of the message, unless it already carries a lifetime of its own: a time-to-live, or an + * expiration. A Solace message must never carry both. + * + * @param messageBuilder the message to set the time-to-live on + * @param timeToLive how long the message stays useful; written as at least one millisecond and at most ten + * years, the bounds Solace accepts + */ + public static void setTimeToLiveIfAbsent(MessageBuilder messageBuilder, Duration timeToLive) { + Map headers = messageBuilder.getHeaders(); + boolean carriesLifetime = headers.containsKey(TIME_TO_LIVE) || + headers.containsKey(EXPIRATION); + if (carriesLifetime) { + return; + } + + messageBuilder.setHeader(TIME_TO_LIVE, withinTheBoundsSolaceAccepts(timeToLive).toMillis()); + } + + /** + * Gives a reply the time-to-live of its request, unless the reply already carries a lifetime of its own. Call it + * after every other header of the reply is set, so that it sees a lifetime the caller set. A request that never + * expires gets a reply without a time-to-live, which never expires either. + * + * @param request the request the reply answers + * @param reply the reply to set the time-to-live on + */ + public static void copyTimeToLiveIfAbsent(Message request, MessageBuilder reply) { + Object requestTimeToLive = request.getHeaders().get(TIME_TO_LIVE); + if (!(requestTimeToLive instanceof Number millis) || millis.longValue() <= 0) { + return; + } + + setTimeToLiveIfAbsent(reply, Duration.ofMillis(millis.longValue())); + } + + private static Duration withinTheBoundsSolaceAccepts(Duration timeToLive) { + if (timeToLive.compareTo(SHORTEST_TIME_TO_LIVE) < 0) { + return SHORTEST_TIME_TO_LIVE; + } + if (timeToLive.compareTo(LONGEST_TIME_TO_LIVE) > 0) { + return LONGEST_TIME_TO_LIVE; + } + return timeToLive; + } +} \ No newline at end of file diff --git a/src/test/java/community/solace/spring/cloud/requestreply/service/RequestReplySimpleServiceTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/RequestReplySimpleServiceTests.java index f3dc0c7..eec25b5 100644 --- a/src/test/java/community/solace/spring/cloud/requestreply/service/RequestReplySimpleServiceTests.java +++ b/src/test/java/community/solace/spring/cloud/requestreply/service/RequestReplySimpleServiceTests.java @@ -13,6 +13,7 @@ import community.solace.spring.cloud.requestreply.model.SensorReading; import community.solace.spring.cloud.requestreply.service.header.parser.SpringHeaderParser; import community.solace.spring.cloud.requestreply.service.header.parser.errormessage.RemoteErrorException; +import community.solace.spring.cloud.requestreply.util.MessageTimeToLive; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -32,12 +33,14 @@ import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; class RequestReplySimpleServiceTests extends AbstractRequestReplySimpleIT { private static final Duration THREAD_LEAK_TIME_LIMIT = Duration.ofSeconds(20); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(10); ArgumentCaptor> messageCaptor = ArgumentCaptor.forClass(Message.class); ArgumentCaptor destinationCaptor = ArgumentCaptor.forClass(String.class); @@ -287,6 +290,131 @@ void requestAndAwaitReplyToTopic_expectAdditionalHeaders_whenRequestReceived() t } + @Test + void requestAndAwaitReplyToTopic_expectTimeoutAsTimeToLive_whenRequestSent() throws Exception { + answerEveryRequestAtOnce(); + + requestReplyService.requestAndAwaitReplyToTopic( + new SensorReading(), + "last_value/temperature/celsius/demo", + SensorReading.class, + REQUEST_TIMEOUT + ); + + assertEquals( + REQUEST_TIMEOUT.toMillis(), + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void requestReplyToTopicReactive_expectTimeoutAsTimeToLive_whenRequestSent() { + answerEveryRequestAtOnce(); + + Flux flux = requestReplyService.requestReplyToTopicReactive( + new SensorReading(), + "last_value/temperature/celsius/demo", + SensorReading.class, + REQUEST_TIMEOUT + ); + + StepVerifier + .create(flux) + .expectComplete() + .verify(Duration.ofSeconds(10)); + + assertEquals( + REQUEST_TIMEOUT.toMillis(), + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void requestAndAwaitReplyToTopic_expectCallersTimeToLive_whenGivenInAdditionalHeaders() throws Exception { + long neverExpire = 0L; + answerEveryRequestAtOnce(); + + requestReplyService.requestAndAwaitReplyToTopic( + new SensorReading(), + "last_value/temperature/celsius/demo", + SensorReading.class, + REQUEST_TIMEOUT, + Map.of(MessageTimeToLive.TIME_TO_LIVE, neverExpire) + ); + + assertEquals( + neverExpire, + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void requestAndAwaitReplyToTopicWithMsg_expectItsTimeToLiveKept_whenMessageCarriesOne() throws Exception { + long timeToLiveOfTheMessage = 5_000L; + answerEveryRequestAtOnce(); + + requestReplyService.requestAndAwaitReplyToTopic( + MessageBuilder.withPayload(new SensorReading()) + .setHeader(MessageTimeToLive.TIME_TO_LIVE, timeToLiveOfTheMessage) + .build(), + "last_value/temperature/celsius/demo", + SensorReading.class, + REQUEST_TIMEOUT + ); + + assertEquals( + timeToLiveOfTheMessage, + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) + ); + } + + /** + * A Solace message must never carry a time-to-live and an expiration together, so a request that carries an + * expiration must not get a time-to-live on top. + */ + @Test + void requestAndAwaitReplyToTopicWithMsg_expectNoTimeToLiveAdded_whenMessageCarriesAnExpiration() throws Exception { + answerEveryRequestAtOnce(); + + requestReplyService.requestAndAwaitReplyToTopic( + MessageBuilder.withPayload(new SensorReading()) + .setHeader(MessageTimeToLive.EXPIRATION, 1_682_928_000_000L) + .build(), + "last_value/temperature/celsius/demo", + SensorReading.class, + REQUEST_TIMEOUT + ); + + assertNull( + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) + ); + } + + /** + * A request whose timeout runs out before a worker picks it up is never sent. Answering inside the send lets the + * time-to-live tests use a timeout no test ever waits for. + */ + private void answerEveryRequestAtOnce() { + Mockito.when(streamBridge.send( + anyString(), + any(Message.class) + )) + .thenAnswer(invocation -> { + Message request = invocation.getArgument(1); + requestReplyService.onReplyReceived( + MessageBuilder.fromMessage(request) + .setHeader(SpringHeaderParser.MULTI_TOTAL_REPLIES, "0") + .build() + ); + return true; + }); + } + + private Message sentRequest() { + Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); + return messageCaptor.getValue(); + } + @Test void requestAndAwaitReplyToTopic_expectException_whenErrorResponse() { SensorReading request = new SensorReading(); diff --git a/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplySimpleMessageHeaderSupportServiceTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplySimpleMessageHeaderSupportServiceTests.java index f313d3a..bdc4a1a 100644 --- a/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplySimpleMessageHeaderSupportServiceTests.java +++ b/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplySimpleMessageHeaderSupportServiceTests.java @@ -4,6 +4,7 @@ import com.solacesystems.jcsmp.impl.sdt.StreamImpl; import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; import community.solace.spring.cloud.requestreply.service.header.parser.SpringHeaderParser; +import community.solace.spring.cloud.requestreply.util.MessageTimeToLive; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.binder.BinderHeaders; @@ -18,11 +19,13 @@ import java.time.Duration; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.*; class RequestReplySimpleMessageHeaderSupportServiceTests extends AbstractRequestReplySimpleIT { + private static final Duration REQUEST_TIME_TO_LIVE = Duration.ofSeconds(10); @Autowired RequestReplyMessageHeaderSupportService supportService; @@ -672,6 +675,138 @@ void wrapFlux_exception() { } + @Test + void wrap_expectTheRequestsTimeToLive_whenRequestCarriesOne() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); + + assertTheRequestsTimeToLive(answerM); + } + + @Test + void wrap_expectNoTimeToLive_whenRequestCarriesNone() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(MessageBuilder.withPayload("demo") + .setHeader("correlationId", "my-correlationId-my") + .setHeader(MessageHeaders.REPLY_CHANNEL, "my-dest-my/{StagePlaceholder}/the-event-after") + .build()); + + assertNull( + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) + ); + } + + @Test + void wrap_expectNoTimeToLive_whenRequestNeverExpires() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(requestWithTimeToLive(Duration.ZERO)); + + assertNull( + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) + ); + } + + @Test + void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { + long neverExpire = 0L; + Function, Message> supplier = supportService.wrap( + m -> m, + Map.of(MessageTimeToLive.TIME_TO_LIVE, neverExpire), + (Class) null + ); + + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); + + assertEquals( + neverExpire, + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) + ); + } + + /** + * A Solace message must never carry a time-to-live and an expiration together. + */ + @Test + void wrap_expectNoTimeToLive_whenAdditionalHeadersGiveAnExpiration() { + Function, Message> supplier = supportService.wrap( + m -> m, + Map.of(MessageTimeToLive.EXPIRATION, 1_682_928_000_000L), + (Class) null + ); + + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); + + assertNull( + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) + ); + } + + @Test + void wrap_exception_expectTheRequestsTimeToLiveOnTheErrorReply() { + Function, Message> supplier = supportService.wrap( + m -> { + throw new IllegalArgumentException("The error message"); + }, + IllegalArgumentException.class + ); + + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); + + assertTheRequestsTimeToLive(answerM); + } + + @Test + void wrapList_groupedResponses_expectTheRequestsTimeToLive() { + Function, List>> supplier = supportService.wrapList(m -> List.of(m, m), "requestReplyRepliesDemo-out-0", (Class) null); + + Message request = MessageBuilder.fromMessage(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)) + .setHeader(SpringHeaderParser.GROUPED_MESSAGES, true) + .build(); + List> answers = supplier.apply(request); + + assertEquals( + 1, + answers.size() + ); + assertTheRequestsTimeToLive(answers.get(0)); + } + + @Test + void wrapFlux_expectTheRequestsTimeToLiveOnEveryReply_includingTheFinishingOne() { + Function>, Flux>> supplier = supportService.wrapFlux((payloadIn, outSink) -> { + outSink.next("first msg"); + outSink.complete(); + }, "requestReplyRepliesDemo-out-0"); + + Flux> answers = supplier.apply(Flux.just(requestWithTimeToLive(REQUEST_TIME_TO_LIVE))); + + StepVerifier + .create(answers) + .consumeNextWith(this::assertTheRequestsTimeToLive) + .consumeNextWith(this::assertTheRequestsTimeToLive) + .expectComplete() + .verify(Duration.ofSeconds(10)); + } + + private static Message requestWithTimeToLive(Duration requestTimeToLive) { + return MessageBuilder.withPayload("demo") + .setHeader("correlationId", "my-correlationId-my") + .setHeader(MessageHeaders.REPLY_CHANNEL, "my-dest-my/{StagePlaceholder}/the-event-after") + .setHeader(MessageTimeToLive.TIME_TO_LIVE, requestTimeToLive.toMillis()) + .build(); + } + + private void assertTheRequestsTimeToLive(Message reply) { + assertEquals( + REQUEST_TIME_TO_LIVE.toMillis(), + reply.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class), + "The reply must expire like the request it answers" + ); + } + @Test void replyTopicWithWildcards() { assertEquals( diff --git a/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java b/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java new file mode 100644 index 0000000..3e0860f --- /dev/null +++ b/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java @@ -0,0 +1,44 @@ +package community.solace.spring.cloud.requestreply.util; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +import org.junit.jupiter.api.Test; + +import org.springframework.integration.support.MessageBuilder; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A timeout becomes the Solace time-to-live of a request, so it has to fit the bounds Solace accepts: 0 means + * "never expire", and JCSMP refuses to send a message whose time-to-live is longer than ten years. + */ +class MessageTimeToLiveTests { + private static final long TEN_YEARS_IN_MILLIS = 315_360_000_000L; + + @Test + void setTimeToLiveIfAbsent_expectOneMillisecond_whenTimeToLiveRoundsDownToZero() { + MessageBuilder messageBuilder = MessageBuilder.withPayload("demo"); + + MessageTimeToLive.setTimeToLiveIfAbsent(messageBuilder, Duration.ofNanos(500_000)); + + assertEquals( + 1L, + messageBuilder.build().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class), + "A time-to-live of 0 would let the message never expire" + ); + } + + @Test + void setTimeToLiveIfAbsent_expectTenYears_whenTheCallerWaitsForever() { + MessageBuilder messageBuilder = MessageBuilder.withPayload("demo"); + + MessageTimeToLive.setTimeToLiveIfAbsent(messageBuilder, ChronoUnit.FOREVER.getDuration()); + + assertEquals( + TEN_YEARS_IN_MILLIS, + messageBuilder.build().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class), + "JCSMP throws an IllegalArgumentException for a longer time-to-live, so the request would not be sent" + ); + } +} \ No newline at end of file