This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27198-nats-jetstream-producer in repository https://gitbox.apache.org/repos/asf/camel.git
commit 8df030853c23cc57581effad7706e0f71ea886fd Author: Claus Ibsen <[email protected]> AuthorDate: Tue Nov 24 16:55:24 2026 +0100 CAMEL-27198: camel-nats - JetStream producer uses requestTimeout and jetstreamName, and says when no acknowledgement came - The JetStream context is created once at the start, with requestTimeout in JetStreamOptions, so a synchronous publish waits requestTimeout instead of the connection timeout of jnats. - When jetstreamName is set, the producer creates that stream at the start, as the consumer does, unless it exists or another stream takes in the subject. The dead addStream branch is removed. - A missing acknowledgement says so: "No acknowledgement from JetStream for subject X within N ms", also when jnats cancels the request. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../org/apache/camel/catalog/components/nats.json | 8 +- .../apache/camel/catalog/docs/nats-component.adoc | 15 ++ .../org/apache/camel/component/nats/nats.json | 8 +- .../camel-nats/src/main/docs/nats-component.adoc | 15 ++ .../camel/component/nats/NatsConfiguration.java | 12 +- .../apache/camel/component/nats/NatsProducer.java | 127 +++++++++- .../component/nats/NatsProducerJetStreamTest.java | 269 +++++++++++++++++++++ .../nats/jetstream/NatsJetstreamProducerIT.java | 162 +++++++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 11 + .../component/dsl/NatsComponentBuilderFactory.java | 14 +- .../endpoint/dsl/NatsEndpointBuilderFactory.java | 36 ++- 11 files changed, 644 insertions(+), 33 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/nats.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/nats.json index d75622d20f75..5eed5b88b3db 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/nats.json +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/nats.json @@ -29,7 +29,7 @@ "flushConnection": { "index": 2, "kind": "property", "displayName": "Flush Connection", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Define if we want to flush connection when stopping or not" }, "flushTimeout": { "index": 3, "kind": "property", "displayName": "Flush Timeout", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 1000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Set the flush timeout (in milliseconds)" }, "jetstreamEnabled": { "index": 4, "kind": "property", "displayName": "Jetstream Enabled", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets whether to enable JetStream support for this endpoint." }, - "jetstreamName": { "index": 5, "kind": "property", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets the name of the JetStream stream to use." }, + "jetstreamName": { "index": 5, "kind": "property", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consume [...] "maxPingsOut": { "index": 6, "kind": "property", "displayName": "Max Pings Out", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 2, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "maximum number of pings have not received a response allowed by the client" }, "maxReconnectAttempts": { "index": 7, "kind": "property", "displayName": "Max Reconnect Attempts", "group": "common", "label": "", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 60, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Max reconnection attempts" }, "noEcho": { "index": 8, "kind": "property", "displayName": "No Echo", "group": "common", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Turn off echo. If supported by the gnatsd version you are connecting to this flag will prevent the server from ech [...] @@ -58,7 +58,7 @@ "consumerConfiguration": { "index": 31, "kind": "property", "displayName": "Consumer Configuration", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "object", "javaType": "io.nats.client.api.ConsumerConfiguration", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets a custom ConsumerConfiguration object f [...] "lazyStartProducer": { "index": 32, "kind": "property", "displayName": "Lazy Start Producer", "group": "producer", "label": "producer", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fai [...] "replySubject": { "index": 33, "kind": "property", "displayName": "Reply Subject", "group": "producer", "label": "producer", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "the subject to which subscribers should send response" }, - "requestTimeout": { "index": 34, "kind": "property", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds" }, + "requestTimeout": { "index": 34, "kind": "property", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds. With JetStream, the time to wait for the acknowledgement [...] "autowiredEnabled": { "index": 35, "kind": "property", "displayName": "Autowired Enabled", "group": "advanced", "label": "advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "description": "Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching [...] "connection": { "index": 36, "kind": "property", "displayName": "Connection", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "io.nats.client.Connection", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Reference an already instantiated connection to Nats server" }, "headerFilterStrategy": { "index": 37, "kind": "property", "displayName": "Header Filter Strategy", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.HeaderFilterStrategy", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "To use a custom header filter strategy." }, @@ -93,7 +93,7 @@ "flushConnection": { "index": 2, "kind": "parameter", "displayName": "Flush Connection", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Define if we want to flush connection when stopping or not" }, "flushTimeout": { "index": 3, "kind": "parameter", "displayName": "Flush Timeout", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 1000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Set the flush timeout (in milliseconds)" }, "jetstreamEnabled": { "index": 4, "kind": "parameter", "displayName": "Jetstream Enabled", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets whether to enable JetStream support for this endpoint." }, - "jetstreamName": { "index": 5, "kind": "parameter", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets the name of the JetStream stream to use." }, + "jetstreamName": { "index": 5, "kind": "parameter", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consum [...] "maxPingsOut": { "index": 6, "kind": "parameter", "displayName": "Max Pings Out", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 2, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "maximum number of pings have not received a response allowed by the client" }, "maxReconnectAttempts": { "index": 7, "kind": "parameter", "displayName": "Max Reconnect Attempts", "group": "common", "label": "", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 60, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Max reconnection attempts" }, "noEcho": { "index": 8, "kind": "parameter", "displayName": "No Echo", "group": "common", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Turn off echo. If supported by the gnatsd version you are connecting to this flag will prevent the server from ec [...] @@ -123,7 +123,7 @@ "exceptionHandler": { "index": 32, "kind": "parameter", "displayName": "Exception Handler", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.ExceptionHandler", "optionalPrefix": "consumer.", "deprecated": false, "autowired": false, "secret": false, "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By de [...] "exchangePattern": { "index": 33, "kind": "parameter", "displayName": "Exchange Pattern", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "enum", "javaType": "org.apache.camel.ExchangePattern", "enum": [ "InOnly", "InOut" ], "deprecated": false, "autowired": false, "secret": false, "description": "Sets the exchange pattern when the consumer creates an exchange." }, "replySubject": { "index": 34, "kind": "parameter", "displayName": "Reply Subject", "group": "producer", "label": "producer", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "the subject to which subscribers should send response" }, - "requestTimeout": { "index": 35, "kind": "parameter", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds" }, + "requestTimeout": { "index": 35, "kind": "parameter", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds. With JetStream, the time to wait for the acknowledgement [...] "lazyStartProducer": { "index": 36, "kind": "parameter", "displayName": "Lazy Start Producer", "group": "producer (advanced)", "label": "producer,advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a produ [...] "connection": { "index": 37, "kind": "parameter", "displayName": "Connection", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "io.nats.client.Connection", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Reference an already instantiated connection to Nats server" }, "headerFilterStrategy": { "index": 38, "kind": "parameter", "displayName": "Header Filter Strategy", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.HeaderFilterStrategy", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "To use a custom header filter strategy." }, diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/nats-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/nats-component.adoc index cf12fae9e773..45ab3b232c60 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/nats-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/nats-component.adoc @@ -285,6 +285,21 @@ YAML:: ---- ==== +=== JetStream producer + +With `jetstreamEnabled=true`, the producer publishes each message to JetStream and waits until the stream that takes +in the subject has stored it. Sending fails with `503 No Responders Available For Request` when no stream takes in the +subject. On a server without JetStream, the message is published as plain NATS. + +When `jetstreamName` is set, the producer checks at startup that this stream exists. When it does not, and no other +stream takes in the subject, the producer creates it with the subject of the topic, as the consumer does. When the +stream cannot be checked or created, the producer logs a WARN and starts anyway. The message is stored by the stream +that takes in the subject, whatever its name. + +`requestTimeout` is how long the producer waits for the acknowledgement. With `jetstreamAsync=true` (the default), the +NATS client also gives up on the acknowledgement after `requestCleanupInterval` (5 seconds by default) to twice that, +so set both to wait longer. + === Manual Acknowledgment (JetStream) When consuming from JetStream, by default messages are automatically acknowledged diff --git a/components/camel-nats/src/generated/resources/META-INF/org/apache/camel/component/nats/nats.json b/components/camel-nats/src/generated/resources/META-INF/org/apache/camel/component/nats/nats.json index d75622d20f75..5eed5b88b3db 100644 --- a/components/camel-nats/src/generated/resources/META-INF/org/apache/camel/component/nats/nats.json +++ b/components/camel-nats/src/generated/resources/META-INF/org/apache/camel/component/nats/nats.json @@ -29,7 +29,7 @@ "flushConnection": { "index": 2, "kind": "property", "displayName": "Flush Connection", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Define if we want to flush connection when stopping or not" }, "flushTimeout": { "index": 3, "kind": "property", "displayName": "Flush Timeout", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 1000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Set the flush timeout (in milliseconds)" }, "jetstreamEnabled": { "index": 4, "kind": "property", "displayName": "Jetstream Enabled", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets whether to enable JetStream support for this endpoint." }, - "jetstreamName": { "index": 5, "kind": "property", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets the name of the JetStream stream to use." }, + "jetstreamName": { "index": 5, "kind": "property", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consume [...] "maxPingsOut": { "index": 6, "kind": "property", "displayName": "Max Pings Out", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 2, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "maximum number of pings have not received a response allowed by the client" }, "maxReconnectAttempts": { "index": 7, "kind": "property", "displayName": "Max Reconnect Attempts", "group": "common", "label": "", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 60, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Max reconnection attempts" }, "noEcho": { "index": 8, "kind": "property", "displayName": "No Echo", "group": "common", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Turn off echo. If supported by the gnatsd version you are connecting to this flag will prevent the server from ech [...] @@ -58,7 +58,7 @@ "consumerConfiguration": { "index": 31, "kind": "property", "displayName": "Consumer Configuration", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "object", "javaType": "io.nats.client.api.ConsumerConfiguration", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets a custom ConsumerConfiguration object f [...] "lazyStartProducer": { "index": 32, "kind": "property", "displayName": "Lazy Start Producer", "group": "producer", "label": "producer", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fai [...] "replySubject": { "index": 33, "kind": "property", "displayName": "Reply Subject", "group": "producer", "label": "producer", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "the subject to which subscribers should send response" }, - "requestTimeout": { "index": 34, "kind": "property", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds" }, + "requestTimeout": { "index": 34, "kind": "property", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds. With JetStream, the time to wait for the acknowledgement [...] "autowiredEnabled": { "index": 35, "kind": "property", "displayName": "Autowired Enabled", "group": "advanced", "label": "advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "description": "Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching [...] "connection": { "index": 36, "kind": "property", "displayName": "Connection", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "io.nats.client.Connection", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Reference an already instantiated connection to Nats server" }, "headerFilterStrategy": { "index": 37, "kind": "property", "displayName": "Header Filter Strategy", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.HeaderFilterStrategy", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "To use a custom header filter strategy." }, @@ -93,7 +93,7 @@ "flushConnection": { "index": 2, "kind": "parameter", "displayName": "Flush Connection", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Define if we want to flush connection when stopping or not" }, "flushTimeout": { "index": 3, "kind": "parameter", "displayName": "Flush Timeout", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 1000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Set the flush timeout (in milliseconds)" }, "jetstreamEnabled": { "index": 4, "kind": "parameter", "displayName": "Jetstream Enabled", "group": "common", "label": "common", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets whether to enable JetStream support for this endpoint." }, - "jetstreamName": { "index": 5, "kind": "parameter", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Sets the name of the JetStream stream to use." }, + "jetstreamName": { "index": 5, "kind": "parameter", "displayName": "Jetstream Name", "group": "common", "label": "common", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consum [...] "maxPingsOut": { "index": 6, "kind": "parameter", "displayName": "Max Pings Out", "group": "common", "label": "common", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 2, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "maximum number of pings have not received a response allowed by the client" }, "maxReconnectAttempts": { "index": 7, "kind": "parameter", "displayName": "Max Reconnect Attempts", "group": "common", "label": "", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 60, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Max reconnection attempts" }, "noEcho": { "index": 8, "kind": "parameter", "displayName": "No Echo", "group": "common", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Turn off echo. If supported by the gnatsd version you are connecting to this flag will prevent the server from ec [...] @@ -123,7 +123,7 @@ "exceptionHandler": { "index": 32, "kind": "parameter", "displayName": "Exception Handler", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.ExceptionHandler", "optionalPrefix": "consumer.", "deprecated": false, "autowired": false, "secret": false, "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By de [...] "exchangePattern": { "index": 33, "kind": "parameter", "displayName": "Exchange Pattern", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "enum", "javaType": "org.apache.camel.ExchangePattern", "enum": [ "InOnly", "InOut" ], "deprecated": false, "autowired": false, "secret": false, "description": "Sets the exchange pattern when the consumer creates an exchange." }, "replySubject": { "index": 34, "kind": "parameter", "displayName": "Reply Subject", "group": "producer", "label": "producer", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "the subject to which subscribers should send response" }, - "requestTimeout": { "index": 35, "kind": "parameter", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds" }, + "requestTimeout": { "index": 35, "kind": "parameter", "displayName": "Request Timeout", "group": "producer", "label": "producer", "required": false, "type": "integer", "javaType": "long", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 20000, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Request timeout in milliseconds. With JetStream, the time to wait for the acknowledgement [...] "lazyStartProducer": { "index": 36, "kind": "parameter", "displayName": "Lazy Start Producer", "group": "producer (advanced)", "label": "producer,advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a produ [...] "connection": { "index": 37, "kind": "parameter", "displayName": "Connection", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "io.nats.client.Connection", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "Reference an already instantiated connection to Nats server" }, "headerFilterStrategy": { "index": 38, "kind": "parameter", "displayName": "Header Filter Strategy", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.HeaderFilterStrategy", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.nats.NatsConfiguration", "configurationField": "configuration", "description": "To use a custom header filter strategy." }, diff --git a/components/camel-nats/src/main/docs/nats-component.adoc b/components/camel-nats/src/main/docs/nats-component.adoc index cf12fae9e773..45ab3b232c60 100644 --- a/components/camel-nats/src/main/docs/nats-component.adoc +++ b/components/camel-nats/src/main/docs/nats-component.adoc @@ -285,6 +285,21 @@ YAML:: ---- ==== +=== JetStream producer + +With `jetstreamEnabled=true`, the producer publishes each message to JetStream and waits until the stream that takes +in the subject has stored it. Sending fails with `503 No Responders Available For Request` when no stream takes in the +subject. On a server without JetStream, the message is published as plain NATS. + +When `jetstreamName` is set, the producer checks at startup that this stream exists. When it does not, and no other +stream takes in the subject, the producer creates it with the subject of the topic, as the consumer does. When the +stream cannot be checked or created, the producer logs a WARN and starts anyway. The message is stored by the stream +that takes in the subject, whatever its name. + +`requestTimeout` is how long the producer waits for the acknowledgement. With `jetstreamAsync=true` (the default), the +NATS client also gives up on the acknowledgement after `requestCleanupInterval` (5 seconds by default) to twice that, +so set both to wait longer. + === Manual Acknowledgment (JetStream) When consuming from JetStream, by default messages are automatically acknowledged diff --git a/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsConfiguration.java b/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsConfiguration.java index a17a57130e7c..2708dcd16011 100644 --- a/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsConfiguration.java +++ b/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsConfiguration.java @@ -239,7 +239,9 @@ public class NatsConfiguration implements Cloneable { } /** - * Request timeout in milliseconds + * Request timeout in milliseconds. With JetStream, the time to wait for the acknowledgement of a published message. + * With jetstreamAsync=true, the NATS client also gives up on the acknowledgement after requestCleanupInterval (to + * twice that), so a longer wait needs a longer requestCleanupInterval too. */ public void setRequestTimeout(long requestTimeout) { this.requestTimeout = requestTimeout; @@ -521,15 +523,15 @@ public class NatsConfiguration implements Cloneable { this.jetstreamEnabled = jetstreamEnabled; } - /** - * The name of the JetStream stream to use. If not specified, a default stream will be used if JetStream is enabled. - */ public String getJetstreamName() { return jetstreamName; } /** - * Sets the name of the JetStream stream to use. + * The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consumer). + * When the stream does not exist, the consumer creates it with the subject of the topic. The producer creates it in + * the same way, unless another stream already takes in the subject. The producer publishes to the subject, and the + * message is stored by the stream that takes in the subject, whatever its name. */ public void setJetstreamName(String jetstreamName) { this.jetstreamName = jetstreamName; diff --git a/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsProducer.java b/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsProducer.java index ee4a2493e6fe..cdef74e31e07 100644 --- a/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsProducer.java +++ b/components/camel-nats/src/main/java/org/apache/camel/component/nats/NatsProducer.java @@ -19,6 +19,8 @@ package org.apache.camel.component.nats; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.List; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; @@ -30,9 +32,12 @@ import io.nats.client.Connection.Status; import io.nats.client.JetStream; import io.nats.client.JetStreamApiException; import io.nats.client.JetStreamManagement; +import io.nats.client.JetStreamOptions; import io.nats.client.Message; import io.nats.client.api.PublishAck; +import io.nats.client.api.ServerInfo; import io.nats.client.api.StreamConfiguration; +import io.nats.client.api.StreamInfo; import io.nats.client.impl.Headers; import io.nats.client.impl.NatsMessage; import org.apache.camel.AsyncCallback; @@ -54,6 +59,8 @@ public class NatsProducer extends DefaultAsyncProducer { private final ExecutorServiceManager executorServiceManager; private ScheduledExecutorService scheduler; private Connection connection; + // the JetStream context of the connection, with the requestTimeout of the endpoint + private volatile JetStream jetStream; public NatsProducer(NatsEndpoint endpoint) { super(endpoint); @@ -180,6 +187,84 @@ public class NatsProducer extends DefaultAsyncProducer { this.connection = this.getEndpoint().getConfiguration().getConnection() != null ? this.getEndpoint().getConfiguration().getConnection() : this.getEndpoint().getConnection(); + + final NatsConfiguration config = this.getEndpoint().getConfiguration(); + final ServerInfo serverInfo = this.connection.getServerInfo(); + // a restarted producer has a new connection + this.jetStream = null; + if (config.isJetstreamEnabled() && serverInfo != null && serverInfo.isJetStreamAvailable()) { + // the JetStream context belongs to the connection, which stays the same object when jnats reconnects + this.jetStream = createJetStream(config); + if (ObjectHelper.isNotEmpty(config.getJetstreamName())) { + ensureStream(config); + } + } + } + + private JetStream createJetStream(NatsConfiguration config) throws IOException { + // jnats uses its own request timeout (the connection timeout) for the acknowledgement of a publish, unless the + // JetStream context has one + final JetStreamOptions.Builder options = JetStreamOptions.builder(); + if (config.getRequestTimeout() > 0) { + options.requestTimeout(Duration.ofMillis(config.getRequestTimeout())); + } + return this.connection.jetStream(options.build()); + } + + private JetStream getJetStream(NatsConfiguration config) throws IOException { + JetStream js = this.jetStream; + if (js == null) { + // JetStream was not available when the producer started + js = createJetStream(config); + this.jetStream = js; + } + return js; + } + + /** + * Creates the stream named by jetstreamName with the subject of the topic, as the consumer does, when it does not + * exist and no other stream takes in the subject. A failure is logged and does not stop the producer from starting: + * the publish itself fails when no stream takes in the subject. + */ + private void ensureStream(NatsConfiguration config) { + final String streamName = config.getJetstreamName(); + final String topic = config.getTopic(); + try { + final JetStreamManagement jsm = this.connection.jetStreamManagement(); + if (lookupStream(jsm, streamName) != null) { + LOG.debug("JetStream stream '{}' already exists. Skipping creation.", streamName); + return; + } + final List<String> others = jsm.getStreamNames(topic); + if (others != null && !others.isEmpty()) { + LOG.info("JetStream stream '{}' does not exist, and is not created: the messages to subject {} are stored" + + " by the stream {}", + streamName, topic, others); + return; + } + LOG.debug("Creating JetStream stream '{}' for subject {}", streamName, topic); + jsm.addStream(StreamConfiguration.builder() + .name(streamName) + .subjects(topic) + .build()); + LOG.info("JetStream stream '{}' created successfully.", streamName); + } catch (Exception e) { + LOG.warn("Cannot check or create the JetStream stream '{}' for subject {} due to: {}", + streamName, topic, e.getMessage()); + LOG.debug("JetStream stream failure", e); + } + } + + private static StreamInfo lookupStream(JetStreamManagement jsm, String streamName) + throws IOException, JetStreamApiException { + try { + return jsm.getStreamInfo(streamName); + } catch (JetStreamApiException e) { + if (e.getErrorCode() == 404) { + return null; + } + throw e; + } } @Override @@ -223,19 +308,10 @@ public class NatsProducer extends DefaultAsyncProducer { private void publishWithJetStream(NatsConfiguration config, final byte[] body, final Exchange exchange) throws Exception { LOG.debug("JetStream is available"); - JetStreamManagement jsm; - JetStream js; + final JetStream js; try { - jsm = this.connection.jetStreamManagement(); - js = jsm.jetStream(); - if (js == null) { - jsm.addStream(StreamConfiguration.builder() - .name(config.getJetstreamName()) - .subjects(config.getTopic()) - .build()); - js = jsm.jetStream(); - } - } catch (IOException | JetStreamApiException e) { + js = getJetStream(config); + } catch (IOException e) { throw new Exception("Failed to initialize JetStream: " + e.getMessage(), e); } @@ -255,7 +331,22 @@ public class NatsProducer extends DefaultAsyncProducer { CompletableFuture<PublishAck> future = js.publishAsync(jetStreamMessage); try { pa = future.get(config.getRequestTimeout(), TimeUnit.MILLISECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e) { + } catch (TimeoutException e) { + throw new Exception( + "No acknowledgement from JetStream for subject " + config.getTopic() + " within " + + config.getRequestTimeout() + " ms", + e); + } catch (CancellationException e) { + throw noAcknowledgement(config, e); + } catch (ExecutionException e) { + // jnats completes the future of the acknowledgement with a CancellationException (or a TimeoutException) + // when it gives up on it, which the future of the PublishAck wraps + if (e.getCause() instanceof CancellationException || e.getCause() instanceof TimeoutException) { + throw noAcknowledgement(config, e.getCause()); + } + throw new Exception("Failed to publish message asynchronously with JetStream: " + e.getMessage(), e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); throw new Exception("Failed to publish message asynchronously with JetStream: " + e.getMessage(), e); } LOG.debug("Publish Sequence async: {}", pa.getSeqno()); @@ -269,6 +360,16 @@ public class NatsProducer extends DefaultAsyncProducer { } } + private static Exception noAcknowledgement(NatsConfiguration config, Throwable cause) { + // jnats gives up on the acknowledgement of an asynchronous publish at its next request cleanup after + // requestCleanupInterval, whatever the requestTimeout + return new Exception( + "No acknowledgement from JetStream for subject " + config.getTopic() + ": " + cause.getMessage() + + " (with jetstreamAsync=true the NATS client gives up on the acknowledgement after" + + " requestCleanupInterval, " + config.getRequestCleanupInterval() + " ms, to twice that)", + cause); + } + private void publishWithoutJetStream(NatsConfiguration config, final byte[] body, final Exchange exchange) { final NatsMessage.Builder builder = NatsMessage.builder() .data(body) diff --git a/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsProducerJetStreamTest.java b/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsProducerJetStreamTest.java new file mode 100644 index 000000000000..ca96ce9ffaae --- /dev/null +++ b/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsProducerJetStreamTest.java @@ -0,0 +1,269 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.nats; + +import java.io.IOException; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import io.nats.client.Connection; +import io.nats.client.JetStream; +import io.nats.client.JetStreamApiException; +import io.nats.client.JetStreamManagement; +import io.nats.client.JetStreamOptions; +import io.nats.client.Message; +import io.nats.client.api.ApiResponse; +import io.nats.client.api.PublishAck; +import io.nats.client.api.ServerInfo; +import io.nats.client.api.StreamConfiguration; +import io.nats.client.api.StreamInfo; +import io.nats.client.impl.NatsMessage; +import io.nats.client.support.JsonParser; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The JetStream producer: the requestTimeout reaches jnats, a missing acknowledgement is reported clearly, and the + * stream of jetstreamName is created when it does not exist (CAMEL-27198). + */ +class NatsProducerJetStreamTest extends CamelTestSupport { + + private final FakeServer server = new FakeServer(); + + @Override + protected RouteBuilder createRouteBuilder() { + context.getRegistry().bind("conn", server.connection()); + return new RouteBuilder() { + @Override + public void configure() { + // the tests send to the endpoint directly + } + }; + } + + private Exchange send(String options) { + return template.send("nats:orders?connection=#conn&jetstreamEnabled=true" + options, + e -> e.getIn().setBody("order-1")); + } + + @Test + void requestTimeoutReachesJnats() { + assertNull(send("&requestTimeout=1234").getException()); + assertNull(send("&requestTimeout=1234").getException()); + assertNull(send("&requestTimeout=1234&jetstreamAsync=false").getException()); + + // one JetStream context per producer, created at the start with the requestTimeout of the endpoint + assertEquals(2, server.jetStreamOptions.size()); + for (JetStreamOptions options : server.jetStreamOptions) { + assertEquals(Duration.ofMillis(1234), options.getRequestTimeout()); + } + assertEquals(2, server.publishedAsync.get()); + assertEquals(1, server.publishedSync.get()); + } + + @Test + void timeoutSaysWhatHappened() { + server.ack = CompletableFuture::new; + + Exchange exchange = send("&requestTimeout=200"); + + Exception e = exchange.getException(); + assertNotNull(e); + assertEquals("No acknowledgement from JetStream for subject orders within 200 ms", e.getMessage()); + assertInstanceOf(TimeoutException.class, e.getCause()); + } + + @Test + void cancelledAcknowledgementSaysWhatHappened() { + // as jnats: the future of the PublishAck is composed on the future of the reply, which jnats cancels when it + // gives up on it + server.ack = () -> { + CompletableFuture<Message> reply = new CompletableFuture<>(); + CompletableFuture<PublishAck> ack = reply.thenCompose(m -> CompletableFuture.completedFuture(null)); + reply.completeExceptionally( + new CancellationException("Future cancelled, response not registered in time, check connection status.")); + return ack; + }; + + Exchange exchange = send("&requestCleanupInterval=1000"); + + Exception e = exchange.getException(); + assertNotNull(e); + assertEquals("No acknowledgement from JetStream for subject orders: Future cancelled, response not registered in" + + " time, check connection status. (with jetstreamAsync=true the NATS client gives up on the" + + " acknowledgement after requestCleanupInterval, 1000 ms, to twice that)", + e.getMessage()); + assertInstanceOf(CancellationException.class, e.getCause()); + } + + @Test + void streamIsCreatedWhenMissing() { + assertNull(send("&jetstreamName=ORDERS").getException()); + + assertEquals(1, server.added.size()); + assertEquals("ORDERS", server.added.get(0).getName()); + assertEquals(List.of("orders"), server.added.get(0).getSubjects()); + } + + @Test + void streamIsNotCreatedWhenItExists() { + server.streamExists = true; + + assertNull(send("&jetstreamName=ORDERS").getException()); + + assertTrue(server.added.isEmpty()); + } + + @Test + void streamIsNotCreatedWhenAnotherStreamTakesInTheSubject() { + server.otherStreams = List.of("ALL_ORDERS"); + + assertNull(send("&jetstreamName=ORDERS").getException()); + + assertTrue(server.added.isEmpty()); + } + + @Test + void producerStartsWhenTheStreamCannotBeChecked() { + server.lookupFailure = new IOException("Timeout or no response waiting for NATS JetStream server"); + + assertNull(send("&jetstreamName=ORDERS").getException()); + + assertTrue(server.added.isEmpty()); + assertEquals(1, server.publishedAsync.get()); + } + + @Test + void noStreamIsLookedUpWithoutJetstreamName() { + assertNull(send("").getException()); + + assertEquals(0, server.lookups.get()); + assertTrue(server.added.isEmpty()); + } + + static final class FakeServer { + final List<JetStreamOptions> jetStreamOptions = new CopyOnWriteArrayList<>(); + final List<StreamConfiguration> added = new CopyOnWriteArrayList<>(); + volatile Supplier<CompletableFuture<PublishAck>> ack = () -> CompletableFuture.completedFuture(publishAck()); + volatile boolean streamExists; + volatile List<String> otherStreams = List.of(); + volatile IOException lookupFailure; + final AtomicInteger lookups = new AtomicInteger(); + final AtomicInteger publishedAsync = new AtomicInteger(); + final AtomicInteger publishedSync = new AtomicInteger(); + + Connection connection() { + JetStreamManagement jsm = proxy(JetStreamManagement.class, (name, args) -> switch (name) { + case "getStreamInfo" -> streamInfo(); + case "getStreamNames" -> otherStreams; + case "addStream" -> { + added.add((StreamConfiguration) args[0]); + yield null; + } + default -> throw new UnsupportedOperationException(name); + }); + JetStream js = proxy(JetStream.class, (name, args) -> switch (name) { + case "publishAsync" -> { + publishedAsync.incrementAndGet(); + yield ack.get(); + } + case "publish" -> { + publishedSync.incrementAndGet(); + yield publishAck(); + } + default -> throw new UnsupportedOperationException(name); + }); + ServerInfo info = new ServerInfo("INFO {\"server_id\":\"fake\",\"jetstream\":true,\"headers\":true}"); + return proxy(Connection.class, (name, args) -> switch (name) { + case "getServerInfo" -> info; + case "jetStreamManagement" -> jsm; + case "jetStream" -> { + jetStreamOptions.add(args.length == 1 ? (JetStreamOptions) args[0] : null); + yield js; + } + case "getStatus" -> Connection.Status.CONNECTED; + default -> null; + }); + } + + private StreamInfo streamInfo() throws IOException, JetStreamApiException { + lookups.incrementAndGet(); + if (lookupFailure != null) { + throw lookupFailure; + } + if (!streamExists) { + // the server's answer as jnats reads it (ApiResponse is abstract) + throw new JetStreamApiException( + new ApiResponse<Void>( + JsonParser.parseUnchecked( + "{\"error\":{\"code\":404,\"err_code\":10059,\"description\":\"stream not found\"}}")) { + }); + } + return new StreamInfo( + JsonParser.parseUnchecked("{\"config\":{\"name\":\"ORDERS\",\"subjects\":[\"orders\"]},\"state\":{}}")); + } + + private static PublishAck publishAck() { + try { + return new PublishAck( + new NatsMessage( + "_INBOX.1", null, "{\"stream\":\"ORDERS\",\"seq\":1}".getBytes(StandardCharsets.UTF_8))); + } catch (IOException | JetStreamApiException e) { + throw new IllegalStateException(e); + } + } + + interface Handler { + Object handle(String name, Object[] args) throws Exception; + } + + @SuppressWarnings("unchecked") + static <T> T proxy(Class<T> type, Handler handler) { + return (T) Proxy.newProxyInstance(FakeServer.class.getClassLoader(), new Class<?>[] { type }, + (p, m, a) -> { + if (m.getDeclaringClass() == Object.class) { + return switch (m.getName()) { + case "hashCode" -> System.identityHashCode(p); + case "equals" -> p == a[0]; + default -> type.getSimpleName() + "@fake"; + }; + } + Object r = handler.handle(m.getName(), a == null ? new Object[0] : a); + if (r == null && m.getReturnType() == boolean.class) { + return false; + } + return r; + }); + } + } +} diff --git a/components/camel-nats/src/test/java/org/apache/camel/component/nats/jetstream/NatsJetstreamProducerIT.java b/components/camel-nats/src/test/java/org/apache/camel/component/nats/jetstream/NatsJetstreamProducerIT.java new file mode 100644 index 000000000000..d4a69cc5380d --- /dev/null +++ b/components/camel-nats/src/test/java/org/apache/camel/component/nats/jetstream/NatsJetstreamProducerIT.java @@ -0,0 +1,162 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.nats.jetstream; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import io.nats.client.Connection; +import io.nats.client.Dispatcher; +import io.nats.client.JetStreamApiException; +import io.nats.client.JetStreamManagement; +import io.nats.client.Nats; +import io.nats.client.api.StreamConfiguration; +import org.apache.camel.Exchange; +import org.apache.camel.component.nats.NatsComponent; +import org.apache.camel.component.nats.integration.NatsITSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Isolated; + +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.junit.jupiter.api.Assertions.assertTrue; + +/** + * The JetStream producer against a NATS server (CAMEL-27198): the requestTimeout reaches jnats, a missing + * acknowledgement is reported clearly, and the stream of jetstreamName is created when it does not exist. + */ +@Isolated +public class NatsJetstreamProducerIT extends NatsITSupport { + + private Connection admin; + private JetStreamManagement jsm; + + @BeforeEach + void connect() throws Exception { + admin = Nats.connect(context.getComponent("nats", NatsComponent.class).getConfiguration().getServers()); + jsm = admin.jetStreamManagement(); + } + + @AfterEach + void close() throws Exception { + for (String name : jsm.getStreamNames()) { + if (name.startsWith("CAMEL27198")) { + jsm.deleteStream(name); + } + } + admin.close(); + } + + /** + * A JetStream publish to a subject that no stream takes in, but that a core NATS subscriber listens to, gets no + * acknowledgement (and no 503 No Responders either). + */ + private void silentSubscriber(String subject) throws Exception { + Dispatcher d = admin.createDispatcher(msg -> { + // never answers + }); + d.subscribe(subject); + admin.flush(Duration.ofSeconds(5)); + } + + private long sendAndTimeMillis(String uri, Exchange[] result) { + long start = System.nanoTime(); + result[0] = template.send(uri, e -> e.getIn().setBody("Hello")); + return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + } + + @Test + void synchronousPublishWaitsRequestTimeout() throws Exception { + silentSubscriber("camel27198.sync"); + Exchange[] result = new Exchange[1]; + + // longer than the connection timeout (2000 ms) that jnats used before + long millis = sendAndTimeMillis("nats:camel27198.sync?jetstreamEnabled=true&jetstreamAsync=false&requestTimeout=3000", + result); + + assertNotNull(result[0].getException()); + assertTrue(millis >= 2900, "waited " + millis + " ms"); + assertTrue(millis < 10000, "waited " + millis + " ms"); + + // and shorter + millis = sendAndTimeMillis("nats:camel27198.sync?jetstreamEnabled=true&jetstreamAsync=false&requestTimeout=500", + result); + + assertNotNull(result[0].getException()); + assertTrue(millis < 1500, "waited " + millis + " ms"); + } + + @Test + void asynchronousTimeoutSaysWhatHappened() throws Exception { + silentSubscriber("camel27198.async"); + Exchange[] result = new Exchange[1]; + + long millis = sendAndTimeMillis("nats:camel27198.async?jetstreamEnabled=true&requestTimeout=500", result); + + Exception e = result[0].getException(); + assertNotNull(e); + assertEquals("No acknowledgement from JetStream for subject camel27198.async within 500 ms", e.getMessage()); + assertTrue(millis < 1500, "waited " + millis + " ms"); + } + + @Test + void asynchronousCancelSaysWhatHappened() throws Exception { + silentSubscriber("camel27198.cancel"); + Exchange[] result = new Exchange[1]; + + // jnats gives up on the acknowledgement after requestCleanupInterval (to twice that), before requestTimeout + long millis = sendAndTimeMillis( + "nats:camel27198.cancel?jetstreamEnabled=true&requestTimeout=20000&requestCleanupInterval=1000", result); + + Exception e = result[0].getException(); + assertNotNull(e); + assertTrue(e.getMessage().startsWith("No acknowledgement from JetStream for subject camel27198.cancel: "), + e.getMessage()); + assertTrue(e.getMessage().contains("requestCleanupInterval, 1000 ms"), e.getMessage()); + assertTrue(millis < 10000, "waited " + millis + " ms"); + } + + @Test + void producerCreatesTheStreamOfJetstreamName() throws Exception { + Exchange exchange = template.send("nats:camel27198.created?jetstreamEnabled=true&jetstreamName=CAMEL27198_CREATED", + e -> e.getIn().setBody("Hello")); + + assertNull(exchange.getException()); + assertEquals(1, jsm.getStreamInfo("CAMEL27198_CREATED").getStreamState().getMsgCount()); + assertEquals(List.of("camel27198.created"), + jsm.getStreamInfo("CAMEL27198_CREATED").getConfiguration().getSubjects()); + } + + @Test + void producerDoesNotCreateAStreamWhenAnotherTakesInTheSubject() throws Exception { + jsm.addStream(StreamConfiguration.builder().name("CAMEL27198_OTHER").subjects("camel27198.other").build()); + + Exchange exchange = template.send("nats:camel27198.other?jetstreamEnabled=true&jetstreamName=CAMEL27198_MISSING", + e -> e.getIn().setBody("Hello")); + + assertNull(exchange.getException()); + assertEquals(1, jsm.getStreamInfo("CAMEL27198_OTHER").getStreamState().getMsgCount()); + JetStreamApiException e + = assertThrows(JetStreamApiException.class, () -> jsm.getStreamInfo("CAMEL27198_MISSING")); + assertEquals(404, e.getErrorCode()); + } +} diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 8e892f5ce65b..7ee420a2f951 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -11291,6 +11291,17 @@ Use certificates that match the hosts, or set the new `hostnameVerification` opt behaviour. An `opentls://` server address still trusts any certificate and is not checked. +=== camel-nats - the JetStream producer creates the stream of jetstreamName and waits requestTimeout + +With `jetstreamEnabled=true`, the producer now creates the stream named by `jetstreamName` at startup, with the subject +of the topic, when this stream does not exist and no other stream takes in the subject. Before, the producer did not +use `jetstreamName`, and each send failed with `503 No Responders Available For Request` when no stream took in the +subject. Remove `jetstreamName` from the producer endpoint to keep the previous behaviour. + +With `jetstreamAsync=false`, the producer now waits `requestTimeout` (20 seconds by default) for the acknowledgement of +JetStream. Before, it waited the connection timeout of the NATS client (`connectionTimeout`, 2 seconds by default). Set +`requestTimeout=2000` to keep the previous wait. + === camel-pulsar - the host name of the broker is verified with pulsar+ssl When the endpoint creates its own Pulsar client, a `pulsar+ssl://` connection now checks that the certificate of the diff --git a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/NatsComponentBuilderFactory.java b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/NatsComponentBuilderFactory.java index 667a6fdb6165..64de9f3ed5f2 100644 --- a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/NatsComponentBuilderFactory.java +++ b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/NatsComponentBuilderFactory.java @@ -135,7 +135,13 @@ public interface NatsComponentBuilderFactory { } /** - * Sets the name of the JetStream stream to use. + * The name of the JetStream stream. The consumer reads from this stream + * (it is required for a JetStream consumer). When the stream does not + * exist, the consumer creates it with the subject of the topic. The + * producer creates it in the same way, unless another stream already + * takes in the subject. The producer publishes to the subject, and the + * message is stored by the stream that takes in the subject, whatever + * its name. * * The option is a: <code>java.lang.String</code> type. * @@ -687,7 +693,11 @@ public interface NatsComponentBuilderFactory { /** - * Request timeout in milliseconds. + * Request timeout in milliseconds. With JetStream, the time to wait for + * the acknowledgement of a published message. With jetstreamAsync=true, + * the NATS client also gives up on the acknowledgement after + * requestCleanupInterval (to twice that), so a longer wait needs a + * longer requestCleanupInterval too. * * The option is a: <code>long</code> type. * diff --git a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NatsEndpointBuilderFactory.java b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NatsEndpointBuilderFactory.java index d800ff6f1786..0d076793c813 100644 --- a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NatsEndpointBuilderFactory.java +++ b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NatsEndpointBuilderFactory.java @@ -164,7 +164,13 @@ public interface NatsEndpointBuilderFactory { return this; } /** - * Sets the name of the JetStream stream to use. + * The name of the JetStream stream. The consumer reads from this stream + * (it is required for a JetStream consumer). When the stream does not + * exist, the consumer creates it with the subject of the topic. The + * producer creates it in the same way, unless another stream already + * takes in the subject. The producer publishes to the subject, and the + * message is stored by the stream that takes in the subject, whatever + * its name. * * The option is a: <code>java.lang.String</code> type. * @@ -1463,7 +1469,13 @@ public interface NatsEndpointBuilderFactory { return this; } /** - * Sets the name of the JetStream stream to use. + * The name of the JetStream stream. The consumer reads from this stream + * (it is required for a JetStream consumer). When the stream does not + * exist, the consumer creates it with the subject of the topic. The + * producer creates it in the same way, unless another stream already + * takes in the subject. The producer publishes to the subject, and the + * message is stored by the stream that takes in the subject, whatever + * its name. * * The option is a: <code>java.lang.String</code> type. * @@ -1818,7 +1830,11 @@ public interface NatsEndpointBuilderFactory { return this; } /** - * Request timeout in milliseconds. + * Request timeout in milliseconds. With JetStream, the time to wait for + * the acknowledgement of a published message. With jetstreamAsync=true, + * the NATS client also gives up on the acknowledgement after + * requestCleanupInterval (to twice that), so a longer wait needs a + * longer requestCleanupInterval too. * * The option is a: <code>long</code> type. * @@ -1833,7 +1849,11 @@ public interface NatsEndpointBuilderFactory { return this; } /** - * Request timeout in milliseconds. + * Request timeout in milliseconds. With JetStream, the time to wait for + * the acknowledgement of a published message. With jetstreamAsync=true, + * the NATS client also gives up on the acknowledgement after + * requestCleanupInterval (to twice that), so a longer wait needs a + * longer requestCleanupInterval too. * * The option will be converted to a <code>long</code> type. * @@ -2277,7 +2297,13 @@ public interface NatsEndpointBuilderFactory { return this; } /** - * Sets the name of the JetStream stream to use. + * The name of the JetStream stream. The consumer reads from this stream + * (it is required for a JetStream consumer). When the stream does not + * exist, the consumer creates it with the subject of the topic. The + * producer creates it in the same way, unless another stream already + * takes in the subject. The producer publishes to the subject, and the + * message is stored by the stream that takes in the subject, whatever + * its name. * * The option is a: <code>java.lang.String</code> type. *
