davsclaus commented on code in PR #26006: URL: https://github.com/apache/camel/pull/26006#discussion_r3905737502
########## components/camel-hivemq/src/main/java/org/apache/camel/component/hivemq/HiveMQEndpoint.java: ########## @@ -0,0 +1,203 @@ +/* + * 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.hivemq; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import com.hivemq.client.mqtt.MqttClient; +import com.hivemq.client.mqtt.MqttClientState; +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient; +import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientBuilder; +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5SimpleAuth; +import com.hivemq.client.mqtt.mqtt5.message.auth.Mqtt5SimpleAuthBuilder; +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.spi.EndpointServiceLocation; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; + +@UriEndpoint(firstVersion = "4.23.0", scheme = "hivemq", title = "HiveMQ", syntax = "hivemq:topic", + category = { Category.MESSAGING, Category.IOT }, headersClass = HiveMQConstants.class) +public class HiveMQEndpoint extends DefaultEndpoint implements EndpointServiceLocation { + + /** + * The MQTT topic name or pattern to subscribe to or publish on. + */ + @UriPath + @Metadata(required = true) + private String topic; + + /** + * The HiveMQ component configuration options. + */ + @UriParam + @Metadata(description = "To use a custom HiveMQConfiguration") + private HiveMQConfiguration configuration; + + private final Map<Mqtt5AsyncClient, AtomicBoolean> reconnectCancellations = new ConcurrentHashMap<>(); + + public HiveMQEndpoint(String uri, HiveMQComponent component, HiveMQConfiguration configuration, String topic) { + super(uri, component); + this.configuration = configuration; + this.topic = topic; + } + + @Override + public Producer createProducer() throws Exception { + return new HiveMQProducer(this); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + HiveMQConsumer consumer = new HiveMQConsumer(this, processor); + configureConsumer(consumer); + return consumer; + } + + public Mqtt5AsyncClient createClient() { + AtomicBoolean cancelReconnect = new AtomicBoolean(); + AtomicReference<Mqtt5AsyncClient> clientRef = new AtomicReference<>(); + Mqtt5ClientBuilder builder = MqttClient.builder() + .serverHost(configuration.getHost()) + .serverPort(configuration.getPort()) + .automaticReconnectWithDefaultConfig() + .addDisconnectedListener(context -> { + // Initial connect() does not complete while auto-reconnect keeps retrying (HiveMQ #302). + // Also honour an explicit stop so DISCONNECTED_RECONNECT / CONNECTING_RECONNECT are cancelled. + if (cancelReconnect.get() || context.getClientConfig().getState() == MqttClientState.CONNECTING) { + context.getReconnector().reconnect(false); + } + }) + .addConnectedListener(context -> { + // HiveMQ schedules reconnect after listeners return; cancelReconnect cannot abort that delay. + // If a reconnect succeeds after Camel stop, disconnect immediately (USER source skips auto-reconnect). + if (cancelReconnect.get()) { + Mqtt5AsyncClient started = clientRef.get(); + if (started != null && started.getState().isConnected()) { + try { + started.disconnect(); + } catch (Exception e) { + // Already disconnecting or not connected + } + } + } + }) + .useMqttVersion5(); + + if (configuration.getClientId() != null) { + builder.identifier(configuration.getClientId()); + } + + if (configuration.isSsl()) { + builder.sslWithDefaultConfig(); Review Comment: Question: SSL is only wired up via `sslWithDefaultConfig()` - there's no integration with Camel's `SSLContextParameters`/JSSE utility for custom trust/key stores or client certs. That's not insecure (no `trustAllCertificates`-style default), just less flexible than most other Camel components with TLS support. Is that intentional scope for this `Preview`-level first cut, with SSLContextParameters support planned as a fast-follow? ########## components/camel-hivemq/src/main/java/org/apache/camel/component/hivemq/HiveMQConsumer.java: ########## @@ -0,0 +1,107 @@ +/* + * 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.hivemq; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient; +import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.support.DefaultConsumer; + +public class HiveMQConsumer extends DefaultConsumer { + + private final HiveMQEndpoint endpoint; + private Mqtt5AsyncClient client; + private ExecutorService executor; + + public HiveMQConsumer(HiveMQEndpoint endpoint, Processor processor) { + super(endpoint, processor); + this.endpoint = endpoint; + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + executor = endpoint.getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, "HiveMQConsumer"); + client = endpoint.createClient(); + endpoint.connect(client); + + client.subscribeWith() + .topicFilter(endpoint.getTopic()) + .qos(endpoint.getConfiguration().getQos()) + .callback(this::onMessage) + .send() + .join(); + } + + @Override + protected void doStop() throws Exception { + if (client != null && client.getState().isConnected()) { + try { + client.unsubscribeWith().topicFilter(endpoint.getTopic()).send() + .orTimeout(5, TimeUnit.SECONDS).join(); + } catch (Exception e) { Review Comment: Minor: this catch block silently swallows the unsubscribe exception. Consider a DEBUG-level log here (and at the similar catch in `HiveMQEndpoint.stopClient`) so a failed best-effort unsubscribe/disconnect isn't completely invisible when diagnosing shutdown issues. Not blocking. ########## components/camel-hivemq/src/test/java/org/apache/camel/component/hivemq/HiveMQConsumerReleaseTest.java: ########## @@ -0,0 +1,126 @@ +/* + * 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.hivemq; + +import java.lang.reflect.Method; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.camel.AsyncCallback; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.support.AsyncProcessorSupport; +import org.apache.camel.support.DefaultExchange; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class HiveMQConsumerReleaseTest { + + private DefaultCamelContext camelContext; + private HiveMQComponent component; + private HiveMQEndpoint endpoint; + + @BeforeEach + void setUp() { + camelContext = new DefaultCamelContext(); + component = new HiveMQComponent(); + component.setCamelContext(camelContext); + endpoint = new HiveMQEndpoint("hivemq:test", component, new HiveMQConfiguration(), "test"); + endpoint.setCamelContext(camelContext); + } + + @AfterEach + void tearDown() { + camelContext.stop(); + } + + @Test + @DisplayName("Synchronous processing releases the exchange exactly once") + void syncProcessingReleasesOnce() throws Exception { + CountingConsumer consumer = new CountingConsumer(endpoint, exchange -> { + }); + + invokeProcessExchange(consumer, new DefaultExchange(camelContext)); + + assertThat(consumer.releases.get()).isEqualTo(1); + } + + @Test + @DisplayName("Asynchronous processing releases the exchange exactly once") + void asyncProcessingReleasesOnce() throws Exception { + CountDownLatch processed = new CountDownLatch(1); + CountingConsumer consumer = new CountingConsumer(endpoint, new AsyncProcessorSupport() { + @Override + public boolean process(Exchange exchange, AsyncCallback callback) { + CompletableFuture.runAsync(() -> { + callback.done(false); + processed.countDown(); + }); + return false; + } + }); + + invokeProcessExchange(consumer, new DefaultExchange(camelContext)); + assertThat(processed.await(5, TimeUnit.SECONDS)).isTrue(); + + assertThat(consumer.releases.get()).isEqualTo(1); + } + + @Test + @DisplayName("Callback plus thrown exception still releases the exchange exactly once") + void callbackThenThrowReleasesOnce() throws Exception { + CountingConsumer consumer = new CountingConsumer(endpoint, new AsyncProcessorSupport() { + @Override + public boolean process(Exchange exchange, AsyncCallback callback) { + callback.done(true); + throw new RuntimeException("after callback"); + } + }); + + invokeProcessExchange(consumer, new DefaultExchange(camelContext)); + + assertThat(consumer.releases.get()).isEqualTo(1); + } + + private static void invokeProcessExchange(HiveMQConsumer consumer, Exchange exchange) throws Exception { Review Comment: Minor nit: using reflection to invoke the private `processExchange` method works but is a bit brittle to refactors. A package-private visibility (test lives in the same package) would let you call it directly without reflection. Not blocking. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
