This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new c2b3124de60f CAMEL-27460: camel-azure-iothub - a device client is no
longer closed as idle after a long send or a slow open (#30844)
c2b3124de60f is described below
commit c2b3124de60f6307ffb318a1a4a6f2f2d000e6a4
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:34:29 2026 +0530
CAMEL-27460: camel-azure-iothub - a device client is no longer closed as
idle after a long send or a slow open (#30844)
DeviceClientPool compared the idle timeout with a "last used" time that was
not kept up to date: acquire read the clock once, before it could block for
the whole open of a new client; a new client got the time read before
open(true); and giving back the last lease checked the idle time before
updating it. A send longer than deviceClientIdleTimeout closed its client
when the lease was given back, and with a hub slower to accept a connection
than the idle timeout every message opened a new connection (5 messages,
5 opens).
A client with a lease is still never evicted. Now its idle time counts from
the last release: the lease touches the client when it is taken and right
before it is given back, and giving it back no longer runs an idle check
(the touchAndMaybeEvict step is removed; the eviction task and acquire
still evict idle clients). A new client gets its time after open(true), the
clock is read at each touch, and the time never moves back. The public API
is unchanged.
Not changed: a DISCONNECTED reported before the new client is pooled is
lost; Lease.close can close a client that another producer leased between
the release and a disconnect that retired it; shutdown() closes leased
clients and clears the creation futures without completing them; a slow
close delays the eviction task.
Tests in DeviceClientPoolTest: a slow send keeps its client and its idle
time
counts from the release, a slowly opened client is not evicted before its
first lease, and 5 messages to a slow hub open one connection.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../azure/iothub/client/DeviceClientPool.java | 94 +++++++----------
.../azure/iothub/client/DeviceClientPoolTest.java | 112 +++++++++++++++++++++
2 files changed, 149 insertions(+), 57 deletions(-)
diff --git
a/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
b/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
index 1ac19c02ba4e..f90c7a15f21b 100644
---
a/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
+++
b/components/camel-azure/camel-azure-iothub/src/main/java/org/apache/camel/component/azure/iothub/client/DeviceClientPool.java
@@ -28,6 +28,7 @@ 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.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongSupplier;
@@ -44,10 +45,11 @@ import org.slf4j.LoggerFactory;
* 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 disconnected clients are
retired automatically; any in-use client is
- * closed only when the final lease is released. Callers may also remove a
client from the pool explicitly during
- * cleanup.
+ * Clients are created lazily, reused across messages, and evicted after an
idle timeout. A client is idle only while it
+ * has no lease, and its idle time counts from the last release (or from the
end of its open, if it was never leased),
+ * so a long send or a slow open does not make it idle. Connection status
changes are monitored through the Azure SDK
+ * callback, and disconnected clients are retired automatically; any in-use
client is closed only when the final lease
+ * is released. Callers may also remove a client from the pool explicitly
during cleanup.
* </p>
*/
public class DeviceClientPool {
@@ -61,18 +63,24 @@ public class DeviceClientPool {
private static final class PooledClient {
final DeviceClient client;
- volatile long lastUsed;
+ // the last time the client was leased or released; the idle time of a
client without a lease runs from here
+ final AtomicLong lastUsed;
final AtomicInteger inUse = new AtomicInteger();
volatile boolean retired;
final AtomicBoolean closed = new AtomicBoolean();
PooledClient(DeviceClient client, long nowMillis) {
this.client = client;
- this.lastUsed = nowMillis;
+ this.lastUsed = new AtomicLong(nowMillis);
}
void touch(long nowMillis) {
- this.lastUsed = nowMillis;
+ // never move it back: a thread that read the clock earlier must
not shorten the idle time
+ lastUsed.accumulateAndGet(nowMillis, Math::max);
+ }
+
+ boolean isIdle(long nowMillis, long idleTimeoutMillis) {
+ return inUse.get() == 0 && (nowMillis - lastUsed.get()) >
idleTimeoutMillis;
}
void acquire() {
@@ -86,13 +94,11 @@ public class DeviceClientPool {
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) {
+ private Lease(DeviceClientPool pool, PooledClient pooled) {
this.pool = pool;
- this.poolKey = poolKey;
this.pooled = pooled;
}
@@ -110,12 +116,10 @@ public class DeviceClientPool {
return;
}
closed = true;
- if (pooled.release()) {
- if (pooled.retired) {
- pool.closeRetired(pooled);
- } else {
- pool.touchAndMaybeEvict(poolKey);
- }
+ // touch before the lease is given back, so the idle time of the
client starts at the release
+ pooled.touch(pool.nowMillis());
+ if (pooled.release() && pooled.retired) {
+ pool.closeRetired(pooled);
}
}
}
@@ -183,11 +187,10 @@ public class DeviceClientPool {
}
String poolKey = resolvePoolKey(deviceId, connectionString);
- final long now = nowMillisSupplier.getAsLong();
PooledClient existing = pool.get(poolKey);
if (existing != null) {
- existing.touch(now);
+ existing.touch(nowMillis());
return existing.client;
}
@@ -201,11 +204,12 @@ public class DeviceClientPool {
return rechecked.client;
}
DeviceClient client = createClient(deviceId, connectionString,
protocol);
- PooledClient pooled = new PooledClient(client, now);
+ // read the clock after open: opening can take longer than the
idle timeout on a slow hub
+ PooledClient pooled = new PooledClient(client, nowMillis());
PooledClient previous = pool.putIfAbsent(poolKey, pooled);
if (previous != null) {
client.close();
- previous.touch(now);
+ previous.touch(nowMillis());
createdFuture.complete(previous.client);
return previous.client;
}
@@ -253,17 +257,13 @@ public class DeviceClientPool {
}
String poolKey = resolvePoolKey(deviceId, connectionString);
- final long now = nowMillisSupplier.getAsLong();
for (;;) {
+ // read the clock on every attempt: getOrCreate below can block
for a whole open of the client
+ final long now = nowMillis();
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()) {
+ if (pooled.isIdle(now, idleTimeout.toMillis())) {
evicted.set(pooled);
return null;
}
@@ -272,7 +272,7 @@ public class DeviceClientPool {
return pooled;
});
if (existing != null) {
- return new Lease(this, poolKey, existing);
+ return new Lease(this, existing);
}
if (evicted.get() != null) {
closeQuietly(poolKey, evicted.get().client, "idle eviction");
@@ -280,18 +280,19 @@ public class DeviceClientPool {
}
DeviceClient client = getOrCreate(deviceId, connectionString,
protocol);
+ final long afterCreate = nowMillis();
AtomicReference<PooledClient> acquired = new AtomicReference<>();
pool.computeIfPresent(poolKey, (key, pooled) -> {
if (pooled.client != client) {
return pooled;
}
- pooled.touch(now);
+ pooled.touch(afterCreate);
pooled.acquire();
acquired.set(pooled);
return pooled;
});
if (acquired.get() != null) {
- return new Lease(this, poolKey, acquired.get());
+ return new Lease(this, acquired.get());
}
// The pool entry may have been evicted or replaced between
creation and the acquire step.
// Loop back to retry instead of recursing to keep the stack depth
constant.
@@ -499,28 +500,6 @@ public class DeviceClientPool {
}
}
- private void touchAndMaybeEvict(String poolKey) {
- long now = nowMillisSupplier.getAsLong();
- AtomicReference<PooledClient> retired = new AtomicReference<>();
- pool.computeIfPresent(poolKey, (key, current) -> {
- if (current.inUse.get() > 0) {
- current.touch(now);
- return current;
- }
- if ((now - current.lastUsed) > idleTimeout.toMillis()) {
- current.retired = true;
- retired.set(current);
- return null;
- }
- current.touch(now);
- return current;
- });
- PooledClient expired = retired.get();
- if (expired != null) {
- closeRetired(expired);
- }
- }
-
private void closeRetired(PooledClient pooled) {
if (!pooled.closed.compareAndSet(false, true)) {
return;
@@ -555,15 +534,12 @@ public class DeviceClientPool {
if (shuttingDown.get()) {
return;
}
- long now = nowMillisSupplier.getAsLong();
+ long now = nowMillis();
for (Map.Entry<String, PooledClient> entry : pool.entrySet()) {
String key = entry.getKey();
AtomicReference<PooledClient> retired = new AtomicReference<>();
pool.computeIfPresent(key, (k, current) -> {
- if (current.inUse.get() > 0) {
- return current;
- }
- if ((now - current.lastUsed) > idleTimeout.toMillis()) {
+ if (current.isIdle(now, idleTimeout.toMillis())) {
current.retired = true;
retired.set(current);
return null;
@@ -577,6 +553,10 @@ public class DeviceClientPool {
}
}
+ private long nowMillis() {
+ return nowMillisSupplier.getAsLong();
+ }
+
public int getActiveClientCount() {
return pool.size();
}
diff --git
a/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
b/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
index a03bd7a6df9d..057014a278b3 100644
---
a/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
+++
b/components/camel-azure/camel-azure-iothub/src/test/java/org/apache/camel/component/azure/iothub/client/DeviceClientPoolTest.java
@@ -38,6 +38,7 @@ 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.ArgumentCaptor;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -47,8 +48,10 @@ 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.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -468,4 +471,113 @@ class DeviceClientPoolTest {
}
}
+ @Test
+ void testSlowSendKeepsItsClientAndIdleTimeCountsFromRelease() throws
Exception {
+ AtomicLong clock = new AtomicLong();
+ List<DeviceClient> created = new ArrayList<>();
+ ScheduledExecutorService evictor = inlineEvictor();
+ DeviceClientPool pool = poolWithClock(evictor, clock, created, 0);
+ pool.start();
+ Runnable evictionRun = scheduledEvictionRun(evictor);
+
+ DeviceClient first;
+ try (DeviceClientPool.Lease lease = pool.lease("d", CS,
IotHubClientProtocol.MQTT)) {
+ first = lease.getClient();
+ // the send takes 15 s, longer than the 10 s idle timeout: the
client is in use all that time
+ clock.addAndGet(15_000);
+ evictionRun.run();
+ assertEquals(1, pool.getActiveClientCount(), "a leased client must
not be evicted");
+ }
+ assertEquals(1, pool.getActiveClientCount(), "the release must not
evict the client it gives back");
+ evictionRun.run();
+ assertEquals(1, pool.getActiveClientCount(), "the idle time starts at
the release");
+ verify(first, never()).close();
+
+ clock.addAndGet(1);
+ try (DeviceClientPool.Lease lease = pool.lease("d", CS,
IotHubClientProtocol.MQTT)) {
+ assertSame(first, lease.getClient(), "the next message reuses the
open client");
+ }
+ assertEquals(1, created.size());
+
+ clock.addAndGet(10_001);
+ evictionRun.run();
+ assertEquals(0, pool.getActiveClientCount(), "a client unused for
longer than the idle timeout is evicted");
+ verify(first, times(1)).close();
+ }
+
+ @Test
+ void testSlowlyOpenedClientIsNotEvictedBeforeItsFirstLease() throws
Exception {
+ AtomicLong clock = new AtomicLong();
+ List<DeviceClient> created = new ArrayList<>();
+ ScheduledExecutorService evictor = inlineEvictor();
+ // open(true) takes 15 s, longer than the 10 s idle timeout
+ DeviceClientPool pool = poolWithClock(evictor, clock, created, 15_000);
+ pool.start();
+ Runnable evictionRun = scheduledEvictionRun(evictor);
+
+ DeviceClient opened = pool.getOrCreate("d", CS,
IotHubClientProtocol.MQTT);
+ // the eviction run comes right after the open, before the creator
leases the client
+ evictionRun.run();
+ assertEquals(1, pool.getActiveClientCount(), "a client that was just
opened is not idle");
+
+ try (DeviceClientPool.Lease lease = pool.lease("d", CS,
IotHubClientProtocol.MQTT)) {
+ assertSame(opened, lease.getClient());
+ }
+ assertEquals(1, created.size());
+ verify(opened, never()).close();
+ }
+
+ @Test
+ void testSlowHubOpensOneConnectionForManyMessages() throws Exception {
+ AtomicLong clock = new AtomicLong();
+ List<DeviceClient> created = new ArrayList<>();
+ // open(true) takes 15 s, longer than the 10 s idle timeout; the sends
are instant
+ DeviceClientPool pool = poolWithClock(null, clock, created, 15_000);
+
+ int messages = 5;
+ for (int i = 0; i < messages; i++) {
+ try (DeviceClientPool.Lease lease = pool.lease("d", CS,
IotHubClientProtocol.MQTT)) {
+ assertSame(created.get(0), lease.getClient(), "every message
reuses the first connection");
+ }
+ clock.addAndGet(100);
+ }
+
+ assertEquals(1, created.size(), "the messages share one connection");
+ assertEquals(1, pool.getActiveClientCount());
+ verify(created.get(0), times(1)).open(true);
+ verify(created.get(0), never()).close();
+ }
+
+ private static DeviceClientPool poolWithClock(
+ ScheduledExecutorService evictor, AtomicLong clock,
List<DeviceClient> created, long openMillis) {
+ DeviceClientPool pool = new DeviceClientPool(Duration.ofSeconds(10),
Duration.ofSeconds(30), evictor);
+ pool.setNowMillisSupplier(clock::get);
+ pool.setDeviceClientFactory((cs, protocol) -> {
+ DeviceClient client = mock(DeviceClient.class);
+ doAnswer(invocation -> {
+ clock.addAndGet(openMillis);
+ return null;
+ }).when(client).open(true);
+ created.add(client);
+ return client;
+ });
+ return pool;
+ }
+
+ // an evictor that runs the queued closes at once; the periodic eviction
run is called by the test
+ private static ScheduledExecutorService inlineEvictor() {
+ ScheduledExecutorService evictor =
mock(ScheduledExecutorService.class);
+ doAnswer(invocation -> {
+ invocation.getArgument(0, Runnable.class).run();
+ return null;
+ }).when(evictor).execute(any(Runnable.class));
+ return evictor;
+ }
+
+ private static Runnable scheduledEvictionRun(ScheduledExecutorService
evictor) {
+ ArgumentCaptor<Runnable> run = ArgumentCaptor.forClass(Runnable.class);
+ verify(evictor).scheduleAtFixedRate(run.capture(), anyLong(),
anyLong(), any(TimeUnit.class));
+ return run.getValue();
+ }
+
}