gnodet-bot commented on code in PR #29489: URL: https://github.com/apache/camel/pull/29489#discussion_r4538567273
########## components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java: ########## @@ -0,0 +1,494 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Thread-safe pool of Azure IoT Hub {@link DeviceClient} instances, keyed by the resolved hub/device/module identity + * derived from the connection string instead of only the raw device id. + * + * <p> + * Clients are created lazily, reused across messages, and evicted after an idle timeout. Connection status changes are + * monitored through the Azure SDK callback, and broken clients are removed by the caller on send failure or disconnect + * as needed. + * </p> + */ +public class DeviceClientPool { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceClientPool.class); + + @FunctionalInterface + public interface DeviceClientFactory { + DeviceClient create(String connectionString, IotHubClientProtocol protocol) throws Exception; + } + + private static final class PooledClient { + final DeviceClient client; + volatile long lastUsed; + final AtomicInteger inUse = new AtomicInteger(); + + PooledClient(DeviceClient client, long nowMillis) { + this.client = client; + this.lastUsed = nowMillis; + } + + void touch(long nowMillis) { + this.lastUsed = nowMillis; + } + + void acquire() { + inUse.incrementAndGet(); + } + + boolean release() { + return inUse.decrementAndGet() == 0; + } + } + + public static final class Lease implements AutoCloseable { + private final DeviceClientPool pool; + private final String poolKey; + private final PooledClient pooled; + private boolean closed; + + private Lease(DeviceClientPool pool, String poolKey, PooledClient pooled) { + this.pool = pool; + this.poolKey = poolKey; + this.pooled = pooled; + } + + public DeviceClient getClient() { + return pooled.client; + } + + public DeviceClient client() { + return pooled.client; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + if (pooled.release()) { + pool.touchAndMaybeEvict(poolKey); + } + } + } + + private final Duration idleTimeout; + private final Duration evictionInterval; + private final Map<String, PooledClient> pool = new ConcurrentHashMap<>(); + private final Map<String, CompletableFuture<DeviceClient>> creationFutures = new ConcurrentHashMap<>(); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + private DeviceClientFactory deviceClientFactory = DeviceClient::new; + private LongSupplier nowMillisSupplier = System::currentTimeMillis; + private ScheduledExecutorService evictionExecutor; + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval) { + this(idleTimeout, evictionInterval, null); + } + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval, ScheduledExecutorService evictionExecutor) { + this.idleTimeout = isPositive(idleTimeout) ? idleTimeout : Duration.ofMinutes(5); + this.evictionInterval = isPositive(evictionInterval) ? evictionInterval : Duration.ofSeconds(30); + this.evictionExecutor = evictionExecutor; + } + + private static boolean isPositive(Duration d) { + return d != null && !d.isZero() && !d.isNegative(); + } + + public void start() { + if (evictionExecutor == null) { + evictionExecutor = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "camel-azure-iothub-device-client-evictor"); + t.setDaemon(true); + return t; + }); + } + evictionExecutor.scheduleAtFixedRate(this::evictIdleClients, + evictionInterval.toMillis(), evictionInterval.toMillis(), TimeUnit.MILLISECONDS); + LOG.info("DeviceClient eviction enabled. idleTimeout={}s, interval={}s", + idleTimeout.getSeconds(), evictionInterval.getSeconds()); + } + + // package-private for test hooks only + DeviceClient getOrCreate(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + PooledClient existing = pool.get(poolKey); + if (existing != null) { + existing.touch(now); + return existing.client; + } + + CompletableFuture<DeviceClient> inFlight = creationFutures.putIfAbsent(poolKey, new CompletableFuture<>()); + if (inFlight == null) { + CompletableFuture<DeviceClient> createdFuture = creationFutures.get(poolKey); + try { + DeviceClient client = createClient(deviceId, connectionString, protocol); + PooledClient pooled = new PooledClient(client, now); + PooledClient previous = pool.putIfAbsent(poolKey, pooled); + if (previous != null) { + client.close(); + previous.touch(now); + createdFuture.complete(previous.client); + return previous.client; + } + createdFuture.complete(client); + return client; + } catch (Exception e) { + createdFuture.completeExceptionally(e); + throw e; + } finally { + creationFutures.remove(poolKey, createdFuture); + } + } + + try { + return inFlight.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for DeviceClient creation for device: " + deviceId, e); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException re) { + throw re; + } + if (cause instanceof Error err) { + throw err; + } + throw new RuntimeException("DeviceClient creation failed for device: " + deviceId, cause); + } + } + + public Lease acquire(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + AtomicReference<PooledClient> evicted = new AtomicReference<>(); + PooledClient existing = pool.computeIfPresent(poolKey, (key, pooled) -> { + if (pooled.inUse.get() > 0) { + pooled.touch(now); + pooled.acquire(); + return pooled; + } + if ((now - pooled.lastUsed) > idleTimeout.toMillis()) { + evicted.set(pooled); + return null; + } + pooled.touch(now); + pooled.acquire(); + return pooled; + }); + if (existing != null) { + return new Lease(this, poolKey, existing); + } + if (evicted.get() != null) { + closeQuietly(poolKey, evicted.get().client, "idle eviction"); + } + + DeviceClient client = getOrCreate(deviceId, connectionString, protocol); + PooledClient pooled = pool.get(poolKey); + if (pooled == null) { + throw new IllegalStateException("DeviceClient not present in pool after creation for device: " + deviceId); + } + if (pooled.client != client) { + throw new IllegalStateException("Pool returned a different client instance for device: " + deviceId); + } + pooled.touch(now); + pooled.acquire(); + return new Lease(this, poolKey, pooled); + } + + public Lease lease(String deviceId, String connectionString, IotHubClientProtocol protocol) { + return acquire(deviceId, connectionString, protocol); + } + + @SuppressWarnings("unused") + void remove(String deviceId, String connectionString) { + String poolKey = resolvePoolKey(deviceId, connectionString); + PooledClient pooled = pool.remove(poolKey); + if (pooled != null) { + closeQuietly(deviceId, pooled.client, "explicit removal"); + } + } + + @SuppressWarnings({ "unused", "ConstantConditions", "ConstantValue" }) + void remove(String deviceId) { + if (deviceId == null || deviceId.isBlank()) { + return; + } + + PooledClient pooled = pool.remove(deviceId); + if (pooled != null) { + closeQuietly(deviceId, pooled.client, "explicit removal"); + return; + } + + for (Map.Entry<String, PooledClient> entry : pool.entrySet()) { + String key = entry.getKey(); + if (matchesDeviceId(key, deviceId)) { + if (pool.remove(key, entry.getValue())) { + closeQuietly(deviceId, entry.getValue().client, "explicit removal"); + return; + } + } + } + } + + private static boolean matchesDeviceId(String poolKey, String deviceId) { + if (poolKey == null) { + return false; + } + if (poolKey.equals(deviceId)) { + return true; + } + String[] parts = poolKey.split(":"); + return parts.length >= 2 && parts[1].equals(deviceId); + } + + private static String resolvePoolKey(String deviceId, String connectionString) { + if (deviceId == null || deviceId.isBlank()) { + return connectionString; + } + String[] items = connectionString == null ? new String[0] : connectionString.split(";"); + String hostName = null; + String csDeviceId = null; + String moduleId = null; + for (String item : items) { + if (item == null || item.isBlank()) { + continue; + } + int eq = item.indexOf('='); + if (eq <= 0) { + continue; + } + String key = item.substring(0, eq).trim(); + String value = item.substring(eq + 1).trim(); + switch (key) { + case "HostName" -> hostName = value; + case "DeviceId" -> csDeviceId = value; + case "ModuleId" -> moduleId = value; + default -> { + // ignore other connection-string fields + } + } + } + if (csDeviceId != null && !csDeviceId.equals(deviceId)) { + throw new IllegalArgumentException( + "Device id '" + deviceId + "' does not match the connection string's DeviceId '" + csDeviceId + "'"); + } + StringBuilder identity = new StringBuilder(); + if (hostName != null && !hostName.isBlank()) { + identity.append(hostName); + } + if (csDeviceId != null && !csDeviceId.isBlank()) { + if (!identity.isEmpty()) { + identity.append(':'); + } + identity.append(csDeviceId); + } + if (moduleId != null && !moduleId.isBlank()) { + if (!identity.isEmpty()) { + identity.append(':'); + } + identity.append(moduleId); + } + return !identity.isEmpty() ? identity.toString() : deviceId; + } + + private DeviceClient createClient(String deviceId, String connectionString, IotHubClientProtocol protocol) { + try { + DeviceClient client = deviceClientFactory.create(connectionString, protocol); + client.open(true); + try { + // Avoid duplicate desired-property subscriptions: subscribe only if not already subscribed. + // The Azure DeviceClient does not expose a way to check, so we rely on only subscribing once per client creation. + client.subscribeToDesiredProperties((twinUpdate, ctx) -> { + }, null); + client.setConnectionStatusChangeCallback(context -> { + if (context == null) { + return; + } + if (context.getNewStatus() + == IotHubConnectionStatus.DISCONNECTED) { + evictDisconnectedClient(deviceId, connectionString, client, context); + } + }, null); + } catch (Exception e) { + closeQuietly(deviceId, client, "subscription setup"); + throw e; + } + LOG.debug("Created new DeviceClient for device: {}", deviceId); + return client; + } catch (Exception e) { + if (isShutdownInterruption(e)) { + Thread.currentThread().interrupt(); + LOG.warn("DeviceClient creation interrupted due to shutdown for device: {}", deviceId); + throw new IllegalStateException("DeviceClient creation interrupted for device: " + deviceId, e); + } + throw new RuntimeException("DeviceClient creation failed for device: " + deviceId, e); + } + } + + private void evictDisconnectedClient( + String deviceId, String connectionString, DeviceClient client, + ConnectionStatusChangeContext context) { + if (context == null || shuttingDown.get()) { + return; + } + if (context.getNewStatus() != IotHubConnectionStatus.DISCONNECTED) { + return; + } + if (context.getNewStatusReason() == IotHubConnectionStatusChangeReason.CLIENT_CLOSE) { + return; + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + PooledClient pooled = pool.get(poolKey); + if (pooled != null && pooled.inUse.get() == 0 && pooled.client == client && pool.remove(poolKey, pooled)) { Review Comment: 🚨 **Two overlapping defects in `evictDisconnectedClient`** **Defect A — `inUse` check not part of the CAS.** ```java if (pooled != null && pooled.inUse.get() == 0 && pooled.client == client && pool.remove(poolKey, pooled)) { ``` `pooled.inUse.get() == 0` is checked before `pool.remove(poolKey, pooled)`. Between the two, `acquire()` can increment `inUse`. `pool.remove` succeeds (same object identity), and `closeQuietly` runs on a client with an active lease. The lease holder gets a closed-client exception on the next send. **Defect B — broken client stays in pool indefinitely when `inUse > 0`.** When the callback fires while a lease is held, eviction is skipped entirely. When the lease is released, `Lease.close()` calls `touchAndMaybeEvict`, which only evicts on idle timeout. Under steady traffic every `acquire()` refreshes `lastUsed`, so the broken client is never removed. Every subsequent send fails. The `retired` flag approach davsclaus outlined in his re-review addresses both atomically: mark-removed inside `computeIfPresent` (atomic with `acquire()`), defer `close()` to the last lease release. ########## components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java: ########## @@ -0,0 +1,494 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Thread-safe pool of Azure IoT Hub {@link DeviceClient} instances, keyed by the resolved hub/device/module identity + * derived from the connection string instead of only the raw device id. + * + * <p> + * Clients are created lazily, reused across messages, and evicted after an idle timeout. Connection status changes are + * monitored through the Azure SDK callback, and broken clients are removed by the caller on send failure or disconnect + * as needed. + * </p> + */ +public class DeviceClientPool { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceClientPool.class); + + @FunctionalInterface + public interface DeviceClientFactory { + DeviceClient create(String connectionString, IotHubClientProtocol protocol) throws Exception; + } + + private static final class PooledClient { + final DeviceClient client; + volatile long lastUsed; + final AtomicInteger inUse = new AtomicInteger(); + + PooledClient(DeviceClient client, long nowMillis) { + this.client = client; + this.lastUsed = nowMillis; + } + + void touch(long nowMillis) { + this.lastUsed = nowMillis; + } + + void acquire() { + inUse.incrementAndGet(); + } + + boolean release() { + return inUse.decrementAndGet() == 0; + } + } + + public static final class Lease implements AutoCloseable { + private final DeviceClientPool pool; + private final String poolKey; + private final PooledClient pooled; + private boolean closed; + + private Lease(DeviceClientPool pool, String poolKey, PooledClient pooled) { + this.pool = pool; + this.poolKey = poolKey; + this.pooled = pooled; + } + + public DeviceClient getClient() { + return pooled.client; + } + + public DeviceClient client() { + return pooled.client; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + if (pooled.release()) { + pool.touchAndMaybeEvict(poolKey); + } + } + } + + private final Duration idleTimeout; + private final Duration evictionInterval; + private final Map<String, PooledClient> pool = new ConcurrentHashMap<>(); + private final Map<String, CompletableFuture<DeviceClient>> creationFutures = new ConcurrentHashMap<>(); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + private DeviceClientFactory deviceClientFactory = DeviceClient::new; + private LongSupplier nowMillisSupplier = System::currentTimeMillis; + private ScheduledExecutorService evictionExecutor; + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval) { + this(idleTimeout, evictionInterval, null); + } + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval, ScheduledExecutorService evictionExecutor) { + this.idleTimeout = isPositive(idleTimeout) ? idleTimeout : Duration.ofMinutes(5); + this.evictionInterval = isPositive(evictionInterval) ? evictionInterval : Duration.ofSeconds(30); + this.evictionExecutor = evictionExecutor; + } + + private static boolean isPositive(Duration d) { + return d != null && !d.isZero() && !d.isNegative(); + } + + public void start() { + if (evictionExecutor == null) { + evictionExecutor = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "camel-azure-iothub-device-client-evictor"); + t.setDaemon(true); + return t; + }); + } + evictionExecutor.scheduleAtFixedRate(this::evictIdleClients, + evictionInterval.toMillis(), evictionInterval.toMillis(), TimeUnit.MILLISECONDS); + LOG.info("DeviceClient eviction enabled. idleTimeout={}s, interval={}s", + idleTimeout.getSeconds(), evictionInterval.getSeconds()); + } + + // package-private for test hooks only + DeviceClient getOrCreate(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + PooledClient existing = pool.get(poolKey); + if (existing != null) { + existing.touch(now); + return existing.client; + } + + CompletableFuture<DeviceClient> inFlight = creationFutures.putIfAbsent(poolKey, new CompletableFuture<>()); + if (inFlight == null) { + CompletableFuture<DeviceClient> createdFuture = creationFutures.get(poolKey); + try { + DeviceClient client = createClient(deviceId, connectionString, protocol); + PooledClient pooled = new PooledClient(client, now); + PooledClient previous = pool.putIfAbsent(poolKey, pooled); + if (previous != null) { + client.close(); + previous.touch(now); + createdFuture.complete(previous.client); + return previous.client; + } + createdFuture.complete(client); + return client; + } catch (Exception e) { Review Comment: ⚠️ **`Error` not caught — waiters on `inFlight.get()` hang indefinitely** If `createClient()` throws an `Error` (`NoClassDefFoundError`, `OutOfMemoryError`), `catch (Exception)` does not fire. The future is removed in `finally` but never completed. Any thread already blocked on `inFlight.get()` (line 191) waits forever — there is no timeout. ```suggestion } catch (Exception e) { createdFuture.completeExceptionally(e); throw e; } catch (Throwable t) { createdFuture.completeExceptionally(t); throw t; } finally { ``` ########## components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java: ########## @@ -0,0 +1,494 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Thread-safe pool of Azure IoT Hub {@link DeviceClient} instances, keyed by the resolved hub/device/module identity + * derived from the connection string instead of only the raw device id. + * + * <p> + * Clients are created lazily, reused across messages, and evicted after an idle timeout. Connection status changes are + * monitored through the Azure SDK callback, and broken clients are removed by the caller on send failure or disconnect + * as needed. + * </p> + */ +public class DeviceClientPool { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceClientPool.class); + + @FunctionalInterface + public interface DeviceClientFactory { + DeviceClient create(String connectionString, IotHubClientProtocol protocol) throws Exception; + } + + private static final class PooledClient { + final DeviceClient client; + volatile long lastUsed; + final AtomicInteger inUse = new AtomicInteger(); + + PooledClient(DeviceClient client, long nowMillis) { + this.client = client; + this.lastUsed = nowMillis; + } + + void touch(long nowMillis) { + this.lastUsed = nowMillis; + } + + void acquire() { + inUse.incrementAndGet(); + } + + boolean release() { + return inUse.decrementAndGet() == 0; + } + } + + public static final class Lease implements AutoCloseable { + private final DeviceClientPool pool; + private final String poolKey; + private final PooledClient pooled; + private boolean closed; + + private Lease(DeviceClientPool pool, String poolKey, PooledClient pooled) { + this.pool = pool; + this.poolKey = poolKey; + this.pooled = pooled; + } + + public DeviceClient getClient() { + return pooled.client; + } + + public DeviceClient client() { + return pooled.client; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + if (pooled.release()) { + pool.touchAndMaybeEvict(poolKey); + } + } + } + + private final Duration idleTimeout; + private final Duration evictionInterval; + private final Map<String, PooledClient> pool = new ConcurrentHashMap<>(); + private final Map<String, CompletableFuture<DeviceClient>> creationFutures = new ConcurrentHashMap<>(); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + private DeviceClientFactory deviceClientFactory = DeviceClient::new; + private LongSupplier nowMillisSupplier = System::currentTimeMillis; + private ScheduledExecutorService evictionExecutor; + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval) { + this(idleTimeout, evictionInterval, null); + } + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval, ScheduledExecutorService evictionExecutor) { + this.idleTimeout = isPositive(idleTimeout) ? idleTimeout : Duration.ofMinutes(5); + this.evictionInterval = isPositive(evictionInterval) ? evictionInterval : Duration.ofSeconds(30); + this.evictionExecutor = evictionExecutor; + } + + private static boolean isPositive(Duration d) { + return d != null && !d.isZero() && !d.isNegative(); + } + + public void start() { + if (evictionExecutor == null) { + evictionExecutor = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "camel-azure-iothub-device-client-evictor"); + t.setDaemon(true); + return t; + }); + } + evictionExecutor.scheduleAtFixedRate(this::evictIdleClients, + evictionInterval.toMillis(), evictionInterval.toMillis(), TimeUnit.MILLISECONDS); + LOG.info("DeviceClient eviction enabled. idleTimeout={}s, interval={}s", + idleTimeout.getSeconds(), evictionInterval.getSeconds()); + } + + // package-private for test hooks only + DeviceClient getOrCreate(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + PooledClient existing = pool.get(poolKey); + if (existing != null) { + existing.touch(now); + return existing.client; + } + + CompletableFuture<DeviceClient> inFlight = creationFutures.putIfAbsent(poolKey, new CompletableFuture<>()); + if (inFlight == null) { + CompletableFuture<DeviceClient> createdFuture = creationFutures.get(poolKey); + try { + DeviceClient client = createClient(deviceId, connectionString, protocol); + PooledClient pooled = new PooledClient(client, now); + PooledClient previous = pool.putIfAbsent(poolKey, pooled); + if (previous != null) { + client.close(); + previous.touch(now); + createdFuture.complete(previous.client); + return previous.client; + } + createdFuture.complete(client); + return client; + } catch (Exception e) { + createdFuture.completeExceptionally(e); + throw e; + } finally { + creationFutures.remove(poolKey, createdFuture); + } + } + + try { + return inFlight.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for DeviceClient creation for device: " + deviceId, e); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException re) { + throw re; + } + if (cause instanceof Error err) { + throw err; + } + throw new RuntimeException("DeviceClient creation failed for device: " + deviceId, cause); + } + } + + public Lease acquire(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + AtomicReference<PooledClient> evicted = new AtomicReference<>(); + PooledClient existing = pool.computeIfPresent(poolKey, (key, pooled) -> { + if (pooled.inUse.get() > 0) { + pooled.touch(now); + pooled.acquire(); + return pooled; + } + if ((now - pooled.lastUsed) > idleTimeout.toMillis()) { + evicted.set(pooled); + return null; + } + pooled.touch(now); + pooled.acquire(); + return pooled; + }); + if (existing != null) { + return new Lease(this, poolKey, existing); + } + if (evicted.get() != null) { + closeQuietly(poolKey, evicted.get().client, "idle eviction"); + } + + DeviceClient client = getOrCreate(deviceId, connectionString, protocol); + PooledClient pooled = pool.get(poolKey); + if (pooled == null) { + throw new IllegalStateException("DeviceClient not present in pool after creation for device: " + deviceId); + } + if (pooled.client != client) { + throw new IllegalStateException("Pool returned a different client instance for device: " + deviceId); + } + pooled.touch(now); + pooled.acquire(); + return new Lease(this, poolKey, pooled); + } + + public Lease lease(String deviceId, String connectionString, IotHubClientProtocol protocol) { + return acquire(deviceId, connectionString, protocol); + } + + @SuppressWarnings("unused") + void remove(String deviceId, String connectionString) { + String poolKey = resolvePoolKey(deviceId, connectionString); + PooledClient pooled = pool.remove(poolKey); + if (pooled != null) { + closeQuietly(deviceId, pooled.client, "explicit removal"); + } + } + + @SuppressWarnings({ "unused", "ConstantConditions", "ConstantValue" }) + void remove(String deviceId) { + if (deviceId == null || deviceId.isBlank()) { + return; + } + + PooledClient pooled = pool.remove(deviceId); + if (pooled != null) { + closeQuietly(deviceId, pooled.client, "explicit removal"); + return; + } + + for (Map.Entry<String, PooledClient> entry : pool.entrySet()) { + String key = entry.getKey(); + if (matchesDeviceId(key, deviceId)) { + if (pool.remove(key, entry.getValue())) { + closeQuietly(deviceId, entry.getValue().client, "explicit removal"); + return; + } + } + } + } + + private static boolean matchesDeviceId(String poolKey, String deviceId) { + if (poolKey == null) { + return false; + } + if (poolKey.equals(deviceId)) { + return true; + } + String[] parts = poolKey.split(":"); + return parts.length >= 2 && parts[1].equals(deviceId); + } + + private static String resolvePoolKey(String deviceId, String connectionString) { + if (deviceId == null || deviceId.isBlank()) { + return connectionString; + } + String[] items = connectionString == null ? new String[0] : connectionString.split(";"); + String hostName = null; + String csDeviceId = null; + String moduleId = null; + for (String item : items) { + if (item == null || item.isBlank()) { + continue; + } + int eq = item.indexOf('='); + if (eq <= 0) { + continue; + } + String key = item.substring(0, eq).trim(); + String value = item.substring(eq + 1).trim(); + switch (key) { + case "HostName" -> hostName = value; + case "DeviceId" -> csDeviceId = value; + case "ModuleId" -> moduleId = value; + default -> { + // ignore other connection-string fields + } + } + } + if (csDeviceId != null && !csDeviceId.equals(deviceId)) { + throw new IllegalArgumentException( + "Device id '" + deviceId + "' does not match the connection string's DeviceId '" + csDeviceId + "'"); + } + StringBuilder identity = new StringBuilder(); + if (hostName != null && !hostName.isBlank()) { + identity.append(hostName); + } + if (csDeviceId != null && !csDeviceId.isBlank()) { + if (!identity.isEmpty()) { + identity.append(':'); + } + identity.append(csDeviceId); + } + if (moduleId != null && !moduleId.isBlank()) { + if (!identity.isEmpty()) { + identity.append(':'); + } + identity.append(moduleId); + } + return !identity.isEmpty() ? identity.toString() : deviceId; + } + + private DeviceClient createClient(String deviceId, String connectionString, IotHubClientProtocol protocol) { + try { + DeviceClient client = deviceClientFactory.create(connectionString, protocol); + client.open(true); + try { + // Avoid duplicate desired-property subscriptions: subscribe only if not already subscribed. + // The Azure DeviceClient does not expose a way to check, so we rely on only subscribing once per client creation. + client.subscribeToDesiredProperties((twinUpdate, ctx) -> { + }, null); + client.setConnectionStatusChangeCallback(context -> { + if (context == null) { + return; + } + if (context.getNewStatus() + == IotHubConnectionStatus.DISCONNECTED) { + evictDisconnectedClient(deviceId, connectionString, client, context); + } + }, null); + } catch (Exception e) { + closeQuietly(deviceId, client, "subscription setup"); + throw e; + } + LOG.debug("Created new DeviceClient for device: {}", deviceId); + return client; + } catch (Exception e) { + if (isShutdownInterruption(e)) { + Thread.currentThread().interrupt(); + LOG.warn("DeviceClient creation interrupted due to shutdown for device: {}", deviceId); + throw new IllegalStateException("DeviceClient creation interrupted for device: " + deviceId, e); + } + throw new RuntimeException("DeviceClient creation failed for device: " + deviceId, e); + } + } + + private void evictDisconnectedClient( + String deviceId, String connectionString, DeviceClient client, + ConnectionStatusChangeContext context) { + if (context == null || shuttingDown.get()) { + return; + } + if (context.getNewStatus() != IotHubConnectionStatus.DISCONNECTED) { + return; + } + if (context.getNewStatusReason() == IotHubConnectionStatusChangeReason.CLIENT_CLOSE) { + return; + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + PooledClient pooled = pool.get(poolKey); + if (pooled != null && pooled.inUse.get() == 0 && pooled.client == client && pool.remove(poolKey, pooled)) { + LOG.warn("Evicted DeviceClient for device {} after disconnect. previousStatus={}, reason={}, cause={}", + deviceId, context.getPreviousStatus(), context.getNewStatusReason(), context.getCause()); + closeQuietly(deviceId, client, "connection status changed to DISCONNECTED"); + } + } + + private void touchAndMaybeEvict(String poolKey) { + long now = nowMillisSupplier.getAsLong(); + AtomicReference<PooledClient> evicted = new AtomicReference<>(); + pool.computeIfPresent(poolKey, (key, current) -> { + if (current.inUse.get() > 0) { + current.touch(now); + return current; + } + if ((now - current.lastUsed) > idleTimeout.toMillis()) { + evicted.set(current); + return null; + } + current.touch(now); + return current; + }); + if (evicted.get() != null) { + closeQuietly(poolKey, evicted.get().client, "idle eviction"); + } + } + + private void evictIdleClients() { + if (shuttingDown.get()) { + return; + } + long now = nowMillisSupplier.getAsLong(); + for (Map.Entry<String, PooledClient> entry : pool.entrySet()) { + String key = entry.getKey(); + AtomicReference<PooledClient> evicted = new AtomicReference<>(); + pool.computeIfPresent(key, (k, current) -> { + if (current.inUse.get() > 0) { + return current; + } + if ((now - current.lastUsed) > idleTimeout.toMillis()) { + evicted.set(current); + return null; + } + return current; + }); + if (evicted.get() != null) { + closeQuietly(key, evicted.get().client, "idle eviction"); + } + } + } + + public int getActiveClientCount() { + return pool.size(); + } + + public void shutdown() { + if (!shuttingDown.compareAndSet(false, true)) { + return; + } + if (evictionExecutor != null) { + evictionExecutor.shutdownNow(); + } + for (Map.Entry<String, PooledClient> entry : pool.entrySet()) { + closeQuietly(entry.getKey(), entry.getValue() == null ? null : entry.getValue().client, "shutdown"); + } + pool.clear(); Review Comment: ⚠️ **`shutdown()` race: client opened while `pool.clear()` runs is orphaned** `getOrCreate()` checks `shuttingDown.get()` on entry. If `shutdown()` sets `shuttingDown`, iterates the pool entries, and calls `pool.clear()` while `open(true)` is still in progress on another thread, the creator will subsequently call `pool.putIfAbsent(poolKey, pooled)` — inserting a live, open client into the now-cleared map. Nothing will ever close it. Fix: after `pool.putIfAbsent`, re-check `shuttingDown.get()` and, if set, remove the entry atomically and close the client. ########## components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java: ########## @@ -0,0 +1,494 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Thread-safe pool of Azure IoT Hub {@link DeviceClient} instances, keyed by the resolved hub/device/module identity + * derived from the connection string instead of only the raw device id. + * + * <p> + * Clients are created lazily, reused across messages, and evicted after an idle timeout. Connection status changes are + * monitored through the Azure SDK callback, and broken clients are removed by the caller on send failure or disconnect + * as needed. Review Comment: 💡 **Inaccurate Javadoc** *"broken clients are removed by the caller on send failure or disconnect as needed"* — with the current `inUse > 0` guard in `evictDisconnectedClient`, broken clients are NOT removed when a lease is active at the time of disconnect. Update this once the disconnect-eviction design is finalised. ########## components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java: ########## @@ -0,0 +1,273 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeCallback; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +class DeviceClientPoolTest { + + private static final String CS = "HostName=h;DeviceId=d;SharedAccessKey=k"; + + @Test + void testLeaseInUseIsReusedAndReleased() throws Exception { + DeviceClient client = mock(DeviceClient.class); + DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5), Duration.ofSeconds(30)); + pool.setDeviceClientFactory((cs, protocol) -> client); + + try (DeviceClientPool.Lease first = pool.lease("d", CS, IotHubClientProtocol.MQTT)) { + assertSame(client, first.getClient()); + assertEquals(1, pool.getActiveClientCount()); + + try (DeviceClientPool.Lease second = pool.lease("d", CS, IotHubClientProtocol.MQTT)) { + assertSame(client, second.getClient()); + assertEquals(1, pool.getActiveClientCount()); + } + } + + assertEquals(1, pool.getActiveClientCount()); + } + + @Test + void testConcurrentFirstAcquireCreatesSingleClient() throws Exception { + DeviceClient client = mock(DeviceClient.class); + AtomicInteger created = new AtomicInteger(); + CountDownLatch factoryStarted = new CountDownLatch(1); + CountDownLatch releaseFactory = new CountDownLatch(1); + DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5), Duration.ofSeconds(30)); + pool.setDeviceClientFactory((cs, protocol) -> { + created.incrementAndGet(); + factoryStarted.countDown(); + try { + assertTrue(releaseFactory.await(5, TimeUnit.SECONDS), "factory should be released after both tasks start"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + return client; + }); + + ExecutorService executor = Executors.newFixedThreadPool(2); + List<DeviceClientPool.Lease> leases = new ArrayList<>(); + List<java.util.concurrent.Future<?>> futures = new ArrayList<>(); Review Comment: 🚨 **FQCN will break CI** `java.util.concurrent.Future<?>` is used as a FQCN here (and at line 110) but `Future` is not imported. OpenRewrite shortens FQCNs during the build and leaves an uncommitted modification; the CI diff check then fails. Please add `import java.util.concurrent.Future;` to the import block. ```suggestion List<Future<?>> futures = new ArrayList<>(); ``` ########## components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java: ########## @@ -0,0 +1,273 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeCallback; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +class DeviceClientPoolTest { + + private static final String CS = "HostName=h;DeviceId=d;SharedAccessKey=k"; + + @Test + void testLeaseInUseIsReusedAndReleased() throws Exception { + DeviceClient client = mock(DeviceClient.class); + DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5), Duration.ofSeconds(30)); + pool.setDeviceClientFactory((cs, protocol) -> client); + + try (DeviceClientPool.Lease first = pool.lease("d", CS, IotHubClientProtocol.MQTT)) { + assertSame(client, first.getClient()); + assertEquals(1, pool.getActiveClientCount()); + + try (DeviceClientPool.Lease second = pool.lease("d", CS, IotHubClientProtocol.MQTT)) { + assertSame(client, second.getClient()); + assertEquals(1, pool.getActiveClientCount()); + } + } + + assertEquals(1, pool.getActiveClientCount()); + } + + @Test + void testConcurrentFirstAcquireCreatesSingleClient() throws Exception { + DeviceClient client = mock(DeviceClient.class); + AtomicInteger created = new AtomicInteger(); + CountDownLatch factoryStarted = new CountDownLatch(1); + CountDownLatch releaseFactory = new CountDownLatch(1); + DeviceClientPool pool = new DeviceClientPool(Duration.ofMinutes(5), Duration.ofSeconds(30)); + pool.setDeviceClientFactory((cs, protocol) -> { + created.incrementAndGet(); + factoryStarted.countDown(); + try { + assertTrue(releaseFactory.await(5, TimeUnit.SECONDS), "factory should be released after both tasks start"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + return client; + }); + + ExecutorService executor = Executors.newFixedThreadPool(2); + List<DeviceClientPool.Lease> leases = new ArrayList<>(); + List<java.util.concurrent.Future<?>> futures = new ArrayList<>(); + + for (int i = 0; i < 2; i++) { + futures.add(executor.submit(() -> { + DeviceClientPool.Lease lease = pool.lease("d", CS, IotHubClientProtocol.MQTT); + synchronized (leases) { + leases.add(lease); + } + return null; + })); + } + + assertTrue(factoryStarted.await(5, TimeUnit.SECONDS), "one thread should open the first client"); + releaseFactory.countDown(); + executor.shutdown(); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS), "worker tasks did not finish"); + for (java.util.concurrent.Future<?> future : futures) { Review Comment: Same FQCN issue as line 94. ```suggestion for (Future<?> future : futures) { ``` ########## components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java: ########## @@ -0,0 +1,494 @@ +/* + * 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.azure.iothub.client; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +import com.microsoft.azure.sdk.iot.device.ConnectionStatusChangeContext; +import com.microsoft.azure.sdk.iot.device.DeviceClient; +import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; +import com.microsoft.azure.sdk.iot.device.IotHubConnectionStatusChangeReason; +import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Thread-safe pool of Azure IoT Hub {@link DeviceClient} instances, keyed by the resolved hub/device/module identity + * derived from the connection string instead of only the raw device id. + * + * <p> + * Clients are created lazily, reused across messages, and evicted after an idle timeout. Connection status changes are + * monitored through the Azure SDK callback, and broken clients are removed by the caller on send failure or disconnect + * as needed. + * </p> + */ +public class DeviceClientPool { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceClientPool.class); + + @FunctionalInterface + public interface DeviceClientFactory { + DeviceClient create(String connectionString, IotHubClientProtocol protocol) throws Exception; + } + + private static final class PooledClient { + final DeviceClient client; + volatile long lastUsed; + final AtomicInteger inUse = new AtomicInteger(); + + PooledClient(DeviceClient client, long nowMillis) { + this.client = client; + this.lastUsed = nowMillis; + } + + void touch(long nowMillis) { + this.lastUsed = nowMillis; + } + + void acquire() { + inUse.incrementAndGet(); + } + + boolean release() { + return inUse.decrementAndGet() == 0; + } + } + + public static final class Lease implements AutoCloseable { + private final DeviceClientPool pool; + private final String poolKey; + private final PooledClient pooled; + private boolean closed; + + private Lease(DeviceClientPool pool, String poolKey, PooledClient pooled) { + this.pool = pool; + this.poolKey = poolKey; + this.pooled = pooled; + } + + public DeviceClient getClient() { + return pooled.client; + } + + public DeviceClient client() { + return pooled.client; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + if (pooled.release()) { + pool.touchAndMaybeEvict(poolKey); + } + } + } + + private final Duration idleTimeout; + private final Duration evictionInterval; + private final Map<String, PooledClient> pool = new ConcurrentHashMap<>(); + private final Map<String, CompletableFuture<DeviceClient>> creationFutures = new ConcurrentHashMap<>(); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + private DeviceClientFactory deviceClientFactory = DeviceClient::new; + private LongSupplier nowMillisSupplier = System::currentTimeMillis; + private ScheduledExecutorService evictionExecutor; + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval) { + this(idleTimeout, evictionInterval, null); + } + + public DeviceClientPool(Duration idleTimeout, Duration evictionInterval, ScheduledExecutorService evictionExecutor) { + this.idleTimeout = isPositive(idleTimeout) ? idleTimeout : Duration.ofMinutes(5); + this.evictionInterval = isPositive(evictionInterval) ? evictionInterval : Duration.ofSeconds(30); + this.evictionExecutor = evictionExecutor; + } + + private static boolean isPositive(Duration d) { + return d != null && !d.isZero() && !d.isNegative(); + } + + public void start() { + if (evictionExecutor == null) { + evictionExecutor = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "camel-azure-iothub-device-client-evictor"); + t.setDaemon(true); + return t; + }); + } + evictionExecutor.scheduleAtFixedRate(this::evictIdleClients, + evictionInterval.toMillis(), evictionInterval.toMillis(), TimeUnit.MILLISECONDS); + LOG.info("DeviceClient eviction enabled. idleTimeout={}s, interval={}s", + idleTimeout.getSeconds(), evictionInterval.getSeconds()); + } + + // package-private for test hooks only + DeviceClient getOrCreate(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + PooledClient existing = pool.get(poolKey); + if (existing != null) { + existing.touch(now); + return existing.client; + } + + CompletableFuture<DeviceClient> inFlight = creationFutures.putIfAbsent(poolKey, new CompletableFuture<>()); + if (inFlight == null) { + CompletableFuture<DeviceClient> createdFuture = creationFutures.get(poolKey); + try { + DeviceClient client = createClient(deviceId, connectionString, protocol); + PooledClient pooled = new PooledClient(client, now); + PooledClient previous = pool.putIfAbsent(poolKey, pooled); + if (previous != null) { + client.close(); + previous.touch(now); + createdFuture.complete(previous.client); + return previous.client; + } + createdFuture.complete(client); + return client; + } catch (Exception e) { + createdFuture.completeExceptionally(e); + throw e; + } finally { + creationFutures.remove(poolKey, createdFuture); + } + } + + try { + return inFlight.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for DeviceClient creation for device: " + deviceId, e); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException re) { + throw re; + } + if (cause instanceof Error err) { + throw err; + } + throw new RuntimeException("DeviceClient creation failed for device: " + deviceId, cause); + } + } + + public Lease acquire(String deviceId, String connectionString, IotHubClientProtocol protocol) { + if (Thread.currentThread().isInterrupted() || shuttingDown.get()) { + throw new IllegalStateException("Skipping client creation due to shutdown: " + deviceId); + } + + String poolKey = resolvePoolKey(deviceId, connectionString); + final long now = nowMillisSupplier.getAsLong(); + + AtomicReference<PooledClient> evicted = new AtomicReference<>(); + PooledClient existing = pool.computeIfPresent(poolKey, (key, pooled) -> { + if (pooled.inUse.get() > 0) { + pooled.touch(now); + pooled.acquire(); + return pooled; + } + if ((now - pooled.lastUsed) > idleTimeout.toMillis()) { + evicted.set(pooled); + return null; + } + pooled.touch(now); + pooled.acquire(); + return pooled; + }); + if (existing != null) { + return new Lease(this, poolKey, existing); + } + if (evicted.get() != null) { + closeQuietly(poolKey, evicted.get().client, "idle eviction"); + } + + DeviceClient client = getOrCreate(deviceId, connectionString, protocol); + PooledClient pooled = pool.get(poolKey); + if (pooled == null) { + throw new IllegalStateException("DeviceClient not present in pool after creation for device: " + deviceId); + } + if (pooled.client != client) { + throw new IllegalStateException("Pool returned a different client instance for device: " + deviceId); + } + pooled.touch(now); + pooled.acquire(); + return new Lease(this, poolKey, pooled); Review Comment: ⚠️ **Acquire slow path: `pool.get(poolKey)` after `getOrCreate()` is not atomic** Between `getOrCreate()` returning (line 237) and `pool.get(poolKey)` (line 238), `evictDisconnectedClient` can call `pool.remove(poolKey, pooled)`. `pool.get` returns `null`, and the exchange fails with `IllegalStateException` where a retry would be correct. This is the race I flagged in my previous review (open thread `PRRT_kwDOAAMl7c62JZe7...`), confirmed by davsclaus in his re-review (finding #2). It has not been addressed in the committed code. The fix: use `computeIfPresent` to atomically acquire the client from the pool, or retry the entire `acquire()` when the slot disappears after `getOrCreate()` completes. -- 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]
