From 6ef8bd2e3391e5e0902a38a6ece4296918f4ef0a Mon Sep 17 00:00:00 2001 From: Heiko Henning Date: Sat, 21 Nov 2026 17:52:36 +0100 Subject: [PATCH 1/6] feat: let request and reply expire when the requester stops waiting A request nobody answered in time, or a reply that came too late, stayed on a persistent queue without a time-to-live and was processed long after the requester had given up. The request now carries the timeout as its Solace time-to-live, and a reply what is left of it on the responder's clock. Closes #84 --- AGENTS.md | 15 +- CHANGELOG.md | 4 + README.md | 30 ++- .../service/RequestReplyService.java | 24 +-- .../service/RequestReplyServiceImpl.java | 2 + ...questReplyMessageHeaderSupportService.java | 66 ++++++- .../header/parser/SolaceHeaderParser.java | 23 ++- .../MessageHeaderTimeToLiveParser.java | 27 +++ .../timetolive/MessageTimeToLiveParser.java | 19 ++ .../requestreply/util/MessageTimeToLive.java | 41 +++++ .../service/HeaderParserTests.java | 11 ++ .../RequestReplySimpleServiceTests.java | 99 ++++++++++ .../RequestReplyCopiedTimeToLiveTests.java | 53 ++++++ ...impleMessageHeaderSupportServiceTests.java | 172 ++++++++++++++++++ 14 files changed, 563 insertions(+), 23 deletions(-) create mode 100644 src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java create mode 100644 src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java create mode 100644 src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java create mode 100644 src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java diff --git a/AGENTS.md b/AGENTS.md index 5acb100..88845ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,8 @@ src/main/java/community/solace/spring/cloud/requestreply/ │ ├── header/ │ │ ├── RequestReplyMessageHeaderSupportService.java # responder-side wrap/wrapList/wrapFlux helpers │ │ └── parser/ # ordered Message/MessageHeaders parsers (correlationId, -│ │ │ # destination, replyTo, replyIndex, totalReplies, errorMessage) +│ │ │ # destination, replyTo, replyIndex, totalReplies, errorMessage, +│ │ │ # timeToLive) │ │ ├── SolaceHeaderParser.java SpringHeaderParser.java HttpHeaderParser.java ... │ ├── logging/ # RequestReplyLogger + DefaultRequestReplyLogger │ └── messageinterceptor/ # RequestSendingInterceptor, ReplyWrappingInterceptor @@ -49,7 +50,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 +119,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 what is left of 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 @@ -163,6 +166,12 @@ 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 gets the request's time‑to‑live less the time since the request message was built on the responder, + so the responder's clock alone decides. `MessageTimeToLive` is the one place that writes it, and it keeps + three rules: never write 0 (Solace reads it as "never expire", so the minimum is 1 ms); never overwrite a + lifetime the message already carries; and never add a time‑to‑live next to `solace_expiration`, because + the Solace binder rejects a message whose two lifetime headers differ. - **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..f3803e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ 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; a reply built by the `wrap*` helpers gets the time-to-live the request arrived with, less the time since it arrived, and at least 1 ms. A message that already carries `solace_timeToLive` or `solace_expiration` keeps its own lifetime, and `additionalHeaders` with `solace_timeToLive` = `0` sends a request that never expires. A `solace_timeToLive` in a binding's producer `defaultHeader` is now overridden; set it in `additionalHeaders` or an interceptor instead. The broker expires a message only on a queue that respects the time-to-live, and moves it 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)) + ## [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..bf5942d 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ 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 outlives the wait. - 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 +200,32 @@ 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; +- on every **reply** built by the `wrap*` helpers, to the time‑to‑live the request arrived with, less the + time since it arrived. A request without a time‑to‑live gets replies without one. A reply whose request + has already expired gets 1 ms, because 0 means "never expire". + +A time‑to‑live you set yourself wins: on a request `Message`, in `additionalHeaders`, in a message +interceptor, or copied onto the reply with `copyHeadersOnWrap`. A message that carries +`solace_expiration` gets no time‑to‑live either, because the Solace binder rejects the two headers with +different values. 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. + +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. + +The reply's time‑to‑live is measured on the responder's own clock, from the moment the request message +was built there, so it does not depend on the requester's and responder's clocks agreeing. + ### Single vs. multi response - **Single response** — you expect exactly one answer. Use `requestAndAwaitReply*` (blocking) or @@ -595,12 +622,13 @@ Parser interfaces (root interface parses a `Message`, the `…Header…` variant - `MessageTotalRepliesParser` / `MessageHeaderTotalRepliesParser` - `MessageReplyIndexParser` / `MessageHeaderReplyIndexParser` - `MessageErrorMessageParser` / `MessageHeaderErrorMessageParser` +- `MessageTimeToLiveParser` / `MessageHeaderTimeToLiveParser` Bundled implementations, in priority order: | Parser | Order | Provides | |--------|-------|----------| -| `SolaceHeaderParser` | 200 | correlationId, destination, replyTo for the Solace binder | +| `SolaceHeaderParser` | 200 | correlationId, destination, replyTo, timeToLive for the Solace binder | | `SpringCloudStreamHeaderParser` | 10000 | destination, totalReplies for Spring Cloud Stream headers | | `SpringIntegrationHeaderParser` | 20000 | correlationId for Spring Integration headers | | `BinderHeaderParser` | 30000 | destination for Spring Cloud Stream binder headers | 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..e209607 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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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..2a3736b 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 @@ -1,6 +1,7 @@ package community.solace.spring.cloud.requestreply.service.header; import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -18,6 +19,7 @@ import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageReplyToParser; import community.solace.spring.cloud.requestreply.service.header.parser.totalreplies.MessageTotalRepliesParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyindex.MessageReplyIndexParser; +import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageTimeToLiveParser; import community.solace.spring.cloud.requestreply.service.messageinterceptor.ReplyWrappingInterceptor; import community.solace.spring.cloud.requestreply.util.MessageChunker; import org.apache.commons.lang3.tuple.Pair; @@ -38,6 +40,8 @@ import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; +import static community.solace.spring.cloud.requestreply.util.MessageTimeToLive.setTimeToLiveIfAbsent; + @Service public class RequestReplyMessageHeaderSupportService { @@ -62,6 +66,9 @@ public class RequestReplyMessageHeaderSupportService { @Autowired private List errorMessageParsers; + @Autowired(required = false) + private List timeToLiveParsers = List.of(); + @Autowired private RequestReplyProperties requestReplyProperties; @Autowired @@ -149,9 +156,28 @@ public String getErrorMessage(Message message) { return null; } + /** + * Reads the time-to-live of a message through the ordered time-to-live parsers. + * + * @param message the message to read + * @return the time-to-live the message carries, or {@code null} if it never expires + */ + public Duration getTimeToLive(Message message) { + if (message == null) { + return null; + } + for (MessageTimeToLiveParser p : timeToLiveParsers) { + Duration value = p.getTimeToLive(message); + if (value != null) { + return value; + } + } + return null; + } + /** * 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 left over from the request * * @param incoming message payload type * @param outgoing message payload type @@ -167,7 +193,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 left over from the request * * @param incoming message payload type * @param outgoing message payload type @@ -186,7 +212,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 left over from the request * * @param incoming message payload type * @param outgoing message payload type @@ -234,7 +260,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 left over from the request * * @param incoming message payload type * @param outgoing message payload type @@ -333,7 +359,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 left over from the request * * @param incoming message payload type * @param outgoing message payload type @@ -347,7 +373,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 left over from the request * * @param incoming message payload type * @param outgoing message payload type @@ -455,6 +481,34 @@ private void transferAndAdoptHeaders(Message request, mb.setHeaderIfAbsent(headerToCopy, val); } } + + Duration replyTimeToLive = remainingTimeToLive(request); + if (replyTimeToLive != null) { + setTimeToLiveIfAbsent(mb, replyTimeToLive); + } + } + + /** + * The time-to-live the request arrived with, less the time since it arrived, so that a reply expires when the + * requester stops waiting for it. + */ + private Duration remainingTimeToLive(Message request) { + Duration requestTimeToLive = getTimeToLive(request); + if (requestTimeToLive == null) { + return null; + } + return requestTimeToLive.minus(timeSinceArrival(request)); + } + + /** + * The binder builds the request message when the request arrives, so its timestamp is the arrival on this host. + */ + private static Duration timeSinceArrival(Message request) { + Long arrival = request.getHeaders().getTimestamp(); + if (arrival == null) { + return Duration.ZERO; + } + return Duration.between(Instant.ofEpochMilli(arrival), Instant.now()); } @FunctionalInterface diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java index 0f7b148..a32379b 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java @@ -4,11 +4,16 @@ import community.solace.spring.cloud.requestreply.service.header.parser.correlationid.MessageHeaderCorrelationIdParser; import community.solace.spring.cloud.requestreply.service.header.parser.destination.MessageHeaderDestinationParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageHeaderReplyToParser; +import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageHeaderTimeToLiveParser; import org.springframework.messaging.MessageHeaders; +import java.time.Duration; import java.util.Optional; -public class SolaceHeaderParser implements MessageHeaderCorrelationIdParser, MessageHeaderDestinationParser, MessageHeaderReplyToParser { +public class SolaceHeaderParser implements MessageHeaderCorrelationIdParser, MessageHeaderDestinationParser, MessageHeaderReplyToParser, MessageHeaderTimeToLiveParser { + public static final String TIME_TO_LIVE = "solace_timeToLive"/*SolaceHeaders.TIME_TO_LIVE*/; + public static final String EXPIRATION = "solace_expiration"/*SolaceHeaders.EXPIRATION*/; + @Override public String getCorrelationId(MessageHeaders headers) { return headers.get("solace_correlationId"/*SolaceHeaders.CORRELATION_ID*/, String.class); @@ -23,4 +28,20 @@ public String getDestination(MessageHeaders headers) { public String getReplyTo(MessageHeaders headers) { return Optional.ofNullable(headers.get("solace_replyTo"/*SolaceHeaders.REPLY_TO*/, Destination.class)).map(Destination::getName).orElse(null); } + + /** + * Reads {@value #TIME_TO_LIVE}, which the Solace binder sets on every inbound message. + * + * @param headers the headers to read + * @return the time-to-live of the message, or {@code null} if it has none or its time-to-live is 0, which + * Solace reads as "never expire" + */ + @Override + public Duration getTimeToLive(MessageHeaders headers) { + Object timeToLive = headers.get(TIME_TO_LIVE); + if (!(timeToLive instanceof Number millis) || millis.longValue() <= 0) { + return null; + } + return Duration.ofMillis(millis.longValue()); + } } diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java new file mode 100644 index 0000000..2eea82b --- /dev/null +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java @@ -0,0 +1,27 @@ +package community.solace.spring.cloud.requestreply.service.header.parser.timetolive; + +import java.time.Duration; + +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHeaders; + +/** + * Reads the time-to-live of a message from its headers. + */ +@FunctionalInterface +public interface MessageHeaderTimeToLiveParser extends MessageTimeToLiveParser { + @Override + default Duration getTimeToLive(Message message) { + return message == null ? + null : + getTimeToLive(message.getHeaders()); + } + + /** + * Reads the time-to-live from the headers of a message. + * + * @param headers the headers to read + * @return the time-to-live of the message, or {@code null} if it never expires or the parser does not know + */ + Duration getTimeToLive(MessageHeaders headers); +} \ No newline at end of file diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java new file mode 100644 index 0000000..3d28ec2 --- /dev/null +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java @@ -0,0 +1,19 @@ +package community.solace.spring.cloud.requestreply.service.header.parser.timetolive; + +import java.time.Duration; + +import org.springframework.messaging.Message; + +/** + * Reads how long a message may live before the broker discards it. + */ +@FunctionalInterface +public interface MessageTimeToLiveParser { + /** + * Reads the time-to-live of a message. + * + * @param message the message to read + * @return the time-to-live of the message, or {@code null} if it never expires or the parser does not know + */ + Duration getTimeToLive(Message message); +} \ No newline at end of file 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..3b7d15e --- /dev/null +++ b/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java @@ -0,0 +1,41 @@ +package community.solace.spring.cloud.requestreply.util; + +import java.time.Duration; +import java.util.Map; + +import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; + +import org.springframework.integration.support.MessageBuilder; + +/** + * Gives a request or a reply the Solace time-to-live after which the broker discards it, so that it does not + * outlive the requester's wait for it. + */ +public final class MessageTimeToLive { + /** + * Solace reads a time-to-live of 0 as "never expire", so a lifetime that is already over is written as this. + */ + private static final Duration SHORTEST_TIME_TO_LIVE = Duration.ofMillis(1); + + 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, which the Solace binder rejects next to a time-to-live of a different value. + * + * @param messageBuilder the message to set the time-to-live on + * @param timeToLive how long the message stays useful; zero or less is written as the shortest time-to-live + */ + public static void setTimeToLiveIfAbsent(MessageBuilder messageBuilder, Duration timeToLive) { + Map headers = messageBuilder.getHeaders(); + boolean carriesLifetime = headers.containsKey(SolaceHeaderParser.TIME_TO_LIVE) || + headers.containsKey(SolaceHeaderParser.EXPIRATION); + if (carriesLifetime) { + return; + } + + Duration atLeastTheShortest = timeToLive.compareTo(SHORTEST_TIME_TO_LIVE) < 0 ? SHORTEST_TIME_TO_LIVE : timeToLive; + messageBuilder.setHeader(SolaceHeaderParser.TIME_TO_LIVE, atLeastTheShortest.toMillis()); + } +} \ No newline at end of file diff --git a/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java index ca41211..a233024 100644 --- a/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java +++ b/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java @@ -6,6 +6,7 @@ import community.solace.spring.cloud.requestreply.service.header.parser.destination.MessageDestinationParser; import community.solace.spring.cloud.requestreply.service.header.parser.errormessage.MessageErrorMessageParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageReplyToParser; +import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageTimeToLiveParser; import community.solace.spring.cloud.requestreply.service.header.parser.totalreplies.MessageTotalRepliesParser; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -38,6 +39,9 @@ class HeaderParserTests extends AbstractRequestReplySimpleIT { @Autowired private List messageErrorMessageParsers; + @Autowired + private List messageTimeToLiveParsers; + @Test void correlationIdParsersShouldNotThrowExceptionWhenGivenNull() { for (MessageCorrelationIdParser parser : messageCorrelationIdParsers) { @@ -73,6 +77,13 @@ void errorMessageParsersShouldNotThrowExceptionWhenGivenNull() { } } + @Test + void timeToLiveParsersShouldNotThrowExceptionWhenGivenNull() { + for (MessageTimeToLiveParser parser : messageTimeToLiveParsers) { + assertNull((parser).getTimeToLive(null), String.format("%s can not handle null values", parser)); + } + } + @Test void headerParserPrecedenceIsObeyed() { MessageBuilder mb = MessageBuilder.withPayload("headerParserPrecedenceIsObeyed"); 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..4774513 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 @@ -11,6 +11,7 @@ import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; import community.solace.spring.cloud.requestreply.model.SensorReading; +import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; import community.solace.spring.cloud.requestreply.service.header.parser.SpringHeaderParser; import community.solace.spring.cloud.requestreply.service.header.parser.errormessage.RemoteErrorException; import org.junit.jupiter.api.Test; @@ -32,6 +33,7 @@ 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; @@ -287,6 +289,103 @@ void requestAndAwaitReplyToTopic_expectAdditionalHeaders_whenRequestReceived() t } + @Test + void requestAndAwaitReplyToTopic_expectTimeoutAsTimeToLive_whenRequestSent() { + assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + new SensorReading(), + "last_value/temperature/celsius/demo", + SensorReading.class, + Duration.ofMillis(100) + )); + + Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); + assertEquals( + 100L, + messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void requestReplyToTopicReactive_expectTimeoutAsTimeToLive_whenRequestSent() { + Flux flux = requestReplyService.requestReplyToTopicReactive( + new SensorReading(), + "last_value/temperature/celsius/demo", + SensorReading.class, + Duration.ofMillis(100) + ); + + StepVerifier + .create(flux) + .expectError(TimeoutException.class) + .verify(Duration.ofSeconds(10)); + + Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); + assertEquals( + 100L, + messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void requestAndAwaitReplyToTopic_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { + long neverExpire = 0L; + + assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + new SensorReading(), + "last_value/temperature/celsius/demo", + SensorReading.class, + Duration.ofMillis(100), + Map.of(SolaceHeaderParser.TIME_TO_LIVE, neverExpire) + )); + + Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); + assertEquals( + neverExpire, + messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void requestAndAwaitReplyToTopicWithMsg_expectItsTimeToLiveKept_whenMessageCarriesOne() { + long timeToLiveOfTheMessage = 5_000L; + + assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + MessageBuilder.withPayload(new SensorReading()) + .setHeader(SolaceHeaderParser.TIME_TO_LIVE, timeToLiveOfTheMessage) + .build(), + "last_value/temperature/celsius/demo", + SensorReading.class, + Duration.ofMillis(100) + )); + + Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); + assertEquals( + timeToLiveOfTheMessage, + messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + ); + } + + /** + * The Solace binder rejects a message whose expiration and time-to-live differ, so a request that carries an + * expiration must not get a time-to-live on top. + */ + @Test + void requestAndAwaitReplyToTopicWithMsg_expectNoTimeToLiveAdded_whenMessageCarriesAnExpiration() { + assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + MessageBuilder.withPayload(new SensorReading()) + .setHeader(SolaceHeaderParser.EXPIRATION, 1_682_928_000_000L) + .build(), + "last_value/temperature/celsius/demo", + SensorReading.class, + Duration.ofMillis(100) + )); + + Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); + assertNull( + messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + ); + } + @Test void requestAndAwaitReplyToTopic_expectException_whenErrorResponse() { SensorReading request = new SensorReading(); diff --git a/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java new file mode 100644 index 0000000..55a73c6 --- /dev/null +++ b/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java @@ -0,0 +1,53 @@ +package community.solace.spring.cloud.requestreply.service.header; + +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; +import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.integration.support.MutableMessage; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHeaders; +import org.springframework.test.context.TestPropertySource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A responder that copies the request's time-to-live onto its replies with {@code copyHeadersOnWrap} chose that + * value itself, so the library must not replace it with what is left of the request's time-to-live. + */ +@TestPropertySource(properties = "spring.cloud.stream.requestreply.copyHeadersOnWrap=" + SolaceHeaderParser.TIME_TO_LIVE) +class RequestReplyCopiedTimeToLiveTests extends AbstractRequestReplySimpleIT { + private static final Duration REQUEST_TIME_TO_LIVE = Duration.ofSeconds(10); + private static final Duration TIME_SINCE_ARRIVAL = Duration.ofSeconds(3); + + @Autowired + RequestReplyMessageHeaderSupportService supportService; + + @Test + void wrap_expectCopiedTimeToLive_whenCopyHeadersOnWrapNamesIt() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(requestArrivedAgo()); + + assertEquals( + REQUEST_TIME_TO_LIVE.toMillis(), + answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + ); + } + + private static Message requestArrivedAgo() { + Map headers = new HashMap<>(); + headers.put(MessageHeaders.TIMESTAMP, Instant.now().minus(TIME_SINCE_ARRIVAL).toEpochMilli()); + headers.put("correlationId", "my-correlationId-my"); + headers.put(MessageHeaders.REPLY_CHANNEL, "my-dest-my/{StagePlaceholder}/the-event-after"); + headers.put(SolaceHeaderParser.TIME_TO_LIVE, REQUEST_TIME_TO_LIVE.toMillis()); + return new MutableMessage<>("demo", headers); + } +} \ No newline at end of file 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..fd00907 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 @@ -3,12 +3,15 @@ import com.solacesystems.jcsmp.SDTStream; import com.solacesystems.jcsmp.impl.sdt.StreamImpl; import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; +import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; import community.solace.spring.cloud.requestreply.service.header.parser.SpringHeaderParser; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.binder.BinderHeaders; import org.springframework.cloud.stream.config.BindingServiceProperties; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.support.MutableMessage; +import org.springframework.integration.support.MutableMessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import reactor.core.publisher.Flux; @@ -16,13 +19,19 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; import java.util.Collections; +import java.util.HashMap; 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); + private static final Duration TIME_SINCE_ARRIVAL = Duration.ofSeconds(3); + private static final Duration SLACK_FOR_A_SLOW_TEST = Duration.ofSeconds(1); @Autowired RequestReplyMessageHeaderSupportService supportService; @@ -672,6 +681,169 @@ void wrapFlux_exception() { } + @Test + void getTimeToLive() { + Message m = MessageBuilder.withPayload("demo") + .setHeader(SolaceHeaderParser.TIME_TO_LIVE, 5_000L) + .build(); + + assertEquals( + Duration.ofSeconds(5), + supportService.getTimeToLive(m) + ); + } + + @Test + void getTimeToLive_ofZero_meansTheMessageNeverExpires() { + Message m = MessageBuilder.withPayload("demo") + .setHeader(SolaceHeaderParser.TIME_TO_LIVE, 0L) + .build(); + + assertNull( + supportService.getTimeToLive(m) + ); + } + + @Test + void wrap_expectRemainingTimeToLive_whenRequestCarriesOne() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)); + + assertTimeToLiveLeftOver(answerM); + } + + @Test + void wrap_expectShortestTimeToLive_whenRequestExpiredBeforeTheReply() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(requestArrivedAgo(REQUEST_TIME_TO_LIVE.plus(TIME_SINCE_ARRIVAL), REQUEST_TIME_TO_LIVE)); + + assertEquals( + 1L, + answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), + "A time-to-live of 0 would let the reply never expire" + ); + } + + @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(SolaceHeaderParser.TIME_TO_LIVE) + ); + } + + @Test + void wrap_expectNoTimeToLive_whenRequestNeverExpires() { + Function, Message> supplier = supportService.wrap(m -> m, (Class) null); + + Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, Duration.ZERO)); + + assertNull( + answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + ); + } + + @Test + void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { + long neverExpire = 0L; + Function, Message> supplier = supportService.wrap( + m -> m, + Map.of(SolaceHeaderParser.TIME_TO_LIVE, neverExpire), + (Class) null + ); + + Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)); + + assertEquals( + neverExpire, + answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + ); + } + + @Test + void wrap_exception_expectRemainingTimeToLiveOnTheErrorReply() { + Function, Message> supplier = supportService.wrap( + m -> { + throw new IllegalArgumentException("The error message"); + }, + IllegalArgumentException.class + ); + + Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)); + + assertTimeToLiveLeftOver(answerM); + } + + @Test + void wrapList_groupedResponses_expectRemainingTimeToLive() { + Function, List>> supplier = supportService.wrapList(m -> List.of(m, m), "requestReplyRepliesDemo-out-0", (Class) null); + + Message request = MutableMessageBuilder.fromMessage(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)) + .setHeader(SpringHeaderParser.GROUPED_MESSAGES, true) + .build(); + List> answers = supplier.apply(request); + + assertEquals( + 1, + answers.size() + ); + assertTimeToLiveLeftOver(answers.get(0)); + } + + @Test + void wrapFlux_expectRemainingTimeToLiveOnEveryReply_includingTheFinishingOne() { + Function>, Flux>> supplier = supportService.wrapFlux((payloadIn, outSink) -> { + outSink.next("first msg"); + outSink.complete(); + }, "requestReplyRepliesDemo-out-0"); + + Flux> answers = supplier.apply(Flux.just(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE))); + + StepVerifier + .create(answers) + .consumeNextWith(this::assertTimeToLiveLeftOver) + .consumeNextWith(this::assertTimeToLiveLeftOver) + .expectComplete() + .verify(Duration.ofSeconds(10)); + } + + /** + * {@link MessageBuilder} sets the timestamp of a message to now; a {@link MutableMessage} keeps the one given, + * which lets a test send a request that arrived a while ago. + */ + private static Message requestArrivedAgo(Duration timeSinceArrival, Duration requestTimeToLive) { + long arrival = Instant.now().minus(timeSinceArrival).toEpochMilli(); + Map headers = new HashMap<>(); + headers.put(MessageHeaders.TIMESTAMP, arrival); + headers.put("correlationId", "my-correlationId-my"); + headers.put(MessageHeaders.REPLY_CHANNEL, "my-dest-my/{StagePlaceholder}/the-event-after"); + headers.put(SolaceHeaderParser.TIME_TO_LIVE, requestTimeToLive.toMillis()); + + Message request = new MutableMessage<>("demo", headers); + + assertEquals(arrival, request.getHeaders().getTimestamp(), "The request must keep the arrival it was given"); + return request; + } + + private void assertTimeToLiveLeftOver(Message reply) { + long leftOver = REQUEST_TIME_TO_LIVE.minus(TIME_SINCE_ARRIVAL).toMillis(); + Long replyTimeToLive = reply.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class); + + assertNotNull(replyTimeToLive, "The reply must carry what is left of the request's time-to-live"); + assertTrue( + replyTimeToLive <= leftOver && replyTimeToLive > leftOver - SLACK_FOR_A_SLOW_TEST.toMillis(), + "The reply must expire with the request: expected about " + leftOver + " ms, but was " + replyTimeToLive + " ms" + ); + } + @Test void replyTopicWithWildcards() { assertEquals( From 51c3a4433f49d87bc827396bbb83973441ad2e57 Mon Sep 17 00:00:00 2001 From: Heiko Henning Date: Sat, 21 Nov 2026 18:10:25 +0100 Subject: [PATCH 2/6] docs: state that a reply may outlive the requester's wait A message arrives with the time-to-live its sender set, not with what is left of it: JCSMP derives the end of life at sending and does not hand it on while a time-to-live is set. The reply's time-to-live is therefore an upper bound, longer by as long as the request waited to be delivered. --- AGENTS.md | 5 ++++- README.md | 5 ++++- .../header/RequestReplyMessageHeaderSupportService.java | 6 ++++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 88845ca..17242f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,7 +168,10 @@ contexts (see §6). If a bean with the binding name already exists, do not overr 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 gets the request's time‑to‑live less the time since the request message was built on the responder, - so the responder's clock alone decides. `MessageTimeToLive` is the one place that writes it, and it keeps + so the responder's clock alone decides. A message arrives with the time‑to‑live its sender set, not with + what is left: JCSMP derives the end of life (`expiration`) from it at sending but does not send it while a + time‑to‑live is set. The reply's value is therefore an upper bound, too long by as long as the request + waited to be delivered and never too short. `MessageTimeToLive` is the one place that writes it, and it keeps three rules: never write 0 (Solace reads it as "never expire", so the minimum is 1 ms); never overwrite a lifetime the message already carries; and never add a time‑to‑live next to `solace_expiration`, because the Solace binder rejects a message whose two lifetime headers differ. diff --git a/README.md b/README.md index bf5942d..c3187d5 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,10 @@ is one: the Solace binder marks messages DMQ‑eligible by default (`solace_dmqE message the time‑to‑live has no effect. The reply's time‑to‑live is measured on the responder's own clock, from the moment the request message -was built there, so it does not depend on the requester's and responder's clocks agreeing. +was built there, so it does not depend on the requester's and responder's clocks agreeing. A message +arrives with the time‑to‑live its sender set, not with what is left of it; the end of life derived from +it at sending is not handed on. A reply can therefore outlive the requester's wait by as long as the +request waited to be delivered, but it never gets less time than the requester has left. ### Single vs. multi response 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 2a3736b..70f515c 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 @@ -489,8 +489,10 @@ private void transferAndAdoptHeaders(Message request, } /** - * The time-to-live the request arrived with, less the time since it arrived, so that a reply expires when the - * requester stops waiting for it. + * The time-to-live the request arrived with, less the time since it arrived. A message arrives with the + * time-to-live its sender set, not with what is left of it: the end of life derived from it at sending is not + * handed on. A reply therefore expires no earlier than the requester stops waiting, and later only by as long as + * the request waited to be delivered. */ private Duration remainingTimeToLive(Message request) { Duration requestTimeToLive = getTimeToLive(request); From dc02bd851efcac6e805facf8fdd76eb0ca0f0d8a Mon Sep 17 00:00:00 2001 From: Heiko Henning Date: Sat, 21 Nov 2026 18:59:15 +0100 Subject: [PATCH 3/6] feat: give a reply the request's time-to-live unchanged A responder cannot know what is left of the request's time-to-live, so computing a remaining time bought a few seconds for clock and timestamp logic. The reply's time-to-live is now set after the caller's headers, so that it never lands next to an expiration the caller gave. --- AGENTS.md | 18 ++-- CHANGELOG.md | 2 +- README.md | 28 ++--- ...questReplyMessageHeaderSupportService.java | 44 +++----- .../requestreply/util/MessageTimeToLive.java | 10 +- .../RequestReplyCopiedTimeToLiveTests.java | 53 --------- ...impleMessageHeaderSupportServiceTests.java | 102 ++++++++---------- .../util/MessageTimeToLiveTests.java | 29 +++++ 8 files changed, 111 insertions(+), 175 deletions(-) delete mode 100644 src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java create mode 100644 src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java diff --git a/AGENTS.md b/AGENTS.md index 17242f1..34bf201 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,8 +120,8 @@ Invariants the wrappers must preserve: - 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`, -- set `solace_timeToLive` on every reply, the terminal and error replies included, to what is left of the - request's time‑to‑live (see §6). +- 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 @@ -167,14 +167,12 @@ contexts (see §6). If a bean with the binding name already exists, do not overr `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 gets the request's time‑to‑live less the time since the request message was built on the responder, - so the responder's clock alone decides. A message arrives with the time‑to‑live its sender set, not with - what is left: JCSMP derives the end of life (`expiration`) from it at sending but does not send it while a - time‑to‑live is set. The reply's value is therefore an upper bound, too long by as long as the request - waited to be delivered and never too short. `MessageTimeToLive` is the one place that writes it, and it keeps - three rules: never write 0 (Solace reads it as "never expire", so the minimum is 1 ms); never overwrite a - lifetime the message already carries; and never add a time‑to‑live next to `solace_expiration`, because - the Solace binder rejects a message whose two lifetime headers differ. + 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 writes it, and it keeps three rules: never write + 0 (Solace reads it as "never expire", so the minimum is 1 ms); 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 f3803e5..62006bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [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; a reply built by the `wrap*` helpers gets the time-to-live the request arrived with, less the time since it arrived, and at least 1 ms. A message that already carries `solace_timeToLive` or `solace_expiration` keeps its own lifetime, and `additionalHeaders` with `solace_timeToLive` = `0` sends a request that never expires. A `solace_timeToLive` in a binding's producer `defaultHeader` is now overridden; set it in `additionalHeaders` or an interceptor instead. The broker expires a message only on a queue that respects the time-to-live, and moves it 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)) +- 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, at least 1 ms; 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, and `additionalHeaders` with `solace_timeToLive` = `0` sends a request that never expires. A `solace_timeToLive` in a binding's producer `defaultHeader` is now overridden; set it in `additionalHeaders` or an interceptor instead. The broker expires a message only on a queue that respects the time-to-live, and moves it 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)) ## [6.1.5] - 2026-11-13 ### Changed diff --git a/README.md b/README.md index c3187d5..3f9170d 100644 --- a/README.md +++ b/README.md @@ -34,7 +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 outlives the wait. +- 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. @@ -205,30 +206,23 @@ is raised. Bookkeeping for the request is always cleaned up on success, error or 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; -- on every **reply** built by the `wrap*` helpers, to the time‑to‑live the request arrived with, less the - time since it arrived. A request without a time‑to‑live gets replies without one. A reply whose request - has already expired gets 1 ms, because 0 means "never expire". +- on the **request**, to the timeout. A timeout below 1 ms is sent as 1 ms, because 0 means "never + expire"; +- 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`, in a message -interceptor, or copied onto the reply with `copyHeadersOnWrap`. A message that carries -`solace_expiration` gets no time‑to‑live either, because the Solace binder rejects the two headers with -different values. 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. +interceptor, 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. 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. -The reply's time‑to‑live is measured on the responder's own clock, from the moment the request message -was built there, so it does not depend on the requester's and responder's clocks agreeing. A message -arrives with the time‑to‑live its sender set, not with what is left of it; the end of life derived from -it at sending is not handed on. A reply can therefore outlive the requester's wait by as long as the -request waited to be delivered, but it never gets less time than the requester has left. - ### Single vs. multi response - **Single response** — you expect exactly one answer. Use `requestAndAwaitReply*` (blocking) or 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 70f515c..76d0a5a 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 @@ -1,7 +1,6 @@ package community.solace.spring.cloud.requestreply.service.header; import java.time.Duration; -import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -177,7 +176,7 @@ public Duration getTimeToLive(Message message) { /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID, target and the time-to-live left over from the request + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -193,7 +192,7 @@ public final > Function, Messa /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID, target and the time-to-live left over from the request + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -212,7 +211,7 @@ public final > Function, Messa /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID, target and the time-to-live left over from the request + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -240,6 +239,7 @@ public final > Function, Messa mb.setHeader(header.getKey(), header.getValue()); } } + adoptTimeToLive(request, mb); return this.replyWrappingInterceptor.interceptReplyWrappingPayloadMessage(mb.build(), bindingName); } catch (Exception e) { @@ -260,7 +260,7 @@ public final > Function, Messa /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID, target and the time-to-live left over from the request + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -359,7 +359,7 @@ private List> wrapListGroupedResponses(Message request, Lis /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID, target and the time-to-live left over from the request + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -373,7 +373,7 @@ public final Function>, Flux>> wrapFlux(BiCons /** * wrap the given function, copying message headers from incoming to outgoing message, - * properly setting correlation ID, target and the time-to-live left over from the request + * properly setting correlation ID, target and the time-to-live of the request * * @param incoming message payload type * @param outgoing message payload type @@ -459,6 +459,7 @@ private void transferAndAdoptHeaders(Message request, MessageBuilder void transferAndAdoptHeaders(Message request, @@ -481,36 +482,17 @@ private void transferAndAdoptHeaders(Message request, mb.setHeaderIfAbsent(headerToCopy, val); } } - - Duration replyTimeToLive = remainingTimeToLive(request); - if (replyTimeToLive != null) { - setTimeToLiveIfAbsent(mb, replyTimeToLive); - } } /** - * The time-to-live the request arrived with, less the time since it arrived. A message arrives with the - * time-to-live its sender set, not with what is left of it: the end of life derived from it at sending is not - * handed on. A reply therefore expires no earlier than the requester stops waiting, and later only by as long as - * the request waited to be delivered. + * Gives the reply the time-to-live of the request, unless the reply already carries a lifetime. Runs after every + * other header of the reply is set, so that it sees a lifetime set by the caller. */ - private Duration remainingTimeToLive(Message request) { + private void adoptTimeToLive(Message request, MessageBuilder mb) { Duration requestTimeToLive = getTimeToLive(request); - if (requestTimeToLive == null) { - return null; - } - return requestTimeToLive.minus(timeSinceArrival(request)); - } - - /** - * The binder builds the request message when the request arrives, so its timestamp is the arrival on this host. - */ - private static Duration timeSinceArrival(Message request) { - Long arrival = request.getHeaders().getTimestamp(); - if (arrival == null) { - return Duration.ZERO; + if (requestTimeToLive != null) { + setTimeToLiveIfAbsent(mb, requestTimeToLive); } - return Duration.between(Instant.ofEpochMilli(arrival), Instant.now()); } @FunctionalInterface 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 index 3b7d15e..b41cf84 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java @@ -8,12 +8,12 @@ import org.springframework.integration.support.MessageBuilder; /** - * Gives a request or a reply the Solace time-to-live after which the broker discards it, so that it does not - * outlive the requester's wait for it. + * 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. */ public final class MessageTimeToLive { /** - * Solace reads a time-to-live of 0 as "never expire", so a lifetime that is already over is written as this. + * 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); @@ -22,10 +22,10 @@ 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, which the Solace binder rejects next to a time-to-live of a different value. + * 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; zero or less is written as the shortest time-to-live + * @param timeToLive how long the message stays useful; below a millisecond it is written as one millisecond */ public static void setTimeToLiveIfAbsent(MessageBuilder messageBuilder, Duration timeToLive) { Map headers = messageBuilder.getHeaders(); diff --git a/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java deleted file mode 100644 index 55a73c6..0000000 --- a/src/test/java/community/solace/spring/cloud/requestreply/service/header/RequestReplyCopiedTimeToLiveTests.java +++ /dev/null @@ -1,53 +0,0 @@ -package community.solace.spring.cloud.requestreply.service.header; - -import java.time.Duration; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; -import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.integration.support.MutableMessage; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHeaders; -import org.springframework.test.context.TestPropertySource; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * A responder that copies the request's time-to-live onto its replies with {@code copyHeadersOnWrap} chose that - * value itself, so the library must not replace it with what is left of the request's time-to-live. - */ -@TestPropertySource(properties = "spring.cloud.stream.requestreply.copyHeadersOnWrap=" + SolaceHeaderParser.TIME_TO_LIVE) -class RequestReplyCopiedTimeToLiveTests extends AbstractRequestReplySimpleIT { - private static final Duration REQUEST_TIME_TO_LIVE = Duration.ofSeconds(10); - private static final Duration TIME_SINCE_ARRIVAL = Duration.ofSeconds(3); - - @Autowired - RequestReplyMessageHeaderSupportService supportService; - - @Test - void wrap_expectCopiedTimeToLive_whenCopyHeadersOnWrapNamesIt() { - Function, Message> supplier = supportService.wrap(m -> m, (Class) null); - - Message answerM = supplier.apply(requestArrivedAgo()); - - assertEquals( - REQUEST_TIME_TO_LIVE.toMillis(), - answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) - ); - } - - private static Message requestArrivedAgo() { - Map headers = new HashMap<>(); - headers.put(MessageHeaders.TIMESTAMP, Instant.now().minus(TIME_SINCE_ARRIVAL).toEpochMilli()); - headers.put("correlationId", "my-correlationId-my"); - headers.put(MessageHeaders.REPLY_CHANNEL, "my-dest-my/{StagePlaceholder}/the-event-after"); - headers.put(SolaceHeaderParser.TIME_TO_LIVE, REQUEST_TIME_TO_LIVE.toMillis()); - return new MutableMessage<>("demo", headers); - } -} \ No newline at end of file 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 fd00907..42c22bf 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 @@ -10,8 +10,6 @@ import org.springframework.cloud.stream.binder.BinderHeaders; import org.springframework.cloud.stream.config.BindingServiceProperties; import org.springframework.integration.support.MessageBuilder; -import org.springframework.integration.support.MutableMessage; -import org.springframework.integration.support.MutableMessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import reactor.core.publisher.Flux; @@ -19,9 +17,7 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.time.Instant; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; @@ -30,8 +26,6 @@ class RequestReplySimpleMessageHeaderSupportServiceTests extends AbstractRequestReplySimpleIT { private static final Duration REQUEST_TIME_TO_LIVE = Duration.ofSeconds(10); - private static final Duration TIME_SINCE_ARRIVAL = Duration.ofSeconds(3); - private static final Duration SLACK_FOR_A_SLOW_TEST = Duration.ofSeconds(1); @Autowired RequestReplyMessageHeaderSupportService supportService; @@ -705,25 +699,12 @@ void getTimeToLive_ofZero_meansTheMessageNeverExpires() { } @Test - void wrap_expectRemainingTimeToLive_whenRequestCarriesOne() { + void wrap_expectTheRequestsTimeToLive_whenRequestCarriesOne() { Function, Message> supplier = supportService.wrap(m -> m, (Class) null); - Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)); + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); - assertTimeToLiveLeftOver(answerM); - } - - @Test - void wrap_expectShortestTimeToLive_whenRequestExpiredBeforeTheReply() { - Function, Message> supplier = supportService.wrap(m -> m, (Class) null); - - Message answerM = supplier.apply(requestArrivedAgo(REQUEST_TIME_TO_LIVE.plus(TIME_SINCE_ARRIVAL), REQUEST_TIME_TO_LIVE)); - - assertEquals( - 1L, - answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), - "A time-to-live of 0 would let the reply never expire" - ); + assertTheRequestsTimeToLive(answerM); } @Test @@ -744,7 +725,7 @@ void wrap_expectNoTimeToLive_whenRequestCarriesNone() { void wrap_expectNoTimeToLive_whenRequestNeverExpires() { Function, Message> supplier = supportService.wrap(m -> m, (Class) null); - Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, Duration.ZERO)); + Message answerM = supplier.apply(requestWithTimeToLive(Duration.ZERO)); assertNull( answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) @@ -760,7 +741,7 @@ void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { (Class) null ); - Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)); + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); assertEquals( neverExpire, @@ -768,8 +749,26 @@ void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { ); } + /** + * 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(SolaceHeaderParser.EXPIRATION, 1_682_928_000_000L), + (Class) null + ); + + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); + + assertNull( + answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + ); + } + @Test - void wrap_exception_expectRemainingTimeToLiveOnTheErrorReply() { + void wrap_exception_expectTheRequestsTimeToLiveOnTheErrorReply() { Function, Message> supplier = supportService.wrap( m -> { throw new IllegalArgumentException("The error message"); @@ -777,16 +776,16 @@ void wrap_exception_expectRemainingTimeToLiveOnTheErrorReply() { IllegalArgumentException.class ); - Message answerM = supplier.apply(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)); + Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); - assertTimeToLiveLeftOver(answerM); + assertTheRequestsTimeToLive(answerM); } @Test - void wrapList_groupedResponses_expectRemainingTimeToLive() { + void wrapList_groupedResponses_expectTheRequestsTimeToLive() { Function, List>> supplier = supportService.wrapList(m -> List.of(m, m), "requestReplyRepliesDemo-out-0", (Class) null); - Message request = MutableMessageBuilder.fromMessage(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE)) + Message request = MessageBuilder.fromMessage(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)) .setHeader(SpringHeaderParser.GROUPED_MESSAGES, true) .build(); List> answers = supplier.apply(request); @@ -795,52 +794,39 @@ void wrapList_groupedResponses_expectRemainingTimeToLive() { 1, answers.size() ); - assertTimeToLiveLeftOver(answers.get(0)); + assertTheRequestsTimeToLive(answers.get(0)); } @Test - void wrapFlux_expectRemainingTimeToLiveOnEveryReply_includingTheFinishingOne() { + 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(requestArrivedAgo(TIME_SINCE_ARRIVAL, REQUEST_TIME_TO_LIVE))); + Flux> answers = supplier.apply(Flux.just(requestWithTimeToLive(REQUEST_TIME_TO_LIVE))); StepVerifier .create(answers) - .consumeNextWith(this::assertTimeToLiveLeftOver) - .consumeNextWith(this::assertTimeToLiveLeftOver) + .consumeNextWith(this::assertTheRequestsTimeToLive) + .consumeNextWith(this::assertTheRequestsTimeToLive) .expectComplete() .verify(Duration.ofSeconds(10)); } - /** - * {@link MessageBuilder} sets the timestamp of a message to now; a {@link MutableMessage} keeps the one given, - * which lets a test send a request that arrived a while ago. - */ - private static Message requestArrivedAgo(Duration timeSinceArrival, Duration requestTimeToLive) { - long arrival = Instant.now().minus(timeSinceArrival).toEpochMilli(); - Map headers = new HashMap<>(); - headers.put(MessageHeaders.TIMESTAMP, arrival); - headers.put("correlationId", "my-correlationId-my"); - headers.put(MessageHeaders.REPLY_CHANNEL, "my-dest-my/{StagePlaceholder}/the-event-after"); - headers.put(SolaceHeaderParser.TIME_TO_LIVE, requestTimeToLive.toMillis()); - - Message request = new MutableMessage<>("demo", headers); - - assertEquals(arrival, request.getHeaders().getTimestamp(), "The request must keep the arrival it was given"); - return request; + 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(SolaceHeaderParser.TIME_TO_LIVE, requestTimeToLive.toMillis()) + .build(); } - private void assertTimeToLiveLeftOver(Message reply) { - long leftOver = REQUEST_TIME_TO_LIVE.minus(TIME_SINCE_ARRIVAL).toMillis(); - Long replyTimeToLive = reply.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class); - - assertNotNull(replyTimeToLive, "The reply must carry what is left of the request's time-to-live"); - assertTrue( - replyTimeToLive <= leftOver && replyTimeToLive > leftOver - SLACK_FOR_A_SLOW_TEST.toMillis(), - "The reply must expire with the request: expected about " + leftOver + " ms, but was " + replyTimeToLive + " ms" + private void assertTheRequestsTimeToLive(Message reply) { + assertEquals( + REQUEST_TIME_TO_LIVE.toMillis(), + reply.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), + "The reply must expire like the request it answers" ); } 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..66e98cb --- /dev/null +++ b/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java @@ -0,0 +1,29 @@ +package community.solace.spring.cloud.requestreply.util; + +import java.time.Duration; + +import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; +import org.junit.jupiter.api.Test; + +import org.springframework.integration.support.MessageBuilder; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Solace reads a time-to-live of 0 as "never expire", so a timeout below a millisecond must not round down to it. + */ +class MessageTimeToLiveTests { + + @Test + void setTimeToLiveIfAbsent_expectOneMillisecond_whenTimeToLiveRoundsDownToZero() { + MessageBuilder messageBuilder = MessageBuilder.withPayload("demo"); + + MessageTimeToLive.setTimeToLiveIfAbsent(messageBuilder, Duration.ofNanos(500_000)); + + assertEquals( + 1L, + messageBuilder.build().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), + "A time-to-live of 0 would let the message never expire" + ); + } +} \ No newline at end of file From 51c22a128ad04b78aa70a48b5e11301836b35997 Mon Sep 17 00:00:00 2001 From: Heiko Henning Date: Sat, 21 Nov 2026 19:05:41 +0100 Subject: [PATCH 4/6] fix: keep a timeout above ten years from failing the send JCSMP refuses a time-to-live above ten years, so a caller that passed a huge timeout to wait forever could no longer send its request. The changelog now lists the expiry as a change in behaviour, and the README says what an interceptor and a request forwarded from Solace get. --- AGENTS.md | 7 ++--- CHANGELOG.md | 6 ++++- README.md | 27 ++++++++++++------- .../header/parser/SolaceHeaderParser.java | 7 ++--- .../requestreply/util/MessageTimeToLive.java | 20 +++++++++++--- .../util/MessageTimeToLiveTests.java | 18 ++++++++++++- 6 files changed, 65 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 34bf201..a39784a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,9 +169,10 @@ contexts (see §6). If a bean with the binding name already exists, do not overr - **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 writes it, and it keeps three rules: never write - 0 (Solace reads it as "never expire", so the minimum is 1 ms); 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 + derives from it. `MessageTimeToLive` is the one place that 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 62006bd..57ad777 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [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, at least 1 ms; 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, and `additionalHeaders` with `solace_timeToLive` = `0` sends a request that never expires. A `solace_timeToLive` in a binding's producer `defaultHeader` is now overridden; set it in `additionalHeaders` or an interceptor instead. The broker expires a message only on a queue that respects the time-to-live, and moves it 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)) +- 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` = `0` 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 diff --git a/README.md b/README.md index 3f9170d..4fca20b 100644 --- a/README.md +++ b/README.md @@ -206,17 +206,25 @@ is raised. Bookkeeping for the request is always cleaned up on success, error or 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. A timeout below 1 ms is sent as 1 ms, because 0 means "never - expire"; +- 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`, in a message -interceptor, 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 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` already, 0 if its sender set none. +Sent on as a request, it keeps that lifetime instead of taking the timeout; remove the header to get the +timeout. 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 @@ -597,7 +605,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/header/parser/SolaceHeaderParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java index a32379b..9bc5c70 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java @@ -1,14 +1,15 @@ package community.solace.spring.cloud.requestreply.service.header.parser; +import java.time.Duration; +import java.util.Optional; + import com.solacesystems.jcsmp.Destination; import community.solace.spring.cloud.requestreply.service.header.parser.correlationid.MessageHeaderCorrelationIdParser; import community.solace.spring.cloud.requestreply.service.header.parser.destination.MessageHeaderDestinationParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageHeaderReplyToParser; import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageHeaderTimeToLiveParser; -import org.springframework.messaging.MessageHeaders; -import java.time.Duration; -import java.util.Optional; +import org.springframework.messaging.MessageHeaders; public class SolaceHeaderParser implements MessageHeaderCorrelationIdParser, MessageHeaderDestinationParser, MessageHeaderReplyToParser, MessageHeaderTimeToLiveParser { public static final String TIME_TO_LIVE = "solace_timeToLive"/*SolaceHeaders.TIME_TO_LIVE*/; 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 index b41cf84..cb45315 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java @@ -16,6 +16,10 @@ public final class MessageTimeToLive { * 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() { } @@ -25,7 +29,8 @@ private MessageTimeToLive() { * 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; below a millisecond it is written as one millisecond + * @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(); @@ -35,7 +40,16 @@ public static void setTimeToLiveIfAbsent(MessageBuilder messageBuilder, Durat return; } - Duration atLeastTheShortest = timeToLive.compareTo(SHORTEST_TIME_TO_LIVE) < 0 ? SHORTEST_TIME_TO_LIVE : timeToLive; - messageBuilder.setHeader(SolaceHeaderParser.TIME_TO_LIVE, atLeastTheShortest.toMillis()); + messageBuilder.setHeader(SolaceHeaderParser.TIME_TO_LIVE, withinTheBoundsSolaceAccepts(timeToLive).toMillis()); + } + + 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/util/MessageTimeToLiveTests.java b/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java index 66e98cb..c0a2607 100644 --- a/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java +++ b/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java @@ -1,6 +1,7 @@ package community.solace.spring.cloud.requestreply.util; import java.time.Duration; +import java.time.temporal.ChronoUnit; import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; import org.junit.jupiter.api.Test; @@ -10,9 +11,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * Solace reads a time-to-live of 0 as "never expire", so a timeout below a millisecond must not round down to it. + * 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() { @@ -26,4 +29,17 @@ void setTimeToLiveIfAbsent_expectOneMillisecond_whenTimeToLiveRoundsDownToZero() "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(SolaceHeaderParser.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 From 7fd75962027fd32ac0e5f5c4140d17ca05c978a2 Mon Sep 17 00:00:00 2001 From: Heiko Henning Date: Sat, 21 Nov 2026 19:13:38 +0100 Subject: [PATCH 5/6] test: answer requests at once in the time-to-live tests A request whose timeout ran out before a worker picked it up was never sent, so verifying the send after a 100 ms timeout could fail on a busy agent. The docs now say what a forwarded Solace message, an error reply and a custom time-to-live parser get. --- AGENTS.md | 4 +- CHANGELOG.md | 2 +- README.md | 9 +- .../service/RequestReplyService.java | 24 ++--- .../RequestReplySimpleServiceTests.java | 91 ++++++++++++------- 5 files changed, 82 insertions(+), 48 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a39784a..b5464c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,7 +173,9 @@ contexts (see §6). If a bean with the binding name already exists, do not overr 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. + every other header, `additionalHeaders` included, so that it sees a lifetime the caller set. Writing is + Solace‑only: a custom `MessageTimeToLiveParser` changes which time‑to‑live a reply copies, not which header + it is written to. - **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 57ad777..6cffa3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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` = `0` 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)) +- 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 diff --git a/README.md b/README.md index 4fca20b..92ccbc6 100644 --- a/README.md +++ b/README.md @@ -222,9 +222,12 @@ 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` already, 0 if its sender set none. -Sent on as a request, it keeps that lifetime instead of taking the timeout; remove the header to get the -timeout. +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 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 e209607..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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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, also set as the Solace time-to-live of the request + * @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/test/java/community/solace/spring/cloud/requestreply/service/RequestReplySimpleServiceTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/RequestReplySimpleServiceTests.java index 4774513..3d71e31 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 @@ -40,6 +40,7 @@ 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); @@ -290,102 +291,130 @@ void requestAndAwaitReplyToTopic_expectAdditionalHeaders_whenRequestReceived() t @Test - void requestAndAwaitReplyToTopic_expectTimeoutAsTimeToLive_whenRequestSent() { - assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + void requestAndAwaitReplyToTopic_expectTimeoutAsTimeToLive_whenRequestSent() throws Exception { + answerEveryRequestAtOnce(); + + requestReplyService.requestAndAwaitReplyToTopic( new SensorReading(), "last_value/temperature/celsius/demo", SensorReading.class, - Duration.ofMillis(100) - )); + REQUEST_TIMEOUT + ); - Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); assertEquals( - 100L, - messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + REQUEST_TIMEOUT.toMillis(), + sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) ); } @Test void requestReplyToTopicReactive_expectTimeoutAsTimeToLive_whenRequestSent() { + answerEveryRequestAtOnce(); + Flux flux = requestReplyService.requestReplyToTopicReactive( new SensorReading(), "last_value/temperature/celsius/demo", SensorReading.class, - Duration.ofMillis(100) + REQUEST_TIMEOUT ); StepVerifier .create(flux) - .expectError(TimeoutException.class) + .expectComplete() .verify(Duration.ofSeconds(10)); - Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); assertEquals( - 100L, - messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + REQUEST_TIMEOUT.toMillis(), + sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) ); } @Test - void requestAndAwaitReplyToTopic_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { + void requestAndAwaitReplyToTopic_expectCallersTimeToLive_whenGivenInAdditionalHeaders() throws Exception { long neverExpire = 0L; + answerEveryRequestAtOnce(); - assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + requestReplyService.requestAndAwaitReplyToTopic( new SensorReading(), "last_value/temperature/celsius/demo", SensorReading.class, - Duration.ofMillis(100), + REQUEST_TIMEOUT, Map.of(SolaceHeaderParser.TIME_TO_LIVE, neverExpire) - )); + ); - Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); assertEquals( neverExpire, - messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) ); } @Test - void requestAndAwaitReplyToTopicWithMsg_expectItsTimeToLiveKept_whenMessageCarriesOne() { + void requestAndAwaitReplyToTopicWithMsg_expectItsTimeToLiveKept_whenMessageCarriesOne() throws Exception { long timeToLiveOfTheMessage = 5_000L; + answerEveryRequestAtOnce(); - assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + requestReplyService.requestAndAwaitReplyToTopic( MessageBuilder.withPayload(new SensorReading()) .setHeader(SolaceHeaderParser.TIME_TO_LIVE, timeToLiveOfTheMessage) .build(), "last_value/temperature/celsius/demo", SensorReading.class, - Duration.ofMillis(100) - )); + REQUEST_TIMEOUT + ); - Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); assertEquals( timeToLiveOfTheMessage, - messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) ); } /** - * The Solace binder rejects a message whose expiration and time-to-live differ, so a request that carries an + * 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() { - assertThrows(TimeoutException.class, () -> requestReplyService.requestAndAwaitReplyToTopic( + void requestAndAwaitReplyToTopicWithMsg_expectNoTimeToLiveAdded_whenMessageCarriesAnExpiration() throws Exception { + answerEveryRequestAtOnce(); + + requestReplyService.requestAndAwaitReplyToTopic( MessageBuilder.withPayload(new SensorReading()) .setHeader(SolaceHeaderParser.EXPIRATION, 1_682_928_000_000L) .build(), "last_value/temperature/celsius/demo", SensorReading.class, - Duration.ofMillis(100) - )); + REQUEST_TIMEOUT + ); - Mockito.verify(streamBridge).send(anyString(), messageCaptor.capture()); assertNull( - messageCaptor.getValue().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + sentRequest().getHeaders().get(SolaceHeaderParser.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(); From 1b3dd50498dd2659016323e69ae1de99039eba82 Mon Sep 17 00:00:00 2001 From: Heiko Henning Date: Sat, 21 Nov 2026 21:19:23 +0100 Subject: [PATCH 6/6] refactor: read the message lifetime where it is written The time-to-live parsers were public API with a single, Solace-only implementation, while writing the lifetime is Solace-only anyway. A parser for another binder would have read its time-to-live only to write it into a Solace header that binder ignores. --- AGENTS.md | 17 ++++---- README.md | 3 +- ...questReplyMessageHeaderSupportService.java | 40 ++---------------- .../header/parser/SolaceHeaderParser.java | 26 +----------- .../MessageHeaderTimeToLiveParser.java | 27 ------------ .../timetolive/MessageTimeToLiveParser.java | 19 --------- .../requestreply/util/MessageTimeToLive.java | 38 ++++++++++++++--- .../service/HeaderParserTests.java | 11 ----- .../RequestReplySimpleServiceTests.java | 18 ++++---- ...impleMessageHeaderSupportServiceTests.java | 41 ++++--------------- .../util/MessageTimeToLiveTests.java | 5 +-- 11 files changed, 66 insertions(+), 179 deletions(-) delete mode 100644 src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java delete mode 100644 src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java diff --git a/AGENTS.md b/AGENTS.md index b5464c5..ccd621e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,8 +39,7 @@ src/main/java/community/solace/spring/cloud/requestreply/ │ ├── header/ │ │ ├── RequestReplyMessageHeaderSupportService.java # responder-side wrap/wrapList/wrapFlux helpers │ │ └── parser/ # ordered Message/MessageHeaders parsers (correlationId, -│ │ │ # destination, replyTo, replyIndex, totalReplies, errorMessage, -│ │ │ # timeToLive) +│ │ │ # destination, replyTo, replyIndex, totalReplies, errorMessage) │ │ ├── SolaceHeaderParser.java SpringHeaderParser.java HttpHeaderParser.java ... │ ├── logging/ # RequestReplyLogger + DefaultRequestReplyLogger │ └── messageinterceptor/ # RequestSendingInterceptor, ReplyWrappingInterceptor @@ -157,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 @@ -169,13 +170,11 @@ contexts (see §6). If a bean with the binding name already exists, do not overr - **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 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 + 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. Writing is - Solace‑only: a custom `MessageTimeToLiveParser` changes which time‑to‑live a reply copies, not which header - it is written to. + `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/README.md b/README.md index 92ccbc6..5797c81 100644 --- a/README.md +++ b/README.md @@ -631,13 +631,12 @@ Parser interfaces (root interface parses a `Message`, the `…Header…` variant - `MessageTotalRepliesParser` / `MessageHeaderTotalRepliesParser` - `MessageReplyIndexParser` / `MessageHeaderReplyIndexParser` - `MessageErrorMessageParser` / `MessageHeaderErrorMessageParser` -- `MessageTimeToLiveParser` / `MessageHeaderTimeToLiveParser` Bundled implementations, in priority order: | Parser | Order | Provides | |--------|-------|----------| -| `SolaceHeaderParser` | 200 | correlationId, destination, replyTo, timeToLive for the Solace binder | +| `SolaceHeaderParser` | 200 | correlationId, destination, replyTo for the Solace binder | | `SpringCloudStreamHeaderParser` | 10000 | destination, totalReplies for Spring Cloud Stream headers | | `SpringIntegrationHeaderParser` | 20000 | correlationId for Spring Integration headers | | `BinderHeaderParser` | 30000 | destination for Spring Cloud Stream binder headers | 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 76d0a5a..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 @@ -18,7 +18,6 @@ import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageReplyToParser; import community.solace.spring.cloud.requestreply.service.header.parser.totalreplies.MessageTotalRepliesParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyindex.MessageReplyIndexParser; -import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageTimeToLiveParser; import community.solace.spring.cloud.requestreply.service.messageinterceptor.ReplyWrappingInterceptor; import community.solace.spring.cloud.requestreply.util.MessageChunker; import org.apache.commons.lang3.tuple.Pair; @@ -39,7 +38,7 @@ import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; -import static community.solace.spring.cloud.requestreply.util.MessageTimeToLive.setTimeToLiveIfAbsent; +import static community.solace.spring.cloud.requestreply.util.MessageTimeToLive.copyTimeToLiveIfAbsent; @Service public class RequestReplyMessageHeaderSupportService { @@ -65,9 +64,6 @@ public class RequestReplyMessageHeaderSupportService { @Autowired private List errorMessageParsers; - @Autowired(required = false) - private List timeToLiveParsers = List.of(); - @Autowired private RequestReplyProperties requestReplyProperties; @Autowired @@ -155,25 +151,6 @@ public String getErrorMessage(Message message) { return null; } - /** - * Reads the time-to-live of a message through the ordered time-to-live parsers. - * - * @param message the message to read - * @return the time-to-live the message carries, or {@code null} if it never expires - */ - public Duration getTimeToLive(Message message) { - if (message == null) { - return null; - } - for (MessageTimeToLiveParser p : timeToLiveParsers) { - Duration value = p.getTimeToLive(message); - if (value != null) { - return value; - } - } - return null; - } - /** * wrap the given function, copying message headers from incoming to outgoing message, * properly setting correlation ID, target and the time-to-live of the request @@ -239,7 +216,7 @@ public final > Function, Messa mb.setHeader(header.getKey(), header.getValue()); } } - adoptTimeToLive(request, mb); + copyTimeToLiveIfAbsent(request, mb); return this.replyWrappingInterceptor.interceptReplyWrappingPayloadMessage(mb.build(), bindingName); } catch (Exception e) { @@ -459,7 +436,7 @@ private void transferAndAdoptHeaders(Message request, MessageBuilder void transferAndAdoptHeaders(Message request, @@ -484,17 +461,6 @@ private void transferAndAdoptHeaders(Message request, } } - /** - * Gives the reply the time-to-live of the request, unless the reply already carries a lifetime. Runs after every - * other header of the reply is set, so that it sees a lifetime set by the caller. - */ - private void adoptTimeToLive(Message request, MessageBuilder mb) { - Duration requestTimeToLive = getTimeToLive(request); - if (requestTimeToLive != null) { - setTimeToLiveIfAbsent(mb, requestTimeToLive); - } - } - @FunctionalInterface public interface ThrowingFunction { diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java index 9bc5c70..0f7b148 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/SolaceHeaderParser.java @@ -1,20 +1,14 @@ package community.solace.spring.cloud.requestreply.service.header.parser; -import java.time.Duration; -import java.util.Optional; - import com.solacesystems.jcsmp.Destination; import community.solace.spring.cloud.requestreply.service.header.parser.correlationid.MessageHeaderCorrelationIdParser; import community.solace.spring.cloud.requestreply.service.header.parser.destination.MessageHeaderDestinationParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageHeaderReplyToParser; -import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageHeaderTimeToLiveParser; - import org.springframework.messaging.MessageHeaders; -public class SolaceHeaderParser implements MessageHeaderCorrelationIdParser, MessageHeaderDestinationParser, MessageHeaderReplyToParser, MessageHeaderTimeToLiveParser { - public static final String TIME_TO_LIVE = "solace_timeToLive"/*SolaceHeaders.TIME_TO_LIVE*/; - public static final String EXPIRATION = "solace_expiration"/*SolaceHeaders.EXPIRATION*/; +import java.util.Optional; +public class SolaceHeaderParser implements MessageHeaderCorrelationIdParser, MessageHeaderDestinationParser, MessageHeaderReplyToParser { @Override public String getCorrelationId(MessageHeaders headers) { return headers.get("solace_correlationId"/*SolaceHeaders.CORRELATION_ID*/, String.class); @@ -29,20 +23,4 @@ public String getDestination(MessageHeaders headers) { public String getReplyTo(MessageHeaders headers) { return Optional.ofNullable(headers.get("solace_replyTo"/*SolaceHeaders.REPLY_TO*/, Destination.class)).map(Destination::getName).orElse(null); } - - /** - * Reads {@value #TIME_TO_LIVE}, which the Solace binder sets on every inbound message. - * - * @param headers the headers to read - * @return the time-to-live of the message, or {@code null} if it has none or its time-to-live is 0, which - * Solace reads as "never expire" - */ - @Override - public Duration getTimeToLive(MessageHeaders headers) { - Object timeToLive = headers.get(TIME_TO_LIVE); - if (!(timeToLive instanceof Number millis) || millis.longValue() <= 0) { - return null; - } - return Duration.ofMillis(millis.longValue()); - } } diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java deleted file mode 100644 index 2eea82b..0000000 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageHeaderTimeToLiveParser.java +++ /dev/null @@ -1,27 +0,0 @@ -package community.solace.spring.cloud.requestreply.service.header.parser.timetolive; - -import java.time.Duration; - -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHeaders; - -/** - * Reads the time-to-live of a message from its headers. - */ -@FunctionalInterface -public interface MessageHeaderTimeToLiveParser extends MessageTimeToLiveParser { - @Override - default Duration getTimeToLive(Message message) { - return message == null ? - null : - getTimeToLive(message.getHeaders()); - } - - /** - * Reads the time-to-live from the headers of a message. - * - * @param headers the headers to read - * @return the time-to-live of the message, or {@code null} if it never expires or the parser does not know - */ - Duration getTimeToLive(MessageHeaders headers); -} \ No newline at end of file diff --git a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java b/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java deleted file mode 100644 index 3d28ec2..0000000 --- a/src/main/java/community/solace/spring/cloud/requestreply/service/header/parser/timetolive/MessageTimeToLiveParser.java +++ /dev/null @@ -1,19 +0,0 @@ -package community.solace.spring.cloud.requestreply.service.header.parser.timetolive; - -import java.time.Duration; - -import org.springframework.messaging.Message; - -/** - * Reads how long a message may live before the broker discards it. - */ -@FunctionalInterface -public interface MessageTimeToLiveParser { - /** - * Reads the time-to-live of a message. - * - * @param message the message to read - * @return the time-to-live of the message, or {@code null} if it never expires or the parser does not know - */ - Duration getTimeToLive(Message message); -} \ No newline at end of file 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 index cb45315..7ae4573 100644 --- a/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java +++ b/src/main/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLive.java @@ -3,15 +3,24 @@ import java.time.Duration; import java.util.Map; -import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; - 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. + * 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. */ @@ -34,13 +43,30 @@ private MessageTimeToLive() { */ public static void setTimeToLiveIfAbsent(MessageBuilder messageBuilder, Duration timeToLive) { Map headers = messageBuilder.getHeaders(); - boolean carriesLifetime = headers.containsKey(SolaceHeaderParser.TIME_TO_LIVE) || - headers.containsKey(SolaceHeaderParser.EXPIRATION); + boolean carriesLifetime = headers.containsKey(TIME_TO_LIVE) || + headers.containsKey(EXPIRATION); if (carriesLifetime) { return; } - messageBuilder.setHeader(SolaceHeaderParser.TIME_TO_LIVE, withinTheBoundsSolaceAccepts(timeToLive).toMillis()); + 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) { diff --git a/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java b/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java index a233024..ca41211 100644 --- a/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java +++ b/src/test/java/community/solace/spring/cloud/requestreply/service/HeaderParserTests.java @@ -6,7 +6,6 @@ import community.solace.spring.cloud.requestreply.service.header.parser.destination.MessageDestinationParser; import community.solace.spring.cloud.requestreply.service.header.parser.errormessage.MessageErrorMessageParser; import community.solace.spring.cloud.requestreply.service.header.parser.replyto.MessageReplyToParser; -import community.solace.spring.cloud.requestreply.service.header.parser.timetolive.MessageTimeToLiveParser; import community.solace.spring.cloud.requestreply.service.header.parser.totalreplies.MessageTotalRepliesParser; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -39,9 +38,6 @@ class HeaderParserTests extends AbstractRequestReplySimpleIT { @Autowired private List messageErrorMessageParsers; - @Autowired - private List messageTimeToLiveParsers; - @Test void correlationIdParsersShouldNotThrowExceptionWhenGivenNull() { for (MessageCorrelationIdParser parser : messageCorrelationIdParsers) { @@ -77,13 +73,6 @@ void errorMessageParsersShouldNotThrowExceptionWhenGivenNull() { } } - @Test - void timeToLiveParsersShouldNotThrowExceptionWhenGivenNull() { - for (MessageTimeToLiveParser parser : messageTimeToLiveParsers) { - assertNull((parser).getTimeToLive(null), String.format("%s can not handle null values", parser)); - } - } - @Test void headerParserPrecedenceIsObeyed() { MessageBuilder mb = MessageBuilder.withPayload("headerParserPrecedenceIsObeyed"); 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 3d71e31..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 @@ -11,9 +11,9 @@ import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; import community.solace.spring.cloud.requestreply.model.SensorReading; -import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; 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; @@ -303,7 +303,7 @@ void requestAndAwaitReplyToTopic_expectTimeoutAsTimeToLive_whenRequestSent() thr assertEquals( REQUEST_TIMEOUT.toMillis(), - sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) ); } @@ -325,7 +325,7 @@ void requestReplyToTopicReactive_expectTimeoutAsTimeToLive_whenRequestSent() { assertEquals( REQUEST_TIMEOUT.toMillis(), - sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) ); } @@ -339,12 +339,12 @@ void requestAndAwaitReplyToTopic_expectCallersTimeToLive_whenGivenInAdditionalHe "last_value/temperature/celsius/demo", SensorReading.class, REQUEST_TIMEOUT, - Map.of(SolaceHeaderParser.TIME_TO_LIVE, neverExpire) + Map.of(MessageTimeToLive.TIME_TO_LIVE, neverExpire) ); assertEquals( neverExpire, - sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) ); } @@ -355,7 +355,7 @@ void requestAndAwaitReplyToTopicWithMsg_expectItsTimeToLiveKept_whenMessageCarri requestReplyService.requestAndAwaitReplyToTopic( MessageBuilder.withPayload(new SensorReading()) - .setHeader(SolaceHeaderParser.TIME_TO_LIVE, timeToLiveOfTheMessage) + .setHeader(MessageTimeToLive.TIME_TO_LIVE, timeToLiveOfTheMessage) .build(), "last_value/temperature/celsius/demo", SensorReading.class, @@ -364,7 +364,7 @@ void requestAndAwaitReplyToTopicWithMsg_expectItsTimeToLiveKept_whenMessageCarri assertEquals( timeToLiveOfTheMessage, - sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) ); } @@ -378,7 +378,7 @@ void requestAndAwaitReplyToTopicWithMsg_expectNoTimeToLiveAdded_whenMessageCarri requestReplyService.requestAndAwaitReplyToTopic( MessageBuilder.withPayload(new SensorReading()) - .setHeader(SolaceHeaderParser.EXPIRATION, 1_682_928_000_000L) + .setHeader(MessageTimeToLive.EXPIRATION, 1_682_928_000_000L) .build(), "last_value/temperature/celsius/demo", SensorReading.class, @@ -386,7 +386,7 @@ void requestAndAwaitReplyToTopicWithMsg_expectNoTimeToLiveAdded_whenMessageCarri ); assertNull( - sentRequest().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + sentRequest().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) ); } 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 42c22bf..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 @@ -3,8 +3,8 @@ import com.solacesystems.jcsmp.SDTStream; import com.solacesystems.jcsmp.impl.sdt.StreamImpl; import community.solace.spring.cloud.requestreply.AbstractRequestReplySimpleIT; -import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; 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; @@ -675,29 +675,6 @@ void wrapFlux_exception() { } - @Test - void getTimeToLive() { - Message m = MessageBuilder.withPayload("demo") - .setHeader(SolaceHeaderParser.TIME_TO_LIVE, 5_000L) - .build(); - - assertEquals( - Duration.ofSeconds(5), - supportService.getTimeToLive(m) - ); - } - - @Test - void getTimeToLive_ofZero_meansTheMessageNeverExpires() { - Message m = MessageBuilder.withPayload("demo") - .setHeader(SolaceHeaderParser.TIME_TO_LIVE, 0L) - .build(); - - assertNull( - supportService.getTimeToLive(m) - ); - } - @Test void wrap_expectTheRequestsTimeToLive_whenRequestCarriesOne() { Function, Message> supplier = supportService.wrap(m -> m, (Class) null); @@ -717,7 +694,7 @@ void wrap_expectNoTimeToLive_whenRequestCarriesNone() { .build()); assertNull( - answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) ); } @@ -728,7 +705,7 @@ void wrap_expectNoTimeToLive_whenRequestNeverExpires() { Message answerM = supplier.apply(requestWithTimeToLive(Duration.ZERO)); assertNull( - answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) ); } @@ -737,7 +714,7 @@ void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { long neverExpire = 0L; Function, Message> supplier = supportService.wrap( m -> m, - Map.of(SolaceHeaderParser.TIME_TO_LIVE, neverExpire), + Map.of(MessageTimeToLive.TIME_TO_LIVE, neverExpire), (Class) null ); @@ -745,7 +722,7 @@ void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { assertEquals( neverExpire, - answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class) + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class) ); } @@ -756,14 +733,14 @@ void wrap_expectCallersTimeToLive_whenGivenInAdditionalHeaders() { void wrap_expectNoTimeToLive_whenAdditionalHeadersGiveAnExpiration() { Function, Message> supplier = supportService.wrap( m -> m, - Map.of(SolaceHeaderParser.EXPIRATION, 1_682_928_000_000L), + Map.of(MessageTimeToLive.EXPIRATION, 1_682_928_000_000L), (Class) null ); Message answerM = supplier.apply(requestWithTimeToLive(REQUEST_TIME_TO_LIVE)); assertNull( - answerM.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE) + answerM.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE) ); } @@ -818,14 +795,14 @@ 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(SolaceHeaderParser.TIME_TO_LIVE, requestTimeToLive.toMillis()) + .setHeader(MessageTimeToLive.TIME_TO_LIVE, requestTimeToLive.toMillis()) .build(); } private void assertTheRequestsTimeToLive(Message reply) { assertEquals( REQUEST_TIME_TO_LIVE.toMillis(), - reply.getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), + reply.getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class), "The reply must expire like the request it answers" ); } 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 index c0a2607..3e0860f 100644 --- a/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java +++ b/src/test/java/community/solace/spring/cloud/requestreply/util/MessageTimeToLiveTests.java @@ -3,7 +3,6 @@ import java.time.Duration; import java.time.temporal.ChronoUnit; -import community.solace.spring.cloud.requestreply.service.header.parser.SolaceHeaderParser; import org.junit.jupiter.api.Test; import org.springframework.integration.support.MessageBuilder; @@ -25,7 +24,7 @@ void setTimeToLiveIfAbsent_expectOneMillisecond_whenTimeToLiveRoundsDownToZero() assertEquals( 1L, - messageBuilder.build().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), + messageBuilder.build().getHeaders().get(MessageTimeToLive.TIME_TO_LIVE, Long.class), "A time-to-live of 0 would let the message never expire" ); } @@ -38,7 +37,7 @@ void setTimeToLiveIfAbsent_expectTenYears_whenTheCallerWaitsForever() { assertEquals( TEN_YEARS_IN_MILLIS, - messageBuilder.build().getHeaders().get(SolaceHeaderParser.TIME_TO_LIVE, Long.class), + 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" ); }