mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iot): search fleet things by connectivity status (#6025)
* feat(iot): search fleet things by connectivity status SearchIndex refused every connectivity field and its documents carried no connectivity, so an application that finds its things by connection state got InvalidQueryException. With connectivity indexing on, a thing now reports the MQTT broker session whose client id is its name, and connectivity.connected, connectivity.clientId and connectivity.disconnectReason can be searched. The other connectivity fields are still refused with InvalidQueryException. A thing whose client id never connected reports connected false and timestamp 0, as on AWS. The broker now records the account, region, connect time, keep alive and clean session of each session, and keeps in memory how the last one of each client id ended in each account and region, until a state reset. The reason is the one the session's disconnected lifecycle event carries, recorded by the same single endSession under the session lock, so the late end of a displaced session cannot overwrite its successor's. A plaintext session counts in the default account and region, a TLS session in its certificate's. Closes #4912 * fix(iot): serialize connectivity reads and resets with session ends A connectivity lookup read the live session without the session lock, so a search racing DeleteConnection could see the session connected after its disconnect was recorded. A state reset cleared the history without the lock too. Both now run under the session lock; the lookup tests the session's ended flag instead of the endpoint, as the lock is never held across endpoint calls. Tests cover the reset contract, a lookup and a reset racing a held DeleteConnection, and a TLS session counting in its certificate's account and region.
This commit is contained in:
1 parent
1eb402d623
commit
34d904fde5
11 files changed
+536
-67
No files matched your search
+153
@@ -0,0 +1,153 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* SearchIndex connectivity against a real MQTT client on the plaintext broker: a client id that
|
||||
* names a thing makes that thing connected, and a DISCONNECT packet, a dropped socket and
|
||||
* DeleteConnection end it with AWS's disconnect reasons. Unsigned requests run in the default
|
||||
* account and region, which is where a plaintext session counts.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IotFleetIndexingConnectivityIntegrationTest.MqttProfile.class)
|
||||
class IotFleetIndexingConnectivityIntegrationTest {
|
||||
|
||||
private static final int PORT = 18840;
|
||||
private static final String BROKER_URI = "tcp://127.0.0.1:" + PORT;
|
||||
private static final String INDEXING = """
|
||||
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY", "thingConnectivityIndexingMode": "STATUS"}}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void searchReportsTheMqttSessionOfTheThingsClientId() throws Exception {
|
||||
String thingName = "fleet-connectivity-" + System.nanoTime();
|
||||
given().contentType("application/json").body(INDEXING).when().post("/indexing/config").then().statusCode(200);
|
||||
given().contentType("application/json").body("{}").when().post("/things/" + thingName).then().statusCode(200);
|
||||
assertEquals(Map.of("clientId", thingName, "connected", false, "timestamp", 0), connectivity(null, thingName));
|
||||
|
||||
MqttClient client = new MqttClient(BROKER_URI, thingName, new MemoryPersistence());
|
||||
client.setTimeToWait(10_000);
|
||||
long beforeConnect = System.currentTimeMillis();
|
||||
client.connect(options(30, true));
|
||||
long afterConnect = System.currentTimeMillis();
|
||||
Map<String, Object> connected = connectivity(null, thingName);
|
||||
long connectedAt = ((Number) connected.get("timestamp")).longValue();
|
||||
assertTrue(connectedAt >= beforeConnect && connectedAt <= afterConnect, "connect timestamp " + connectedAt);
|
||||
assertEquals(Map.of("connected", true, "timestamp", connected.get("timestamp"), "keepAliveDuration", 30,
|
||||
"cleanSession", true, "clientId", thingName), connected);
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"queryString\": \"connectivity.connected:true AND thingName:" + thingName + "\"}")
|
||||
.when()
|
||||
.post("/indices/search")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("things.thingName", contains(thingName));
|
||||
|
||||
String otherAccount = "AWS4-HMAC-SHA256 Credential=111100000012/20260215/us-east-1/iot/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
given().header("Authorization", otherAccount).contentType("application/json").body(INDEXING)
|
||||
.when().post("/indexing/config").then().statusCode(200);
|
||||
given().header("Authorization", otherAccount).contentType("application/json").body("{}")
|
||||
.when().post("/things/" + thingName).then().statusCode(200);
|
||||
assertEquals(Map.of("clientId", thingName, "connected", false, "timestamp", 0),
|
||||
connectivity(otherAccount, thingName));
|
||||
|
||||
client.disconnect();
|
||||
Map<String, Object> disconnected = awaitDisconnected(thingName);
|
||||
assertTrue(((Number) disconnected.get("timestamp")).longValue() >= connectedAt);
|
||||
assertEquals(Map.of("connected", false, "timestamp", disconnected.get("timestamp"),
|
||||
"disconnectReason", "CLIENT_INITIATED_DISCONNECT", "keepAliveDuration", 30, "cleanSession", true,
|
||||
"clientId", thingName), disconnected);
|
||||
|
||||
client.connect(options(45, false));
|
||||
Map<String, Object> reconnected = connectivity(null, thingName);
|
||||
assertEquals(true, reconnected.get("connected"));
|
||||
assertEquals(45, reconnected.get("keepAliveDuration"));
|
||||
assertEquals(false, reconnected.get("cleanSession"));
|
||||
client.disconnectForcibly(0, 0, false);
|
||||
client.close();
|
||||
Map<String, Object> lost = awaitDisconnected(thingName);
|
||||
assertEquals(Map.of("connected", false, "timestamp", lost.get("timestamp"), "disconnectReason",
|
||||
"CONNECTION_LOST", "keepAliveDuration", 45, "cleanSession", false, "clientId", thingName), lost);
|
||||
|
||||
MqttClient deleted = new MqttClient(BROKER_URI, thingName, new MemoryPersistence());
|
||||
deleted.setTimeToWait(10_000);
|
||||
deleted.connect(options(60, true));
|
||||
assertEquals(true, connectivity(null, thingName).get("connected"));
|
||||
given().when().delete("/connections/{clientId}", thingName).then().statusCode(200);
|
||||
Map<String, Object> apiInitiated = awaitDisconnected(thingName);
|
||||
assertEquals(Map.of("connected", false, "timestamp", apiInitiated.get("timestamp"), "disconnectReason",
|
||||
"API_INITIATED_DISCONNECT", "keepAliveDuration", 60, "cleanSession", true, "clientId", thingName),
|
||||
apiInitiated);
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"queryString\": \"connectivity.disconnectReason:API_INITIATED_DISCONNECT AND thingName:"
|
||||
+ thingName + "\"}")
|
||||
.when()
|
||||
.post("/indices/search")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("things.thingName", contains(thingName));
|
||||
deleted.close(true);
|
||||
}
|
||||
|
||||
private static Map<String, Object> connectivity(String authorization, String thingName) {
|
||||
return given()
|
||||
.headers(authorization == null ? Map.of() : Map.of("Authorization", authorization))
|
||||
.contentType("application/json")
|
||||
.body("{\"queryString\": \"thingName:" + thingName + "\"}")
|
||||
.when()
|
||||
.post("/indices/search")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("things[0].connectivity");
|
||||
}
|
||||
|
||||
/** The broker learns of a disconnect on its event loop, a moment after the client returns. */
|
||||
private static Map<String, Object> awaitDisconnected(String thingName) throws InterruptedException {
|
||||
Instant deadline = Instant.now().plus(Duration.ofSeconds(5));
|
||||
Map<String, Object> state = connectivity(null, thingName);
|
||||
while (Boolean.TRUE.equals(state.get("connected")) && Instant.now().isBefore(deadline)) {
|
||||
Thread.sleep(25);
|
||||
state = connectivity(null, thingName);
|
||||
}
|
||||
assertEquals(false, state.get("connected"));
|
||||
return state;
|
||||
}
|
||||
|
||||
private static MqttConnectOptions options(int keepAliveSeconds, boolean cleanSession) {
|
||||
MqttConnectOptions options = new MqttConnectOptions();
|
||||
options.setCleanSession(cleanSession);
|
||||
options.setConnectionTimeout(2);
|
||||
options.setKeepAliveInterval(keepAliveSeconds);
|
||||
options.setAutomaticReconnect(false);
|
||||
return options;
|
||||
}
|
||||
|
||||
public static final class MqttProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.iot.mqtt.enabled", "true",
|
||||
"floci.services.iot.mqtt.auto-start", "true",
|
||||
"floci.services.iot.mqtt.host", "127.0.0.1",
|
||||
"floci.services.iot.mqtt.port", Integer.toString(PORT));
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-11
@@ -341,28 +341,24 @@ class IotFleetIndexingIntegrationTest {
|
||||
.statusCode(200)
|
||||
.body("$", aMapWithSize(1))
|
||||
.body("things", hasSize(1))
|
||||
.body("things[0]", aMapWithSize(5))
|
||||
.body("things[0]", aMapWithSize(6))
|
||||
.body("things[0].thingName", equalTo("search-a"))
|
||||
.body("things[0].thingId", not(emptyOrNullString()))
|
||||
.body("things[0].thingTypeName", equalTo("search-sensor"))
|
||||
.body("things[0].thingGroupNames", contains("search-north"))
|
||||
.body("things[0].attributes.provider", equalTo("Acme"))
|
||||
.body("things[0].attributes.site", equalTo("north"))
|
||||
.body("things[0]", not(hasKey("connectivity")));
|
||||
.body("things[0].connectivity", aMapWithSize(3))
|
||||
.body("things[0].connectivity.clientId", equalTo("search-a"))
|
||||
.body("things[0].connectivity.connected", equalTo(false))
|
||||
.body("things[0].connectivity.timestamp", equalTo(0));
|
||||
search(auth, """
|
||||
{"queryString": "thingName:search-c", "queryVersion": "2017-09-30", "indexName": "AWS_Things"}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("things[0]", aMapWithSize(2))
|
||||
.body("things[0]", aMapWithSize(3))
|
||||
.body("things[0].thingName", equalTo("search-c"))
|
||||
.body("things[0]", not(hasKey("connectivity")));
|
||||
search(auth, """
|
||||
{"queryString": "connectivity.connected:true"}
|
||||
""")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidQueryException"))
|
||||
.body("message", equalTo("Floci does not support the field connectivity.connected in fleet index "
|
||||
+ "queries, query string: connectivity.connected:true"));
|
||||
.body("things[0]", hasKey("connectivity"));
|
||||
|
||||
String nextToken = search(auth, """
|
||||
{"queryString": "thingName:search-*", "maxResults": 2}
|
||||
|
||||
+31
-20
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.iot.IotMqttBrokerService.Connectivity;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.Field;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.GeoLocation;
|
||||
@@ -24,6 +25,7 @@ import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
@@ -34,6 +36,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IotFleetIndexingServiceTest {
|
||||
|
||||
@@ -73,13 +77,15 @@ class IotFleetIndexingServiceTest {
|
||||
new Field("thingGroupName", "String"),
|
||||
new Field("thingGroupId", "String"));
|
||||
|
||||
private static final String ACCOUNT = IotServiceTestSupport.ACCOUNT;
|
||||
private static final String CONNECTIVITY_NOT_ENABLED = "Query includes one or more constraints for Connectivity "
|
||||
+ "attribute, but Connectivity indexing is not enabled for AWS_Things index";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final IotServiceTestSupport iot = new IotServiceTestSupport(REGION, null);
|
||||
private final IotMqttBrokerService broker = mock(IotMqttBrokerService.class);
|
||||
private final IotFleetIndexingService service =
|
||||
new IotFleetIndexingService(new InMemoryStorage<>(), iot.service);
|
||||
new IotFleetIndexingService(new InMemoryStorage<>(), iot.service, broker);
|
||||
|
||||
private JsonNode json(String text) {
|
||||
try {
|
||||
@@ -720,7 +726,7 @@ class IotFleetIndexingServiceTest {
|
||||
}
|
||||
|
||||
private IotService.Page<ObjectNode> search(ObjectNode request) {
|
||||
return service.searchIndex(request, REGION);
|
||||
return service.searchIndex(request, ACCOUNT, REGION);
|
||||
}
|
||||
|
||||
private List<String> names(String queryString) {
|
||||
@@ -838,22 +844,28 @@ class IotFleetIndexingServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectivityFieldsAreRefusedLikeShadowAndDeviceDefenderFields() {
|
||||
void connectivityReportsTheBrokerStateOfTheCallersAccountAndRegion() {
|
||||
fleet("{\"thingIndexingMode\": \"REGISTRY\", \"thingConnectivityIndexingMode\": \"STATUS\"}");
|
||||
when(broker.connectivity(ACCOUNT, REGION, "alpha-1")).thenReturn(Optional.of(
|
||||
new Connectivity(true, 1_700_000_000_000L, null, 30, true)));
|
||||
when(broker.connectivity(ACCOUNT, REGION, "alpha-2")).thenReturn(Optional.of(
|
||||
new Connectivity(false, 1_700_000_100_000L, "CLIENT_INITIATED_DISCONNECT", 60, false)));
|
||||
|
||||
assertUnsupported("connectivity.connected:true", "the field connectivity.connected");
|
||||
assertUnsupported("connectivity.clientId:alpha-1", "the field connectivity.clientId");
|
||||
assertUnsupported("connectivity.disconnectReason:CONNECTION_LOST", "the field connectivity.disconnectReason");
|
||||
assertUnsupported("thingName:gamma OR connectivity.connected:false", "the field connectivity.connected");
|
||||
}
|
||||
|
||||
@Test
|
||||
void documentsCarryNoConnectivityWhileConnectivityIsIndexed() {
|
||||
fleet("{\"thingIndexingMode\": \"REGISTRY\", \"thingConnectivityIndexingMode\": \"STATUS\"}");
|
||||
|
||||
assertFalse(document("alpha-1").has("connectivity"));
|
||||
assertEquals(json("{\"thingName\": \"gamma\", \"thingId\": \""
|
||||
+ iot.service.describeThing("gamma", REGION).getThingId() + "\"}"), document("gamma"));
|
||||
assertEquals(List.of("alpha-1"), names("connectivity.connected:true"));
|
||||
assertEquals(List.of("alpha-2", "beta-1", "gamma"), names("connectivity.connected:FALSE"));
|
||||
assertEquals(List.of("alpha-2"), names("connectivity.disconnectReason:client_initiated_disconnect"));
|
||||
assertEquals(List.of("beta-1"), names("connectivity.clientId:beta-1"));
|
||||
assertEquals(json("""
|
||||
{"connected": true, "timestamp": 1700000000000, "keepAliveDuration": 30, "cleanSession": true,
|
||||
"clientId": "alpha-1"}
|
||||
"""), document("alpha-1").get("connectivity"));
|
||||
assertEquals(json("""
|
||||
{"connected": false, "timestamp": 1700000100000, "disconnectReason": "CLIENT_INITIATED_DISCONNECT",
|
||||
"keepAliveDuration": 60, "cleanSession": false, "clientId": "alpha-2"}
|
||||
"""), document("alpha-2").get("connectivity"));
|
||||
assertEquals(json("""
|
||||
{"clientId": "beta-1", "connected": false, "timestamp": 0}
|
||||
"""), document("beta-1").get("connectivity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -921,7 +933,6 @@ class IotFleetIndexingServiceTest {
|
||||
assertUnsupported("shadow.reported.x:1", "the field shadow.reported.x");
|
||||
assertUnsupported("deviceDefender.violationCount:1", "the field deviceDefender.violationCount");
|
||||
assertUnsupported("connectivity.timestamp:0", "the field connectivity.timestamp");
|
||||
assertUnsupported("connectivity.connected:true", "the field connectivity.connected");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1299,7 +1310,7 @@ class IotFleetIndexingServiceTest {
|
||||
|
||||
private void assertSearchBodyFails(String body, String message) {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> service.searchIndex(json(body), REGION), body);
|
||||
() -> service.searchIndex(json(body), ACCOUNT, REGION), body);
|
||||
assertEquals("SerializationException", failure.getErrorCode(), body);
|
||||
assertEquals(400, failure.getHttpStatus(), body);
|
||||
assertEquals(message, failure.getMessage(), body);
|
||||
@@ -1315,12 +1326,12 @@ class IotFleetIndexingServiceTest {
|
||||
iot.service.createThing("alpha-9", Map.of("provider", "acme"), null, "eu-west-1");
|
||||
|
||||
assertEquals(List.of("alpha-1", "alpha-2"), names("attributes.provider:acme"));
|
||||
assertThrows(AwsException.class, () -> service.searchIndex(query("*"), "eu-west-1"));
|
||||
assertThrows(AwsException.class, () -> service.searchIndex(query("*"), ACCOUNT, "eu-west-1"));
|
||||
|
||||
service.updateIndexingConfiguration(json("""
|
||||
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"}}
|
||||
"""), "eu-west-1");
|
||||
List<ObjectNode> other = service.searchIndex(query("attributes.provider:acme"), "eu-west-1").items();
|
||||
List<ObjectNode> other = service.searchIndex(query("attributes.provider:acme"), ACCOUNT, "eu-west-1").items();
|
||||
assertEquals(1, other.size());
|
||||
assertEquals("alpha-9", other.get(0).path("thingName").asText());
|
||||
}
|
||||
|
||||
+25
@@ -209,6 +209,31 @@ class IotMqttBrokerDeviceVerificationTest {
|
||||
assertEquals(device.certificate().getCertificateId(), disconnected.get("principalIdentifier").asText());
|
||||
}
|
||||
|
||||
/**
|
||||
* A TLS session counts in its device certificate's account and region for fleet indexing, not
|
||||
* in the default ones: connected there while live, then how it ended, and nothing elsewhere.
|
||||
*/
|
||||
@Test
|
||||
void aTlsSessionsConnectivityCountsInItsCertificatesAccountAndRegion() throws Exception {
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
RegisteredDevice device = new RegisteredDevice("123456789012", "eu-west-1", registered(deviceLeaf).certificate());
|
||||
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);
|
||||
assertTrue(broker.connectivity("123456789012", "eu-west-1", "sensor-1").orElseThrow().connected());
|
||||
assertTrue(broker.connectivity("000000000000", "us-east-1", "sensor-1").isEmpty());
|
||||
client.disconnect();
|
||||
client.close();
|
||||
publishedEvent("$aws/events/presence/disconnected/sensor-1");
|
||||
|
||||
assertEquals("CLIENT_INITIATED_DISCONNECT",
|
||||
broker.connectivity("123456789012", "eu-west-1", "sensor-1").orElseThrow().disconnectReason());
|
||||
assertTrue(broker.connectivity("000000000000", "us-east-1", "sensor-1").isEmpty());
|
||||
assertTrue(broker.connectivity("123456789012", "us-east-1", "sensor-1").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeniedDeviceIsAnsweredWithConnackNotAuthorized() throws Exception {
|
||||
RegisteredDevice device = registered(deviceLeaf);
|
||||
|
||||
@@ -87,6 +87,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -100,6 +101,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
@@ -1185,6 +1187,190 @@ class IotMqttBrokerServiceTest {
|
||||
verify(current, never()).publish(eq("stale/topic"), any(), any(), anyBoolean(), anyBoolean());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fleet indexing connectivity is per account and region: a plaintext session counts in the
|
||||
* default account, so switching that default stands in for a second account. Account A's
|
||||
* recorded disconnect survives a session of the same client id in account B, while B's session
|
||||
* is live and after it ends.
|
||||
*/
|
||||
@Test
|
||||
void connectivityHistoryOfAClientIdIsKeptPerAccountAndRegion() {
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.defaultAccountId()).thenReturn("111111111111");
|
||||
AtomicReference<Handler<Void>> disconnectInA = new AtomicReference<>();
|
||||
broker.handleEndpoint(endpointCapturing("device-1", disconnectInA, new AtomicReference<>()), false);
|
||||
disconnectInA.get().handle(null);
|
||||
|
||||
when(config.defaultAccountId()).thenReturn("222222222222");
|
||||
AtomicReference<Handler<Void>> closeInB = new AtomicReference<>();
|
||||
broker.handleEndpoint(endpointCapturing("device-1", new AtomicReference<>(), closeInB), false);
|
||||
|
||||
assertEquals("CLIENT_INITIATED_DISCONNECT",
|
||||
broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow().disconnectReason());
|
||||
assertTrue(broker.connectivity("222222222222", "us-east-1", "device-1").orElseThrow().connected());
|
||||
closeInB.get().handle(null);
|
||||
assertEquals("CLIENT_INITIATED_DISCONNECT",
|
||||
broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow().disconnectReason());
|
||||
assertEquals("CONNECTION_LOST",
|
||||
broker.connectivity("222222222222", "us-east-1", "device-1").orElseThrow().disconnectReason());
|
||||
assertTrue(broker.connectivity("111111111111", "eu-west-1", "device-1").isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* A client id names one broker session across accounts and regions: a connection in account B
|
||||
* displaces account A's live session of the same client id, which then reports
|
||||
* DUPLICATE_CLIENTID, also after the displaced connection's close arrives.
|
||||
*/
|
||||
@Test
|
||||
void aSessionDisplacedByTheSameClientIdInAnotherAccountReportsDuplicateClientId() {
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.defaultAccountId()).thenReturn("111111111111");
|
||||
AtomicReference<Handler<Void>> closeInA = new AtomicReference<>();
|
||||
MqttEndpoint inA = endpointCapturing("device-1", new AtomicReference<>(), closeInA);
|
||||
broker.handleEndpoint(inA, false);
|
||||
|
||||
when(config.defaultAccountId()).thenReturn("222222222222");
|
||||
broker.handleEndpoint(endpointCapturing("device-1", new AtomicReference<>(), new AtomicReference<>()), false);
|
||||
|
||||
verify(inA).close();
|
||||
assertFalse(broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow().connected());
|
||||
assertEquals("DUPLICATE_CLIENTID",
|
||||
broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow().disconnectReason());
|
||||
closeInA.get().handle(null);
|
||||
assertEquals("DUPLICATE_CLIENTID",
|
||||
broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow().disconnectReason());
|
||||
assertTrue(broker.connectivity("222222222222", "us-east-1", "device-1").orElseThrow().connected());
|
||||
}
|
||||
|
||||
/**
|
||||
* DeleteConnection ends the session with API_INITIATED_DISCONNECT, the reason AWS gives a
|
||||
* disconnect through that API, also after the close it causes reaches the broker.
|
||||
*/
|
||||
@Test
|
||||
void deleteConnectionEndsTheSessionWithApiInitiatedDisconnect() {
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.defaultAccountId()).thenReturn("111111111111");
|
||||
AtomicReference<Handler<Void>> close = new AtomicReference<>();
|
||||
MqttEndpoint endpoint = endpointCapturing("device-1", new AtomicReference<>(), close);
|
||||
broker.handleEndpoint(endpoint, false);
|
||||
|
||||
assertTrue(broker.disconnectClient("device-1", false));
|
||||
|
||||
verify(endpoint).close();
|
||||
IotMqttBrokerService.Connectivity ended =
|
||||
broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow();
|
||||
assertFalse(ended.connected());
|
||||
assertEquals("API_INITIATED_DISCONNECT", ended.disconnectReason());
|
||||
close.get().handle(null);
|
||||
assertEquals("API_INITIATED_DISCONNECT",
|
||||
broker.connectivity("111111111111", "us-east-1", "device-1").orElseThrow().disconnectReason());
|
||||
assertFalse(broker.disconnectClient("device-1", false));
|
||||
}
|
||||
|
||||
/**
|
||||
* A state reset forgets how sessions ended but keeps a live session connected, and that
|
||||
* session's end after the reset is recorded again.
|
||||
*/
|
||||
@Test
|
||||
void aResetForgetsEndedSessionsButNotLiveOnes() {
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.defaultAccountId()).thenReturn("111111111111");
|
||||
AtomicReference<Handler<Void>> disconnectGone = new AtomicReference<>();
|
||||
broker.handleEndpoint(endpointCapturing("gone", disconnectGone, new AtomicReference<>()), false);
|
||||
disconnectGone.get().handle(null);
|
||||
AtomicReference<Handler<Void>> disconnectLive = new AtomicReference<>();
|
||||
broker.handleEndpoint(endpointCapturing("live", disconnectLive, new AtomicReference<>()), false);
|
||||
|
||||
broker.clear();
|
||||
|
||||
assertTrue(broker.connectivity("111111111111", "us-east-1", "gone").isEmpty());
|
||||
assertTrue(broker.connectivity("111111111111", "us-east-1", "live").orElseThrow().connected());
|
||||
disconnectLive.get().handle(null);
|
||||
assertEquals("CLIENT_INITIATED_DISCONNECT",
|
||||
broker.connectivity("111111111111", "us-east-1", "live").orElseThrow().disconnectReason());
|
||||
}
|
||||
|
||||
/**
|
||||
* A fleet index lookup and a state reset each wait for a session end in flight, held where it
|
||||
* schedules the disconnected event: the lookup then reports API_INITIATED_DISCONNECT rather
|
||||
* than a session that is still connected, and the reset forgets that end rather than having
|
||||
* it written back after the reset.
|
||||
*/
|
||||
@Test
|
||||
void connectivityLookupsAndResetsWaitForASessionEndInFlight() throws Exception {
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.defaultAccountId()).thenReturn("111111111111");
|
||||
when(iotService.get()).thenReturn(mock(IotService.class));
|
||||
|
||||
assertEquals("API_INITIATED_DISCONNECT", duringHeldDeleteConnection(racing ->
|
||||
racing.connectivity("111111111111", "us-east-1", "held").orElseThrow().disconnectReason()));
|
||||
IotMqttBrokerService reset = duringHeldDeleteConnection(racing -> {
|
||||
racing.clear();
|
||||
return racing;
|
||||
});
|
||||
assertTrue(reset.connectivity("111111111111", "us-east-1", "held").isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code during} on another thread while a DeleteConnection of client id {@code held} is
|
||||
* inside its session end, asserts it waits for that end, and returns its result.
|
||||
*/
|
||||
private <T> T duringHeldDeleteConnection(Function<IotMqttBrokerService, T> during) throws Exception {
|
||||
CountDownLatch ending = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Vertx heldVertx = mock(Vertx.class, AdditionalAnswers.delegatesTo(vertx));
|
||||
doAnswer(invocation -> {
|
||||
if (Thread.currentThread() == deletingThread.get()) {
|
||||
ending.countDown();
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
}
|
||||
vertx.runOnContext(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(heldVertx).runOnContext(any());
|
||||
IotMqttBrokerService racing = new IotMqttBrokerService(config, heldVertx, iotService, customAuthorizer, registry);
|
||||
racing.handleEndpoint(endpointCapturing("held", new AtomicReference<>(), new AtomicReference<>()), false);
|
||||
AtomicReference<Thread> duringThread = new AtomicReference<>();
|
||||
ExecutorService deleting = Executors.newSingleThreadExecutor();
|
||||
ExecutorService concurrent = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<Boolean> delete = deleting.submit(() -> {
|
||||
deletingThread.set(Thread.currentThread());
|
||||
return racing.disconnectClient("held", false);
|
||||
});
|
||||
assertTrue(ending.await(10, TimeUnit.SECONDS), "DeleteConnection is ending the session");
|
||||
Future<T> result = concurrent.submit(() -> {
|
||||
duringThread.set(Thread.currentThread());
|
||||
return during.apply(racing);
|
||||
});
|
||||
ThreadStates.awaitBlockedOrDone(duringThread, result);
|
||||
assertFalse(result.isDone(), "waits for the session end in flight");
|
||||
release.countDown();
|
||||
assertTrue(delete.get(10, TimeUnit.SECONDS));
|
||||
return result.get(10, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
release.countDown();
|
||||
deleting.shutdown();
|
||||
concurrent.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private static MqttEndpoint endpointCapturing(String clientId, AtomicReference<Handler<Void>> disconnect,
|
||||
AtomicReference<Handler<Void>> close) {
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
when(endpoint.clientIdentifier()).thenReturn(clientId);
|
||||
when(endpoint.isConnected()).thenReturn(true);
|
||||
when(endpoint.disconnectHandler(any())).thenAnswer(invocation -> {
|
||||
disconnect.set(invocation.getArgument(0));
|
||||
return endpoint;
|
||||
});
|
||||
when(endpoint.closeHandler(any())).thenAnswer(invocation -> {
|
||||
close.set(invocation.getArgument(0));
|
||||
return endpoint;
|
||||
});
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Two publishes from two connections, the first one's rule action held on a latch: the second
|
||||
* publish is fanned out, so its rules were handed over, yet they start only once the first
|
||||
|
||||
Reference in new issue
Block a user