gnodet-bot commented on code in PR #29489: URL: https://github.com/apache/camel/pull/29489#discussion_r4537299604
########## 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: ⚠️ **Race between `pool.get(poolKey)` and `pooled.acquire()`** — the slow path (lines 237–247) performs a non-atomic read-then-acquire sequence. Between `pool.get(poolKey)` at line 238 and `pooled.acquire()` at line 246, `evictDisconnectedClient()` can fire on the SDK callback thread, see `inUse==0`, atomically remove the entry via `pool.remove(poolKey, pooled)`, and close the underlying `DeviceClient`. The caller then gets back a `Lease` whose client is already closed, causing the next `send()` to throw `IotHubClientException`. The fast path (the `computeIfPresent` block at the top of `acquire()`) is safe because it holds the segment lock across the touch+acquire. The slow path needs the same pattern: ```suggestion DeviceClient client = getOrCreate(deviceId, connectionString, protocol); // Use computeIfPresent to atomically verify presence and acquire, // preventing evictDisconnectedClient from removing between get and acquire. AtomicReference<PooledClient> acquired = new AtomicReference<>(); pool.computeIfPresent(poolKey, (key, p) -> { if (p.client == client) { p.touch(now); p.acquire(); acquired.set(p); } return p; }); PooledClient pooled = acquired.get(); if (pooled == null) { // Entry was evicted between getOrCreate and acquire — retry return acquire(deviceId, connectionString, protocol); } return new Lease(this, poolKey, pooled); ``` -- 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]
