mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -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
@@ -425,6 +425,13 @@ class IotTest {
|
||||
assertThat(plain.attributes()).containsOnly(Map.entry("provider", provider + "1"));
|
||||
for (ThingDocument thing : all) {
|
||||
assertThat(thing.thingId()).isNotBlank();
|
||||
// A thing whose client id never connected, in the shape AWS reports it.
|
||||
assertThat(thing.connectivity().clientId()).isEqualTo(thing.thingName());
|
||||
assertThat(thing.connectivity().connected()).isFalse();
|
||||
assertThat(thing.connectivity().timestamp()).isZero();
|
||||
assertThat(thing.connectivity().disconnectReason()).isNull();
|
||||
assertThat(thing.connectivity().keepAliveDuration()).isNull();
|
||||
assertThat(thing.connectivity().cleanSession()).isNull();
|
||||
}
|
||||
|
||||
awaitSearch("attributes.provider:" + provider + "1", prefix, "a", "b");
|
||||
@@ -437,6 +444,7 @@ class IotTest {
|
||||
awaitSearch("thingName:" + prefix + "* AND NOT attributes.provider:" + provider + "1", prefix, "c");
|
||||
awaitSearch("attributes.provider:" + provider + "?", prefix, "a", "b", "c");
|
||||
awaitSearch("thingGroupNames:" + group, prefix, "a");
|
||||
awaitSearch("connectivity.connected:false AND thingName:" + prefix + "*", prefix, "a", "b", "c");
|
||||
|
||||
Set<String> paged = new TreeSet<>();
|
||||
String nextToken = null;
|
||||
|
||||
+12
-3
@@ -125,7 +125,7 @@ Status: configuration and a bounded SearchIndex subset.
|
||||
- `AND`, `OR` and `NOT` in upper case, their forms `&&`, `||` and `!`, a leading `-` for negation, and parentheses.
|
||||
- Precedence as measured on AWS: `NOT` binds tightest, then `AND`, then `OR`. Whitespace is an `AND` that binds looser than `OR`, so `a OR b c` means `(a OR b) AND c`.
|
||||
|
||||
The fields are `thingName`, `thingId`, `thingTypeName`, `thingGroupNames` (direct memberships) and `attributes.<name>`.
|
||||
The fields are `thingName`, `thingId`, `thingTypeName`, `thingGroupNames` (direct memberships), `attributes.<name>`, `connectivity.connected`, `connectivity.clientId` and `connectivity.disconnectReason`.
|
||||
|
||||
Errors follow AWS, with AWS's messages. The body and member types are checked first, then the member constraints, then the index, then the query, then `nextToken`:
|
||||
|
||||
@@ -143,22 +143,31 @@ Syntax AWS accepts but Floci does not evaluate is refused with `InvalidQueryExce
|
||||
- comparisons (`>`, `<`, `>=`, `<=`)
|
||||
- free text terms without a field, including lower case `and`, `or` and `not`
|
||||
- field grouping (`field:(a OR b)`)
|
||||
- every `connectivity.*`, `shadow.*` and `deviceDefender.*` field once its indexing is on. While that indexing is off the answer is AWS's `InvalidRequestException` above.
|
||||
- every `shadow.*` and `deviceDefender.*` field, and the `connectivity.*` fields Floci does not index (`timestamp`, `keepAliveDuration`, `cleanSession`, `sessionExpiry`, `version`), once its indexing is on. While that indexing is off the answer is AWS's `InvalidRequestException` above.
|
||||
|
||||
Searching `AWS_ThingGroups` is refused with `InvalidRequestException` and `Floci does not support searching AWS_ThingGroups` while that index is enabled. While it is disabled the answer is AWS's `ResourceNotFoundException`.
|
||||
|
||||
Results:
|
||||
|
||||
- A thing has `thingName` and `thingId`, and `thingTypeName`, `thingGroupNames` and `attributes` only when it has them. `shadow` and `deviceDefender` are never returned: Floci keeps no indexed shadow document.
|
||||
- `connectivity` is never returned either. AWS adds it while `thingConnectivityIndexingMode` is `STATUS`, where a thing that never connected shows `connected` `false` and `timestamp` `0`.
|
||||
- Things come in thing name order. AWS does not specify an order.
|
||||
- `maxResults` and `nextToken` page the results. Without `maxResults` every match comes in one page. The token marks the last thing returned, so the next page continues after it even when things before it were deleted, as on AWS. A token continues only the request that issued it: the same `queryString`, and `indexName` and `queryVersion` sent the same way, since an omitted member differs from its explicit default. `maxResults` may change between pages.
|
||||
- An index answers at once: a thing is searchable as soon as it is created, where AWS takes a few seconds.
|
||||
|
||||
`connectivity` is returned while `thingConnectivityIndexingMode` is `STATUS`. It reports the embedded MQTT broker session whose client id is the thing name:
|
||||
|
||||
- Connected: `connected` `true`, `timestamp` (the connect time in epoch milliseconds), `keepAliveDuration`, `cleanSession` and `clientId`.
|
||||
- After the session ended: `connected` `false`, `timestamp` (the disconnect time), `disconnectReason`, `keepAliveDuration`, `cleanSession` and `clientId`. The reason is the one the session's [disconnected lifecycle event](#lifecycle-events) carries.
|
||||
- Never connected: `{"clientId": "<thingName>", "connected": false, "timestamp": 0}`.
|
||||
- A plaintext session, including MQTT over WebSocket, counts in the default account and region, as the broker's shadow topics do. A session on the TLS listener counts in the account and region of its device certificate.
|
||||
- A client id names one broker session across accounts and regions: a connection with the client id of a live session in another account or region displaces it, and the displaced one then reports `DUPLICATE_CLIENTID`.
|
||||
- The state is in memory only. A restart loses it, and a state reset forgets how sessions ended; a live session stays connected.
|
||||
|
||||
Current limitations:
|
||||
|
||||
- `ListIndices` and the statistics and aggregation APIs (`GetStatistics`, `GetCardinality`, `GetPercentiles`, `GetBucketsAggregation`) are not modeled yet.
|
||||
- `customFields` types are not applied to search: attribute values are matched as strings.
|
||||
- `connectivity.sessionExpiry` and the socket information of `filter.connectivity.includeSocketInformation` are not reported.
|
||||
- `managedFields` and `customFields` sent in the thing group configuration are checked (the custom fields for their types only) but not stored: `GetIndexingConfiguration` reports the managed fields the mode selects and no custom fields.
|
||||
|
||||
## MQTT Broker
|
||||
|
||||
@@ -15,15 +15,15 @@ import java.util.regex.Pattern;
|
||||
* The part of the AWS IoT fleet indexing query language Floci evaluates, parsed into a predicate
|
||||
* over a thing's index document. Precedence is the one measured on AWS: NOT binds tightest, then
|
||||
* AND, then OR, and whitespace is an AND looser than OR, so {@code a OR b c} is
|
||||
* {@code (a OR b) AND c}. Values match case-insensitively, field names exactly. Floci evaluates the
|
||||
* registry fields and attributes; connectivity, shadow and Device Defender fields are refused, with
|
||||
* AWS's error while their indexing is off. Syntax AWS accepts but Floci does not evaluate is refused
|
||||
* rather than matching nothing. A query is checked in the order measured on AWS: syntax, then the
|
||||
* 12-term limit, then fields and values, the first such error in the query winning.
|
||||
* {@code (a OR b) AND c}. Values match case-insensitively, field names exactly. Syntax AWS accepts
|
||||
* but Floci does not evaluate is refused rather than matching nothing. A query is checked in the
|
||||
* order measured on AWS: syntax, then the 12-term limit, then fields and values, the first such
|
||||
* error in the query winning.
|
||||
*/
|
||||
final class IotFleetIndexQuery {
|
||||
|
||||
private static final Set<String> FIELDS = Set.of("thingName", "thingId", "thingTypeName", "thingGroupNames");
|
||||
private static final Set<String> FIELDS = Set.of("thingName", "thingId", "thingTypeName", "thingGroupNames",
|
||||
"connectivity.connected", "connectivity.clientId", "connectivity.disconnectReason");
|
||||
private static final String ATTRIBUTES = "attributes.";
|
||||
private static final Set<String> OPERATORS = Set.of("AND", "OR", "NOT", "-", ")");
|
||||
private static final Pattern COMPARISON = Pattern.compile("[<>]");
|
||||
@@ -235,11 +235,11 @@ final class IotFleetIndexQuery {
|
||||
}
|
||||
|
||||
/**
|
||||
* A registry field or attribute passes. One under connectivity, shadow or Device Defender first
|
||||
* needs that indexing on, with AWS's error: a classic shadow field needs REGISTRY_AND_SHADOW, a
|
||||
* named shadow field needs named shadow indexing and a shadow in its filter (otherwise an invalid
|
||||
* field name, as on AWS). Floci then refuses it, since it indexes none of them. Anything else is
|
||||
* the invalid field name AWS reports.
|
||||
* A field Floci indexes passes. One under connectivity, shadow or Device Defender first needs
|
||||
* that indexing on, with AWS's error: a classic shadow field needs REGISTRY_AND_SHADOW, a named
|
||||
* shadow field needs named shadow indexing and a shadow in its filter (otherwise an invalid field
|
||||
* name, as on AWS). Floci then refuses those it does not index. Anything else is the invalid
|
||||
* field name AWS reports.
|
||||
*/
|
||||
private void checkField(String field) {
|
||||
if (field.startsWith(ATTRIBUTES) && field.length() > ATTRIBUTES.length()) {
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ public class IotFleetIndexingController {
|
||||
@Path("/indices/search")
|
||||
public Response searchIndex(@Context HttpHeaders headers, String body) {
|
||||
IotService.Page<ObjectNode> page = fleetIndexingService.searchIndex(IotRequestBody.read(objectMapper, body),
|
||||
regionResolver.resolveRegion(headers));
|
||||
regionResolver.getAccountId(), regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.putArray("things").addAll(page.items());
|
||||
if (page.nextToken() != null) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
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;
|
||||
@@ -98,18 +99,22 @@ public class IotFleetIndexingService {
|
||||
|
||||
private final StorageBackend<String, IotIndexingConfiguration> store;
|
||||
private final IotService iotService;
|
||||
private final IotMqttBrokerService mqttBrokerService;
|
||||
/** Guards the read-modify-write of an update that changes only one of the two configurations. */
|
||||
private final Object lock = new Object();
|
||||
|
||||
@Inject
|
||||
public IotFleetIndexingService(StorageFactory storageFactory, IotService iotService) {
|
||||
public IotFleetIndexingService(StorageFactory storageFactory, IotService iotService,
|
||||
IotMqttBrokerService mqttBrokerService) {
|
||||
this(storageFactory.create("iot", "iot-indexing-configuration.json",
|
||||
new TypeReference<Map<String, IotIndexingConfiguration>>() {}), iotService);
|
||||
new TypeReference<Map<String, IotIndexingConfiguration>>() {}), iotService, mqttBrokerService);
|
||||
}
|
||||
|
||||
IotFleetIndexingService(StorageBackend<String, IotIndexingConfiguration> store, IotService iotService) {
|
||||
IotFleetIndexingService(StorageBackend<String, IotIndexingConfiguration> store, IotService iotService,
|
||||
IotMqttBrokerService mqttBrokerService) {
|
||||
this.store = store;
|
||||
this.iotService = iotService;
|
||||
this.mqttBrokerService = mqttBrokerService;
|
||||
}
|
||||
|
||||
public void updateIndexingConfiguration(JsonNode request, String region) {
|
||||
@@ -167,7 +172,7 @@ public class IotFleetIndexingService {
|
||||
* and version as sent) and the last thing returned, so a page continues after that thing
|
||||
* whatever was deleted before it. It also carries a checksum, so an edited token is invalid.
|
||||
*/
|
||||
public IotService.Page<ObjectNode> searchIndex(JsonNode request, String region) {
|
||||
public IotService.Page<ObjectNode> searchIndex(JsonNode request, String accountId, String region) {
|
||||
if (!request.isObject()) {
|
||||
throw serializationError("request body", JsonNodeType.OBJECT);
|
||||
}
|
||||
@@ -216,6 +221,7 @@ public class IotFleetIndexingService {
|
||||
Predicate<JsonNode> query = IotFleetIndexQuery.parse(queryString, indexing);
|
||||
String parameters = pageParameters(requestedIndexName, queryVersion, queryString);
|
||||
String after = pageAfter(nextToken, parameters);
|
||||
boolean connectivityIndexed = "STATUS".equals(indexing.thingConnectivityIndexingMode());
|
||||
Map<String, List<String>> thingGroupNames = thingGroupNames(region);
|
||||
List<ObjectNode> matches = new ArrayList<>();
|
||||
for (Thing thing : iotService.listThings(region)) {
|
||||
@@ -224,6 +230,12 @@ public class IotFleetIndexingService {
|
||||
continue;
|
||||
}
|
||||
ObjectNode document = document(thing, thingGroupNames.getOrDefault(thingName, List.of()));
|
||||
if (connectivityIndexed) {
|
||||
document.set("connectivity", mqttBrokerService.connectivity(accountId, region, thingName)
|
||||
.map(state -> connectivity(state, thingName))
|
||||
.orElseGet(() -> JsonNodeFactory.instance.objectNode()
|
||||
.put("clientId", thingName).put("connected", false).put("timestamp", 0)));
|
||||
}
|
||||
if (query.test(document)) {
|
||||
matches.add(document);
|
||||
if (matches.size() > pageSize) {
|
||||
@@ -306,6 +318,18 @@ public class IotFleetIndexingService {
|
||||
return document;
|
||||
}
|
||||
|
||||
private static ObjectNode connectivity(Connectivity state, String clientId) {
|
||||
ObjectNode connectivity = JsonNodeFactory.instance.objectNode()
|
||||
.put("connected", state.connected())
|
||||
.put("timestamp", state.timestamp());
|
||||
if (state.disconnectReason() != null) {
|
||||
connectivity.put("disconnectReason", state.disconnectReason());
|
||||
}
|
||||
return connectivity.put("keepAliveDuration", state.keepAliveDuration())
|
||||
.put("cleanSession", state.cleanSession())
|
||||
.put("clientId", clientId);
|
||||
}
|
||||
|
||||
/** The schema of the named index, null while it is disabled. */
|
||||
private static String schema(String indexName, IotIndexingConfiguration configuration) {
|
||||
return switch (indexName) {
|
||||
|
||||
@@ -123,8 +123,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
static final String CONNECTION_LOST = "CONNECTION_LOST";
|
||||
static final String MQTT_KEEP_ALIVE_TIMEOUT = "MQTT_KEEP_ALIVE_TIMEOUT";
|
||||
static final String PRESENCE_TOPIC_PREFIX = "$aws/events/presence/";
|
||||
private static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID";
|
||||
private static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT";
|
||||
static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID";
|
||||
static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT";
|
||||
private static final String CLIENT_ERROR = "CLIENT_ERROR";
|
||||
private static final long KEEP_ALIVE_SLACK_NANOS = TimeUnit.MILLISECONDS.toNanos(250);
|
||||
|
||||
@@ -145,6 +145,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
private final Object sessionLock = new Object();
|
||||
/** The last lifecycle event versionNumber per client id; neither a state reset nor a broker restart clears it. */
|
||||
private final Map<String, Long> presenceVersions = new ConcurrentHashMap<>();
|
||||
/** How a client id's last session in an account and region ended, for fleet indexing; a state reset clears it. */
|
||||
private final Map<HistoryKey, Connectivity> lastDisconnects = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger pendingRuleEvaluations = new AtomicInteger();
|
||||
private final AtomicBoolean ruleEvaluationsThrottled = new AtomicBoolean();
|
||||
/**
|
||||
@@ -219,11 +221,14 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* The broker keeps nothing in Floci storage; a reset only suspends rules, in
|
||||
* {@link #beforeReset()}.
|
||||
* The broker keeps nothing in Floci storage; a reset forgets how earlier sessions ended, and
|
||||
* suspends rules in {@link #beforeReset()}. Live sessions stay connected.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
synchronized (sessionLock) {
|
||||
lastDisconnects.clear();
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void startIfEnabled() {
|
||||
@@ -405,6 +410,25 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return Optional.of(new ConnectionInfo(session.clientId(), session.sourceIp(), session.sourcePort()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A client id's connection as fleet indexing reports it in an account and region: its live
|
||||
* session, else how its last one ended. Empty when it has not connected there since the last
|
||||
* reset. A plaintext session counts in the default account and region, as the broker's shadow
|
||||
* topics do; a TLS session in its certificate's. Read under the session lock, so a session
|
||||
* being ended is never reported connected after its disconnect is recorded; the lock is never
|
||||
* held across endpoint calls, so liveness is the session's own ended flag.
|
||||
*/
|
||||
Optional<Connectivity> connectivity(String accountId, String region, String clientId) {
|
||||
synchronized (sessionLock) {
|
||||
ClientSession session = sessionsByClient.get(clientId);
|
||||
if (session != null && !session.ended().get()
|
||||
&& accountId.equals(session.accountId()) && region.equals(session.region())) {
|
||||
return Optional.of(session.connected());
|
||||
}
|
||||
return Optional.ofNullable(lastDisconnects.get(new HistoryKey(accountId, region, clientId)));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> listSubscriptions(String clientId) {
|
||||
return subscriptionsByClient.getOrDefault(clientId, Map.of()).keySet().stream()
|
||||
.sorted()
|
||||
@@ -425,10 +449,10 @@ public class IotMqttBrokerService implements Resettable {
|
||||
SocketAddress remoteAddress = endpoint.remoteAddress();
|
||||
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
|
||||
int sourcePort = remoteAddress == null ? -1 : remoteAddress.port();
|
||||
String principal = null;
|
||||
IotService.RegisteredDevice device = null;
|
||||
if (verifyDevice) {
|
||||
principal = admittedDevice(endpoint, clientId, sourceIp);
|
||||
if (principal == null) {
|
||||
device = admittedDevice(endpoint, clientId, sourceIp);
|
||||
if (device == null) {
|
||||
endpoint.reject(endpoint.protocolVersion() == 5
|
||||
? MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED_5
|
||||
: MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
|
||||
@@ -447,7 +471,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return;
|
||||
}
|
||||
}
|
||||
admit(endpoint, principal, sourceIp, sourcePort, connectNanos);
|
||||
admit(endpoint, device, sourceIp, sourcePort, connectNanos);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -489,15 +513,18 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code principal} is the certificate id a TLS client was admitted with, null otherwise.
|
||||
* {@code device} is the registered device a TLS client was admitted as, null otherwise; its
|
||||
* certificate id is the session's principal, and its account and region the session's.
|
||||
* {@code clientIp} and {@code clientPort} are the address the client connected from: the
|
||||
* socket's, or for a WebSocket client the one the bridge recorded at the upgrade, as the
|
||||
* bridge's own socket is loopback. {@code connectNanos} is when the CONNECT arrived, which
|
||||
* the keep-alive runs from.
|
||||
*/
|
||||
private void admit(MqttEndpoint endpoint, String principal, String clientIp, int clientPort, long connectNanos) {
|
||||
private void admit(MqttEndpoint endpoint, IotService.RegisteredDevice device, String clientIp, int clientPort,
|
||||
long connectNanos) {
|
||||
String clientId = endpoint.clientIdentifier();
|
||||
boolean cleanSession = endpoint.isCleanSession();
|
||||
String principal = device == null ? null : device.certificate().getCertificateId();
|
||||
ClientSession session;
|
||||
ClientSession replaced = null;
|
||||
synchronized (sessionLock) {
|
||||
@@ -512,7 +539,11 @@ public class IotMqttBrokerService implements Resettable {
|
||||
principal,
|
||||
versionNumber,
|
||||
new AtomicBoolean(),
|
||||
new AtomicLong(connectNanos));
|
||||
new AtomicLong(connectNanos),
|
||||
device == null ? config.defaultAccountId() : device.accountId(),
|
||||
device == null ? config.defaultRegion() : device.region(),
|
||||
System.currentTimeMillis(),
|
||||
endpoint.keepAliveTimeSeconds());
|
||||
ClientSession previous = sessionsByClient.put(clientId, session);
|
||||
if (previous != null && previous.endpoint() != endpoint) {
|
||||
endSession(previous, DUPLICATE_CLIENTID);
|
||||
@@ -553,12 +584,12 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* The certificate id of the device behind the connection when it may connect, otherwise null.
|
||||
* The registered device behind the connection when it may connect, otherwise null.
|
||||
* A failure while deciding refuses the client rather than leaving the CONNECT unanswered. A
|
||||
* refusal is the client's own doing and reaches it as the CONNACK, so it is logged at debug
|
||||
* only: the CONNECT is reachable by anyone.
|
||||
*/
|
||||
private String admittedDevice(MqttEndpoint endpoint, String clientId, String sourceIp) {
|
||||
private IotService.RegisteredDevice admittedDevice(MqttEndpoint endpoint, String clientId, String sourceIp) {
|
||||
try {
|
||||
Optional<IotService.RegisteredDevice> device = presentedDevice(endpoint);
|
||||
if (device.isEmpty()) {
|
||||
@@ -570,7 +601,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateId);
|
||||
return null;
|
||||
}
|
||||
return certificateId;
|
||||
return device.get();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "IoT MQTT TLS client {0} refused: device verification failed: {1}", clientId, e.getMessage());
|
||||
return null;
|
||||
@@ -784,14 +815,16 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
/**
|
||||
* Ends the session once: the first reason reported wins, and only that one publishes the
|
||||
* disconnected event and gets true. The versionNumber counts up only while the session is still
|
||||
* the client id's current one, so a session replaced by a newer connection leaves it alone.
|
||||
* disconnected event, records how the session ended for fleet indexing, and gets true. The
|
||||
* versionNumber counts up only while the session is still the client id's current one, so a
|
||||
* session replaced by a newer connection leaves it alone.
|
||||
*/
|
||||
private boolean endSession(ClientSession session, String reason) {
|
||||
synchronized (sessionLock) {
|
||||
if (!session.ended().compareAndSet(false, true)) {
|
||||
return false;
|
||||
}
|
||||
lastDisconnects.put(session.historyKey(), session.disconnected(reason));
|
||||
if (sessionsByClient.remove(session.clientId(), session)) {
|
||||
presenceVersions.computeIfPresent(session.clientId(), (id, version) -> version + 1);
|
||||
}
|
||||
@@ -906,7 +939,26 @@ public class IotMqttBrokerService implements Resettable {
|
||||
String principalIdentifier,
|
||||
long versionNumber,
|
||||
AtomicBoolean ended,
|
||||
AtomicLong lastPacketNanos) {
|
||||
AtomicLong lastPacketNanos,
|
||||
String accountId,
|
||||
String region,
|
||||
long connectedAt,
|
||||
int keepAliveDuration) {
|
||||
|
||||
HistoryKey historyKey() {
|
||||
return new HistoryKey(accountId, region, clientId);
|
||||
}
|
||||
|
||||
Connectivity connected() {
|
||||
return new Connectivity(true, connectedAt, null, keepAliveDuration, cleanSession);
|
||||
}
|
||||
|
||||
Connectivity disconnected(String reason) {
|
||||
return new Connectivity(false, System.currentTimeMillis(), reason, keepAliveDuration, cleanSession);
|
||||
}
|
||||
}
|
||||
|
||||
private record HistoryKey(String accountId, String region, String clientId) {
|
||||
}
|
||||
|
||||
private record Subscription(String topicFilter, int qos) {
|
||||
@@ -914,4 +966,9 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
record ConnectionInfo(String clientId, String address, int port) {
|
||||
}
|
||||
|
||||
/** Timestamps are epoch milliseconds: the connect while connected, the disconnect after. */
|
||||
record Connectivity(boolean connected, long timestamp, String disconnectReason, int keepAliveDuration,
|
||||
boolean cleanSession) {
|
||||
}
|
||||
}
|
||||
+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