diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java index 525dfe8b2f..51bbeba875 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java @@ -1,7 +1,7 @@ package io.github.hectorvent.floci.services.cloudtrail; +import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -23,9 +23,11 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; import java.util.zip.GZIPOutputStream; /** @@ -49,6 +51,7 @@ public class CloudTrailLogWriter { private static final DateTimeFormatter PATH_DATE = DateTimeFormatter.ofPattern("yyyy/MM/dd"); private static final DateTimeFormatter FILE_TS = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmm'Z'"); + static final int MAX_RECORDS_PER_LOG_FILE = 1_000; private static final String FILENAME_RAND_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; @@ -58,6 +61,7 @@ public class CloudTrailLogWriter { private final RegionResolver regionResolver; private final ObjectMapper mapper; private final SecureRandom rng = new SecureRandom(); + private final ConcurrentHashMap flushLocks = new ConcurrentHashMap<>(); private ScheduledExecutorService executor; @@ -110,7 +114,7 @@ public class CloudTrailLogWriter { try { for (CloudTrailService.TrailKey key : cloudTrailService.trailsWithPendingRecords()) { try { - flushTrail(key); + flushTrailBatches(key); } catch (RuntimeException e) { LOG.warnv(e, "CloudTrail log flush failed for trail {0} in {1}", key.trailName(), key.region()); @@ -121,17 +125,50 @@ public class CloudTrailLogWriter { } } - private void flushTrail(CloudTrailService.TrailKey key) { + private void flushTrailBatches(CloudTrailService.TrailKey key) { + FlushLock lock = flushLocks.compute(key, (ignored, existing) -> { + FlushLock result = existing != null ? existing : new FlushLock(); + result.users++; + return result; + }); + lock.mutex.lock(); + try { + int remaining = cloudTrailService.pendingRecordCount(key); + while (remaining > 0) { + int flushed = flushTrail(key); + if (flushed == 0) { + return; + } + remaining -= flushed; + } + } finally { + lock.mutex.unlock(); + flushLocks.computeIfPresent(key, (ignored, current) -> { + if (current != lock) { + return current; + } + current.users--; + return current.users == 0 ? null : current; + }); + } + } + + private static final class FlushLock { + private final ReentrantLock mutex = new ReentrantLock(); + private int users; + } + + private int flushTrail(CloudTrailService.TrailKey key) { Trail trail = cloudTrailService.getTrail(key.region(), key.trailName()); if (trail == null) { - // Trail was deleted while records were pending — drop them. - cloudTrailService.drainPendingRecords(key); - return; + // Trail was deleted while records were pending. Drop only the + // records that existed when this flush cycle started. + return cloudTrailService.drainPendingRecords(key, MAX_RECORDS_PER_LOG_FILE).size(); } - List records = cloudTrailService.drainPendingRecords(key); + List records = cloudTrailService.drainPendingRecords(key, MAX_RECORDS_PER_LOG_FILE); if (records.isEmpty()) { - return; + return 0; } byte[] payload; @@ -181,19 +218,22 @@ public class CloudTrailLogWriter { LOG.warnv(e, "CloudTrail self-delivery event emission failed for trail {0} " + "(write already succeeded, records not re-queued)", key.trailName()); } + return records.size(); } private byte[] serializeAndGzip(List records) { - ObjectNode envelope = mapper.createObjectNode(); - ArrayNode arr = envelope.putArray("Records"); - for (ObjectNode r : records) { - arr.add(r); - } try { - byte[] json = mapper.writeValueAsBytes(envelope); - ByteArrayOutputStream baos = new ByteArrayOutputStream(Math.max(64, json.length / 4)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (GZIPOutputStream gz = new GZIPOutputStream(baos)) { - gz.write(json); + try (JsonGenerator generator = mapper.getFactory().createGenerator(gz)) { + generator.writeStartObject(); + generator.writeArrayFieldStart("Records"); + for (ObjectNode record : records) { + generator.writeTree(record); + } + generator.writeEndArray(); + generator.writeEndObject(); + } } return baos.toByteArray(); } catch (Exception e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java index 3431875b29..74f96611ee 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java @@ -27,10 +27,11 @@ import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.ListIterator; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentLinkedDeque; import java.util.function.Supplier; @ApplicationScoped @@ -47,7 +48,7 @@ public class CloudTrailService { private final ObjectMapper mapper; /** Per-trail pending record buffers — ephemeral, never persisted. */ - private final ConcurrentHashMap> pendingRecordsByTrail = + private final ConcurrentHashMap> pendingRecordsByTrail = new ConcurrentHashMap<>(); /** @@ -364,25 +365,45 @@ public class CloudTrailService { } public void requeueRecords(TrailKey key, List records) { - if (!records.isEmpty()) { - queueFor(key).addAll(records); + if (records.isEmpty()) { + return; + } + ConcurrentLinkedDeque q = queueFor(key); + ListIterator it = records.listIterator(records.size()); + // Add in reverse so the first failed record remains first. + while (it.hasPrevious()) { + q.addFirst(it.previous()); } } public List drainPendingRecords(TrailKey key) { - ConcurrentLinkedQueue q = pendingRecordsByTrail.get(key); - if (q == null) return List.of(); + return drainPendingRecords(key, Integer.MAX_VALUE); + } + + public List drainPendingRecords(TrailKey key, int maxRecords) { + if (maxRecords <= 0) { + return List.of(); + } + ConcurrentLinkedDeque q = pendingRecordsByTrail.get(key); + if (q == null) { + return List.of(); + } List drained = new ArrayList<>(); ObjectNode r; - while ((r = q.poll()) != null) { + while (drained.size() < maxRecords && (r = q.pollFirst()) != null) { drained.add(r); } return drained; } + public int pendingRecordCount(TrailKey key) { + ConcurrentLinkedDeque q = pendingRecordsByTrail.get(key); + return q == null ? 0 : q.size(); + } + public List trailsWithPendingRecords() { List result = new ArrayList<>(); - for (Map.Entry> e : pendingRecordsByTrail.entrySet()) { + for (Map.Entry> e : pendingRecordsByTrail.entrySet()) { if (!e.getValue().isEmpty()) { result.add(e.getKey()); } @@ -396,8 +417,8 @@ public class CloudTrailService { .orElse(null); } - private ConcurrentLinkedQueue queueFor(TrailKey key) { - return pendingRecordsByTrail.computeIfAbsent(key, k -> new ConcurrentLinkedQueue<>()); + private ConcurrentLinkedDeque queueFor(TrailKey key) { + return pendingRecordsByTrail.computeIfAbsent(key, k -> new ConcurrentLinkedDeque<>()); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java index 52c167fcc8..598b9fcbbe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerService.java @@ -225,7 +225,13 @@ public class IotMqttBrokerService { server = null; tlsServer = null; keyManager = null; - sessionsByClient.values().forEach(session -> session.endpoint().close()); + sessionsByClient.values().forEach(session -> { + try { + session.endpoint().close(); + } catch (IllegalStateException e) { + LOG.debugv("IoT MQTT client {0} was already closed during broker shutdown", session.clientId()); + } + }); sessionsByClient.clear(); subscriptionsByClient.clear(); if (mqttServer != null) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterBatchingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterBatchingIntegrationTest.java new file mode 100644 index 0000000000..e1c3f2ca19 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterBatchingIntegrationTest.java @@ -0,0 +1,355 @@ +package io.github.hectorvent.floci.services.cloudtrail; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.services.cloudtrail.model.DataResource; +import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector; +import io.github.hectorvent.floci.services.cloudtrail.model.Trail; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.zip.GZIPInputStream; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@QuarkusTest +class CloudTrailLogWriterBatchingIntegrationTest { + + @Inject + CloudTrailLogWriter writer; + + @Inject + CloudTrailService realService; + + @AfterEach + void restoreRealService() { + QuarkusMock.installMockForType(realService, CloudTrailService.class); + } + + @Test + void maximumSizedFlushWritesOneValidOrderedGzipObject() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "batch-max-logs-" + suffix; + String trailName = "batch-max-trail-" + suffix; + String region = "us-east-1"; + + createBucket(bucket); + + CloudTrailService.TrailKey key = new CloudTrailService.TrailKey(region, trailName, region); + Deque pending = records(CloudTrailLogWriter.MAX_RECORDS_PER_LOG_FILE); + installMockCloudTrailService(bucket, trailName, region, key, pending); + + writer.flushNow(); + + List objects = readCloudTrailObjects(bucket); + assertEquals(1, objects.size()); + JsonNode envelope = objects.getFirst().envelope(); + assertEquals(1, envelope.size(), "Expected only the Records envelope field"); + assertTrue(envelope.path("Records").isArray(), "Records is not an array"); + assertRecordRange(toList(envelope.path("Records")), 0, 999); + } + + @Test + void flushWritesAllQueuedRecordsInBoundedObjects() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "batch-logs-" + suffix; + String trailName = "batch-trail-" + suffix; + String region = "us-east-1"; + + createBucket(bucket); + + CloudTrailService.TrailKey key = new CloudTrailService.TrailKey(region, trailName, region); + Deque pending = records(1_001); + installMockCloudTrailService(bucket, trailName, region, key, pending); + + writer.flushNow(); + + List> allObjects = readCloudTrailRecordGroups(bucket); + assertEquals(2, allObjects.size()); + allObjects = new ArrayList<>(allObjects); + allObjects.sort(Comparator.comparingInt(CloudTrailLogWriterBatchingIntegrationTest::firstRecordIndex)); + assertRecordRange(allObjects.get(0), 0, 999); + assertRecordRange(allObjects.get(1), 1_000, 1_000); + } + + @Test + void sustainedBacklogDrainsIncrementallyInOrder() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "batch-backlog-logs-" + suffix; + String trailName = "batch-backlog-trail-" + suffix; + String region = "us-east-1"; + + createBucket(bucket); + + CloudTrailService.TrailKey key = new CloudTrailService.TrailKey(region, trailName, region); + Deque pending = records(2_500); + installMockCloudTrailService(bucket, trailName, region, key, pending); + + writer.flushNow(); + + List> recordGroups = readCloudTrailRecordGroups(bucket).stream() + .sorted(Comparator.comparingInt(CloudTrailLogWriterBatchingIntegrationTest::firstRecordIndex)) + .toList(); + + assertEquals(3, recordGroups.size()); + assertRecordRange(recordGroups.get(0), 0, 999); + assertRecordRange(recordGroups.get(1), 1_000, 1_999); + assertRecordRange(recordGroups.get(2), 2_000, 2_499); + } + + @Test + void failedBoundedBatchRetriesBeforeNewerQueuedRecords() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "batch-source-" + suffix; + String destinationBucket = "batch-retry-logs-" + suffix; + String trailName = "batch-retry-trail-" + suffix; + String region = "us-east-1"; + + realService.createTrail(region, trailName, destinationBucket, null, + null, true, false, false, false); + realService.putEventSelectors(region, trailName, List.of(new EventSelector( + "All", + false, + List.of(new DataResource("AWS::S3::Object", + List.of("arn:aws:s3:::" + sourceBucket + "/"))), + List.of()))); + realService.startLogging(region, trailName); + emitS3Events(sourceBucket, region, 0, 1_000); + + writer.flushNow(); + + createBucket(destinationBucket); + emitS3Events(sourceBucket, region, 1_001, 1_005); + + writer.flushNow(); + + List> recordGroups = new ArrayList<>(readCloudTrailRecordGroups(destinationBucket)); + recordGroups.sort(Comparator.comparingInt(CloudTrailLogWriterBatchingIntegrationTest::firstRecordIndex)); + assertEquals(2, recordGroups.size()); + assertRecordRange(recordGroups.get(0), 0, 999); + assertRecordRange(recordGroups.get(1), 1_000, 1_005); + } + + @Test + void overlappingFlushesForOneTrailAreSerialized() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "serialized-logs-" + suffix; + String trailName = "serialized-trail-" + suffix; + String region = "us-east-1"; + + createBucket(bucket); + + CloudTrailService.TrailKey key = new CloudTrailService.TrailKey(region, trailName, region); + Deque pending = records(2); + Trail trail = new Trail(trailName, + "arn:aws:cloudtrail:" + region + ":000000000000:trail/" + trailName, + bucket, null, null, true, false, region, false, false, false, false); + CountDownLatch firstDrainEntered = new CountDownLatch(1); + CountDownLatch releaseFirstDrain = new CountDownLatch(1); + CountDownLatch secondDrainEntered = new CountDownLatch(1); + AtomicBoolean inDrain = new AtomicBoolean(); + AtomicBoolean overlap = new AtomicBoolean(); + AtomicInteger drainCalls = new AtomicInteger(); + + CloudTrailService mockService = mock(CloudTrailService.class); + when(mockService.trailsWithPendingRecords()) + .thenAnswer(inv -> pending.isEmpty() ? List.of() : List.of(key)); + when(mockService.pendingRecordCount(eq(key))).thenAnswer(inv -> pending.size()); + when(mockService.getTrail(region, trailName)).thenReturn(trail); + when(mockService.drainPendingRecords(eq(key), eq(CloudTrailLogWriter.MAX_RECORDS_PER_LOG_FILE))) + .thenAnswer(inv -> { + if (!inDrain.compareAndSet(false, true)) { + overlap.set(true); + } + try { + if (drainCalls.getAndIncrement() == 0) { + firstDrainEntered.countDown(); + releaseFirstDrain.await(5, TimeUnit.SECONDS); + } else { + secondDrainEntered.countDown(); + } + return drain(pending, CloudTrailLogWriter.MAX_RECORDS_PER_LOG_FILE); + } finally { + inDrain.set(false); + } + }); + doAnswer(inv -> null).when(mockService).emitS3DataEvent(any()); + QuarkusMock.installMockForType(mockService, CloudTrailService.class); + + Thread first = new Thread(writer::flushNow); + Thread second = new Thread(writer::flushNow); + first.start(); + assertTrue(firstDrainEntered.await(5, TimeUnit.SECONDS)); + second.start(); + + assertFalse(secondDrainEntered.await(200, TimeUnit.MILLISECONDS), + "A second flush must wait for the first trail flush to finish"); + releaseFirstDrain.countDown(); + first.join(5_000); + second.join(5_000); + + assertFalse(first.isAlive(), "First flush did not finish"); + assertFalse(second.isAlive(), "Second flush did not finish"); + assertFalse(overlap.get(), "Flushes for one trail overlapped"); + } + + private void installMockCloudTrailService(String bucket, String trailName, String region, + CloudTrailService.TrailKey key, + Deque pending) { + Trail trail = new Trail(trailName, + "arn:aws:cloudtrail:" + region + ":000000000000:trail/" + trailName, + bucket, null, null, true, false, region, false, false, false, false); + + CloudTrailService mockService = mock(CloudTrailService.class); + when(mockService.trailsWithPendingRecords()) + .thenAnswer(inv -> pending.isEmpty() ? List.of() : List.of(key)); + when(mockService.pendingRecordCount(eq(key))).thenAnswer(inv -> pending.size()); + when(mockService.getTrail(region, trailName)).thenReturn(trail); + when(mockService.drainPendingRecords(eq(key), eq(CloudTrailLogWriter.MAX_RECORDS_PER_LOG_FILE))) + .thenAnswer(inv -> drain(pending, CloudTrailLogWriter.MAX_RECORDS_PER_LOG_FILE)); + doAnswer(inv -> null).when(mockService).emitS3DataEvent(any()); + + QuarkusMock.installMockForType(mockService, CloudTrailService.class); + } + + private void emitS3Events(String bucket, String region, int first, int last) { + for (int i = first; i <= last; i++) { + realService.emitS3DataEvent(CloudTrailService.S3EventInput.builder() + .region(region) + .eventName("PutObject") + .bucketName(bucket) + .key(objectKey(i)) + .accessKeyId(null) + .sourceIp(null) + .userAgent("test") + .bytesIn(0) + .bytesOut(0) + .errorCode(null) + .errorMessage(null) + .eventTimeMillis(System.currentTimeMillis()) + .build()); + } + } + + private static List drain(Deque pending, int maxRecords) { + List drained = new ArrayList<>(); + while (drained.size() < maxRecords && !pending.isEmpty()) { + drained.add(pending.removeFirst()); + } + return drained; + } + + private static Deque records(int count) { + ObjectMapper mapper = new ObjectMapper(); + Deque records = new ArrayDeque<>(); + for (int i = 0; i < count; i++) { + ObjectNode record = mapper.createObjectNode(); + record.put("eventName", "PutObject"); + record.putObject("requestParameters").put("key", objectKey(i)); + records.add(record); + } + return records; + } + + private static void assertRecordRange(List records, int first, int last) { + assertEquals(last - first + 1, records.size()); + for (int i = first; i <= last; i++) { + JsonNode record = records.get(i - first); + assertEquals(objectKey(i), record.path("requestParameters").path("key").asText()); + } + } + + private static String objectKey(int index) { + return "object-" + String.format("%04d", index); + } + + private static int firstRecordIndex(List records) { + return recordIndex(records.getFirst()); + } + + private static int recordIndex(JsonNode record) { + String key = record.path("requestParameters").path("key").asText(); + return Integer.parseInt(key.substring("object-".length())); + } + + private static void createBucket(String name) { + given().when().put("/" + name).then().statusCode(200); + } + + private static List> readCloudTrailRecordGroups(String bucket) throws Exception { + return readCloudTrailObjects(bucket).stream() + .map(logObject -> toList(logObject.envelope().path("Records"))) + .toList(); + } + + private static List readCloudTrailObjects(String bucket) throws Exception { + List objects = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + for (String key : listCloudTrailKeys(bucket)) { + byte[] gz = given().when().get("/" + bucket + "/" + key) + .then().statusCode(200).extract().asByteArray(); + try (GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(gz))) { + JsonNode envelope = mapper.readTree(gzin); + JsonNode records = envelope.get("Records"); + assertNotNull(records, "Missing Records[] in " + key); + assertTrue(records.isArray(), "Records is not an array in " + key); + objects.add(new CloudTrailLogObject(key, envelope)); + } + } + return objects; + } + + private static List toList(JsonNode records) { + List result = new ArrayList<>(); + records.forEach(result::add); + return result; + } + + private static List listCloudTrailKeys(String bucket) { + String xml = given().when().get("/" + bucket + "?list-type=2") + .then().statusCode(200).extract().asString(); + List keys = new ArrayList<>(); + int from = 0; + while (true) { + int open = xml.indexOf("", from); + if (open < 0) { + break; + } + int close = xml.indexOf("", open); + String key = xml.substring(open + 5, close); + if (key.contains("/CloudTrail/") && key.endsWith(".json.gz")) { + keys.add(key); + } + from = close + 6; + } + keys.sort(Comparator.naturalOrder()); + return keys; + } + + private record CloudTrailLogObject(String key, JsonNode envelope) { + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.java index 476cd38e1f..d8b645fd83 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.java @@ -68,12 +68,14 @@ class CloudTrailLogWriterRequeueTest { CloudTrailService mockService = mock(CloudTrailService.class); when(mockService.trailsWithPendingRecords()) .thenAnswer(inv -> pending.isEmpty() ? List.of() : List.of(key)); + when(mockService.pendingRecordCount(eq(key))).thenAnswer(inv -> pending.size()); when(mockService.getTrail(region, trailName)).thenReturn(trail); - when(mockService.drainPendingRecords(key)).thenAnswer(inv -> { - List drained = new ArrayList<>(pending); - pending.clear(); - return drained; - }); + when(mockService.drainPendingRecords(eq(key), eq(CloudTrailLogWriter.MAX_RECORDS_PER_LOG_FILE))) + .thenAnswer(inv -> { + List drained = new ArrayList<>(pending); + pending.clear(); + return drained; + }); doAnswer(inv -> { List records = inv.getArgument(1); pending.addAll(records); diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java index e12291c6f8..1fe1d4485e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java @@ -263,6 +263,19 @@ class IotMqttBrokerDeviceVerificationTest { } } + @Test + void stoppingAfterClientDisconnectDoesNotFail() throws Exception { + RegisteredDevice device = registered(deviceLeaf); + when(service.findRegisteredCertificate(certificate(deviceLeaf))).thenReturn(Optional.of(device)); + when(service.isConnectAllowed(eq(device), eq("sensor-1"), eq("127.0.0.1"), isNull())).thenReturn(true); + + MqttClient client = connectTls("sensor-1", deviceLeaf, null); + client.disconnect(); + client.close(); + + broker.stop(); + } + /** Dials {@code host}, which Paho also sends as the TLS server name; MQTT 3.1.1 pinned so a refusal is not retried as 3.1. */ private MqttClient connectTls(String clientId, CertificateGenerator.GeneratedCertificate leaf, String host) throws Exception { MqttClient client = new MqttClient("ssl://" + (host == null ? "127.0.0.1" : host) + ":" + tlsPort, clientId, new MemoryPersistence());