mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
feat(iot): search thing groups in the AWS_ThingGroups index (#10006)
This commit is contained in:
1 parent
5470b03f4b
commit
c633ae21cd
6 files changed
+318
-74
No files matched your search
@@ -125,15 +125,15 @@ With connectivity indexing set to `STATUS`, `POST /things/{thingName}/connectivi
|
||||
|
||||
### SearchIndex
|
||||
|
||||
`SearchIndex` (`POST /indices/search`) searches the things of the caller's account and region in the `AWS_Things` index, the default index name. Floci evaluates this part of the query language:
|
||||
`SearchIndex` (`POST /indices/search`) searches the things of the caller's account and region in the `AWS_Things` index, the default index name, or their thing groups in `AWS_ThingGroups`. Floci evaluates this part of the query language:
|
||||
|
||||
- `field:value`. Values match case-insensitively, field names exactly: `attributes.Site:north` matches nothing when the attribute is named `site`.
|
||||
- `*` (any run of characters) and `?` (one character) inside a value, and `\` to escape one character. A quoted value such as `thingName:"x"` matches literally.
|
||||
- `field:*` matches the things that have the field. A bare `*` matches every thing.
|
||||
- `field:*` matches the documents that have the field. A bare `*` matches every document of the searched index.
|
||||
- `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), `attributes.<name>`, `connectivity.connected`, `connectivity.clientId` and `connectivity.disconnectReason`.
|
||||
The fields of `AWS_Things` are `thingName`, `thingId`, `thingTypeName`, `thingGroupNames` (direct memberships), `attributes.<name>`, `connectivity.connected`, `connectivity.clientId` and `connectivity.disconnectReason`. The fields of `AWS_ThingGroups` are the members of a thing group document: `thingGroupName`, `thingGroupId`, `thingGroupDescription`, `parentGroupNames` and `attributes.<name>`. A field that belongs to the other index is the invalid field name AWS reports.
|
||||
|
||||
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`:
|
||||
|
||||
@@ -153,14 +153,15 @@ Syntax AWS accepts but Floci does not evaluate is refused with `InvalidQueryExce
|
||||
- field grouping (`field:(a OR b)`)
|
||||
- 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`.
|
||||
A search of `AWS_ThingGroups` reports the caller's thing groups in the `thingGroups` member AWS names for that index, and never fills `things`; a search of `AWS_Things` is the other way round. `shadow.*`, `deviceDefender.*` and `connectivity.*` are not fields of a group document, so there they are the invalid field name rather than the errors above. While the index 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.
|
||||
- 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.
|
||||
- A thing group has `thingGroupName` and `thingGroupId`, and `thingGroupDescription` and `attributes`, both read from its `thingGroupProperties`, only when it has them. `parentGroupNames` is never returned: Floci models static groups, so no group has a parent.
|
||||
- Things and thing groups come in their own 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 document returned, so the next page continues after it even when documents 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 or a thing group 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:
|
||||
|
||||
|
||||
@@ -13,9 +13,10 @@ import java.util.regex.Matcher;
|
||||
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
|
||||
* The part of the AWS IoT fleet indexing query language Floci evaluates, parsed into a predicate over
|
||||
* an index document. A query over AWS_Things is checked against that index's fields, one over
|
||||
* AWS_ThingGroups against the fields of a group 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. 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
|
||||
@@ -25,6 +26,9 @@ final class IotFleetIndexQuery {
|
||||
|
||||
private static final Set<String> FIELDS = Set.of("thingName", "thingId", "thingTypeName", "thingGroupNames",
|
||||
"connectivity.connected", "connectivity.clientId", "connectivity.disconnectReason");
|
||||
/** The searchable fields of a thing group document, as AWS returns them in a SearchIndex response. */
|
||||
private static final Set<String> THING_GROUP_FIELDS = Set.of("thingGroupName", "thingGroupId",
|
||||
"thingGroupDescription", "parentGroupNames");
|
||||
private static final String ATTRIBUTES = "attributes.";
|
||||
private static final Set<String> OPERATORS = Set.of("AND", "OR", "NOT", "-", ")");
|
||||
private static final Pattern COMPARISON = Pattern.compile("[<>]");
|
||||
@@ -36,19 +40,29 @@ final class IotFleetIndexQuery {
|
||||
|
||||
private final String queryString;
|
||||
private final ThingIndexing indexing;
|
||||
private final boolean thingGroups;
|
||||
private final List<String> tokens;
|
||||
private int position;
|
||||
private int terms;
|
||||
private AwsException deferred;
|
||||
|
||||
private IotFleetIndexQuery(String queryString, ThingIndexing indexing) {
|
||||
private IotFleetIndexQuery(String queryString, ThingIndexing indexing, boolean thingGroups) {
|
||||
this.queryString = queryString;
|
||||
this.indexing = indexing;
|
||||
this.thingGroups = thingGroups;
|
||||
this.tokens = tokenize();
|
||||
}
|
||||
|
||||
static Predicate<JsonNode> parse(String queryString, ThingIndexing indexing) {
|
||||
IotFleetIndexQuery parser = new IotFleetIndexQuery(queryString, indexing);
|
||||
return parse(new IotFleetIndexQuery(queryString, indexing, false));
|
||||
}
|
||||
|
||||
/** A query over AWS_ThingGroups, whose documents hold only the fields of the group itself. */
|
||||
static Predicate<JsonNode> parseThingGroups(String queryString) {
|
||||
return parse(new IotFleetIndexQuery(queryString, null, true));
|
||||
}
|
||||
|
||||
private static Predicate<JsonNode> parse(IotFleetIndexQuery parser) {
|
||||
Predicate<JsonNode> query = parser.clauses();
|
||||
if (parser.position < parser.tokens.size()) {
|
||||
throw parser.syntaxError();
|
||||
@@ -236,16 +250,22 @@ final class IotFleetIndexQuery {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* A field the searched index has passes. In AWS_Things, 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, in either index.
|
||||
*/
|
||||
private void checkField(String field) {
|
||||
if (field.startsWith(ATTRIBUTES) && field.length() > ATTRIBUTES.length()) {
|
||||
return;
|
||||
}
|
||||
if (thingGroups) {
|
||||
if (!THING_GROUP_FIELDS.contains(field)) {
|
||||
throw parseError("invalid field name, field name: " + field);
|
||||
}
|
||||
return;
|
||||
}
|
||||
String attribute;
|
||||
boolean enabled;
|
||||
if (field.startsWith("connectivity.")) {
|
||||
|
||||
@@ -107,10 +107,11 @@ public class IotFleetIndexingController {
|
||||
@POST
|
||||
@Path("/indices/search")
|
||||
public Response searchIndex(@Context HttpHeaders headers, String body) {
|
||||
IotService.Page<ObjectNode> page = fleetIndexingService.searchIndex(IotRequestBody.read(objectMapper, body),
|
||||
regionResolver.getAccountId(), regionResolver.resolveRegion(headers));
|
||||
IotFleetIndexingService.SearchPage page = fleetIndexingService.searchIndex(
|
||||
IotRequestBody.read(objectMapper, body), regionResolver.getAccountId(),
|
||||
regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.putArray("things").addAll(page.items());
|
||||
response.putArray(page.member()).addAll(page.items());
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
|
||||
@@ -189,14 +189,15 @@ public class IotFleetIndexingService {
|
||||
}
|
||||
|
||||
/**
|
||||
* SearchIndex over the things of the caller's account and region, in thing name order. A
|
||||
* request is checked in the order measured on AWS: the body and member types, member
|
||||
* constraints, an empty index name, the query version, an unknown or disabled index, the query,
|
||||
* then the page token. The token names the request it continues (its query string, index name
|
||||
* 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.
|
||||
* SearchIndex over the things or the thing groups of the caller's account and region, in name order
|
||||
* and under the member AWS names the hits of that index in. A request is checked in the order
|
||||
* measured on AWS: the body and member types, member constraints, an empty index name, the query
|
||||
* version, an unknown or disabled index, the query, then the page token. The token names the request
|
||||
* it continues (its query string, index name and version as sent) and the last item returned, so a
|
||||
* page continues after that item whatever was deleted before it. It also carries a checksum, so an
|
||||
* edited token is invalid.
|
||||
*/
|
||||
public IotService.Page<ObjectNode> searchIndex(JsonNode request, String accountId, String region) {
|
||||
public SearchPage searchIndex(JsonNode request, String accountId, String region) {
|
||||
requireObject(request);
|
||||
String queryString = text(request.path("queryString"), "queryString");
|
||||
JsonNode maxResults = request.path("maxResults");
|
||||
@@ -235,41 +236,76 @@ public class IotFleetIndexingService {
|
||||
throw new AwsException("ResourceNotFoundException", "Index " + indexName
|
||||
+ " does not exist. Please enable index by calling UpdateIndexingConfiguration", 404);
|
||||
}
|
||||
if (THING_GROUPS_INDEX.equals(indexName)) {
|
||||
// ponytail: thing group documents are not modeled; refusing beats an empty result.
|
||||
throw invalid("Floci does not support searching AWS_ThingGroups");
|
||||
}
|
||||
ThingIndexing indexing = configuration.thing();
|
||||
Predicate<JsonNode> query = IotFleetIndexQuery.parse(queryString, indexing);
|
||||
boolean thingGroups = THING_GROUPS_INDEX.equals(indexName);
|
||||
Predicate<JsonNode> query = thingGroups ? IotFleetIndexQuery.parseThingGroups(queryString)
|
||||
: IotFleetIndexQuery.parse(queryString, configuration.thing());
|
||||
String parameters = pageParameters(requestedIndexName, queryVersion, queryString);
|
||||
String after = pageAfter(nextToken, parameters);
|
||||
String nameField = thingGroups ? "thingGroupName" : "thingName";
|
||||
String member = thingGroups ? "thingGroups" : "things";
|
||||
Stream<ObjectNode> documents = thingGroups ? thingGroupDocuments(region, after)
|
||||
: thingDocuments(accountId, region, configuration.thing(), after);
|
||||
List<ObjectNode> matches = documents.filter(query).limit((long) pageSize + 1).toList();
|
||||
if (matches.size() <= pageSize) {
|
||||
return new SearchPage(member, matches, null);
|
||||
}
|
||||
matches = new ArrayList<>(matches);
|
||||
matches.removeLast();
|
||||
return new SearchPage(member, matches,
|
||||
pageToken(parameters, JsonNodes.asText(matches.getLast().path(nameField))));
|
||||
}
|
||||
|
||||
/** A SearchIndex page: its items, the member AWS returns them in, and the token for the next page. */
|
||||
public record SearchPage(String member, List<ObjectNode> items, String nextToken) {
|
||||
}
|
||||
|
||||
/** The AWS_Things of the page cursor onwards, in name order, with connectivity while it is indexed. */
|
||||
private Stream<ObjectNode> thingDocuments(String accountId, String region, ThingIndexing indexing, String after) {
|
||||
boolean connectivityIndexed = "STATUS".equals(indexing.thingConnectivityIndexingMode());
|
||||
Map<String, List<String>> thingGroupNames = thingGroupNames(region);
|
||||
List<ObjectNode> matches = new ArrayList<>();
|
||||
for (Thing thing : iotService.listThings(region)) {
|
||||
String thingName = thing.getThingName();
|
||||
if (after != null && thingName.compareTo(after) <= 0) {
|
||||
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) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return iotService.listThings(region).stream()
|
||||
.filter(thing -> afterCursor(thing.getThingName(), after))
|
||||
.map(thing -> {
|
||||
String thingName = thing.getThingName();
|
||||
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)));
|
||||
}
|
||||
return document;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The AWS_ThingGroups of the page cursor onwards, in name order. Floci models static groups only,
|
||||
* so no group has a parent and no document carries {@code parentGroupNames}.
|
||||
*/
|
||||
private Stream<ObjectNode> thingGroupDocuments(String region, String after) {
|
||||
return iotService.listThingGroups(region, null, null).items().stream()
|
||||
.filter(group -> afterCursor(group.getThingGroupName(), after))
|
||||
.map(IotFleetIndexingService::groupDocument);
|
||||
}
|
||||
|
||||
/** Whether a name continues the page, so the items a token skips never cost a document. */
|
||||
private static boolean afterCursor(String name, String after) {
|
||||
return after == null || name.compareTo(after) > 0;
|
||||
}
|
||||
|
||||
/** A group's index document; like AWS it leaves out a member the group does not have. */
|
||||
private static ObjectNode groupDocument(IotThingGroup group) {
|
||||
ObjectNode document = JsonNodeFactory.instance.objectNode()
|
||||
.put("thingGroupName", group.getThingGroupName())
|
||||
.put("thingGroupId", group.getThingGroupId());
|
||||
if (group.getDescription() != null && !group.getDescription().isEmpty()) {
|
||||
document.put("thingGroupDescription", group.getDescription());
|
||||
}
|
||||
if (matches.size() <= pageSize) {
|
||||
return new IotService.Page<>(matches, null);
|
||||
if (!group.getAttributes().isEmpty()) {
|
||||
ObjectNode attributes = document.putObject("attributes");
|
||||
group.getAttributes().forEach(attributes::put);
|
||||
}
|
||||
matches.removeLast();
|
||||
return new IotService.Page<>(matches, pageToken(parameters, JsonNodes.asText(matches.getLast().path("thingName"))));
|
||||
return document;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -282,7 +318,7 @@ public class IotFleetIndexingService {
|
||||
.getBytes(StandardCharsets.UTF_8)).toString();
|
||||
}
|
||||
|
||||
/** The thing name a page token continues after, null for the first page. */
|
||||
/** The name a page token continues after, null for the first page. */
|
||||
private static String pageAfter(String nextToken, String parameters) {
|
||||
if (nextToken == null) {
|
||||
return null;
|
||||
@@ -302,13 +338,13 @@ public class IotFleetIndexingService {
|
||||
return token.group(3);
|
||||
}
|
||||
|
||||
private static String pageToken(String parameters, String thingName) {
|
||||
return Base64Url.encode(parameters + pageCheck(parameters, thingName) + thingName);
|
||||
private static String pageToken(String parameters, String cursor) {
|
||||
return Base64Url.encode(parameters + pageCheck(parameters, cursor) + cursor);
|
||||
}
|
||||
|
||||
/** A checksum of a token's parameters and cursor, so an edited or truncated token is invalid, as on AWS. */
|
||||
private static String pageCheck(String parameters, String thingName) {
|
||||
return UUID.nameUUIDFromBytes((parameters + thingName).getBytes(StandardCharsets.UTF_8)).toString();
|
||||
private static String pageCheck(String parameters, String cursor) {
|
||||
return UUID.nameUUIDFromBytes((parameters + cursor).getBytes(StandardCharsets.UTF_8)).toString();
|
||||
}
|
||||
|
||||
/** The thing groups each thing of the region is a direct member of, in group name order. */
|
||||
|
||||
@@ -17,6 +17,7 @@ import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
@@ -456,9 +457,69 @@ class IotFleetIndexingIntegrationTest {
|
||||
search(auth, """
|
||||
{"queryString": "*", "indexName": "AWS_ThingGroups"}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("thingGroups", empty())
|
||||
.body("$", not(hasKey("things")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The thing group index as the SDKs see it: the groups of the caller's account and region come in
|
||||
* {@code thingGroups} in group name order, with only the members a group has, and a page continues
|
||||
* after the group it stopped at.
|
||||
*/
|
||||
@Test
|
||||
void searchOfThingGroupsReturnsTheGroupsOfTheCallersAccount() {
|
||||
String auth = auth("111100000012", "us-east-1");
|
||||
update(auth, """
|
||||
{"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "ON"}}
|
||||
""");
|
||||
post(auth, "/thing-groups/release", """
|
||||
{"thingGroupProperties": {"thingGroupDescription": "canary releases",
|
||||
"attributePayload": {"attributes": {"release_channel": "stable"}}}}
|
||||
""");
|
||||
post(auth, "/thing-groups/stable", "{}");
|
||||
|
||||
search(auth, """
|
||||
{"queryString": "*", "indexName": "AWS_ThingGroups"}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("thingGroups", hasSize(2))
|
||||
.body("thingGroups.thingGroupName", contains("release", "stable"))
|
||||
.body("thingGroups[0].thingGroupId", notNullValue())
|
||||
.body("thingGroups[0].thingGroupDescription", equalTo("canary releases"))
|
||||
.body("thingGroups[0].attributes.release_channel", equalTo("stable"))
|
||||
.body("thingGroups[1].thingGroupId", notNullValue())
|
||||
.body("thingGroups[1]", not(hasKey("thingGroupDescription")))
|
||||
.body("thingGroups[1]", not(hasKey("attributes")));
|
||||
|
||||
search(auth, """
|
||||
{"queryString": "attributes.release_channel:stable", "indexName": "AWS_ThingGroups"}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("thingGroups.thingGroupName", contains("release"));
|
||||
|
||||
String token = search(auth, """
|
||||
{"queryString": "thingGroupName:*", "indexName": "AWS_ThingGroups", "maxResults": 1}
|
||||
""")
|
||||
.statusCode(200)
|
||||
.body("thingGroups.thingGroupName", contains("release"))
|
||||
.body("nextToken", notNullValue())
|
||||
.extract().jsonPath().getString("nextToken");
|
||||
search(auth, """
|
||||
{"queryString": "thingGroupName:*", "indexName": "AWS_ThingGroups", "maxResults": 1,
|
||||
"nextToken": "%s"}
|
||||
""".formatted(token))
|
||||
.statusCode(200)
|
||||
.body("thingGroups.thingGroupName", contains("stable"))
|
||||
.body("nextToken", nullValue());
|
||||
|
||||
search(auth, """
|
||||
{"queryString": "thingName:any", "indexName": "AWS_ThingGroups"}
|
||||
""")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"))
|
||||
.body("message", equalTo("Floci does not support searching AWS_ThingGroups"));
|
||||
.body("__type", equalTo("InvalidQueryException"))
|
||||
.body("message", equalTo("Unable to parse query, invalid field name, field name: thingName, "
|
||||
+ "query string: thingName:any"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -38,6 +38,9 @@ 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.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IotFleetIndexingServiceTest {
|
||||
@@ -718,6 +721,24 @@ class IotFleetIndexingServiceTest {
|
||||
registry.addThingToThingGroup("north-group", "alpha-2", REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* The group index enabled over three groups, one per member AWS gives a group document: attributes
|
||||
* only, nothing but a name, and a description with an attribute.
|
||||
*/
|
||||
private void indexGroups() {
|
||||
update("""
|
||||
{"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "ON"}}
|
||||
""");
|
||||
iot.service.createThingGroup("north-group", json("""
|
||||
{"attributePayload": {"attributes": {"site": "north"}}}
|
||||
"""), REGION);
|
||||
iot.service.createThingGroup("south-group", mapper.createObjectNode(), REGION);
|
||||
iot.service.createThingGroup("release", json("""
|
||||
{"thingGroupDescription": "canary releases",
|
||||
"attributePayload": {"attributes": {"release_channel": "stable"}}}
|
||||
"""), REGION);
|
||||
}
|
||||
|
||||
private void fleet() {
|
||||
fleet("{\"thingIndexingMode\": \"REGISTRY\"}");
|
||||
}
|
||||
@@ -726,7 +747,7 @@ class IotFleetIndexingServiceTest {
|
||||
return mapper.createObjectNode().put("queryString", queryString);
|
||||
}
|
||||
|
||||
private IotService.Page<ObjectNode> search(ObjectNode request) {
|
||||
private IotFleetIndexingService.SearchPage search(ObjectNode request) {
|
||||
return service.searchIndex(request, ACCOUNT, REGION);
|
||||
}
|
||||
|
||||
@@ -734,6 +755,15 @@ class IotFleetIndexingServiceTest {
|
||||
return search(query(queryString)).items().stream().map(thing -> thing.path("thingName").asString()).toList();
|
||||
}
|
||||
|
||||
/** A search of the thing group index. */
|
||||
private ObjectNode groups(String queryString) {
|
||||
return query(queryString).put("indexName", "AWS_ThingGroups");
|
||||
}
|
||||
|
||||
private static List<String> groupNames(IotFleetIndexingService.SearchPage page) {
|
||||
return page.items().stream().map(group -> group.path("thingGroupName").asString()).toList();
|
||||
}
|
||||
|
||||
private ObjectNode document(String thingName) {
|
||||
List<ObjectNode> things = search(query("thingName:" + thingName)).items();
|
||||
assertEquals(1, things.size());
|
||||
@@ -869,6 +899,21 @@ class IotFleetIndexingServiceTest {
|
||||
"""), document("beta-1").get("connectivity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLaterPageAsksTheBrokerOnlyForThingsAfterItsCursor() {
|
||||
fleet("{\"thingIndexingMode\": \"REGISTRY\", \"thingConnectivityIndexingMode\": \"STATUS\"}");
|
||||
String afterAlpha = search(query("*").put("maxResults", 1)).nextToken();
|
||||
|
||||
reset(broker);
|
||||
assertEquals(List.of("alpha-2", "beta-1", "gamma"),
|
||||
thingNames(search(query("*").put("maxResults", Integer.MAX_VALUE).put("nextToken", afterAlpha))));
|
||||
|
||||
verify(broker, never()).connectivity(ACCOUNT, REGION, "alpha-1");
|
||||
verify(broker).connectivity(ACCOUNT, REGION, "alpha-2");
|
||||
verify(broker).connectivity(ACCOUNT, REGION, "beta-1");
|
||||
verify(broker).connectivity(ACCOUNT, REGION, "gamma");
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectivityQueriesNeedConnectivityIndexing() {
|
||||
fleet();
|
||||
@@ -1142,21 +1187,101 @@ class IotFleetIndexingServiceTest {
|
||||
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"},
|
||||
"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "ON"}}
|
||||
""");
|
||||
assertSearchFails(query("*").put("indexName", "AWS_ThingGroups"), "InvalidRequestException", 400,
|
||||
"Floci does not support searching AWS_ThingGroups");
|
||||
assertEquals(List.of(), search(query("*").put("indexName", "AWS_ThingGroups")).items());
|
||||
assertEquals(List.of(), search(query("*").put("indexName", "AWS_Things").put("queryVersion", "2017-09-30"))
|
||||
.items());
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS_ThingGroups answers with the thing group documents AWS returns for that index, in group name
|
||||
* order and under {@code thingGroups}: the group's own fields only, so a thing field is not a field
|
||||
* of this index and a page continues after the group it stopped at.
|
||||
*/
|
||||
@Test
|
||||
void searchOfThingGroupsFindsGroupsByTheirOwnFields() {
|
||||
indexGroups();
|
||||
IotFleetIndexingService.SearchPage all = search(groups("*"));
|
||||
|
||||
assertEquals("thingGroups", all.member());
|
||||
assertEquals(List.of("north-group", "release", "south-group"), groupNames(all));
|
||||
assertNull(all.nextToken());
|
||||
assertEquals(List.of("release"), groupNames(search(groups("attributes.release_channel:stable"))));
|
||||
assertEquals(List.of("release"), groupNames(search(groups("thingGroupDescription:canary*"))));
|
||||
assertEquals(List.of("north-group"), groupNames(search(groups("attributes.site:north"))));
|
||||
assertEquals(List.of("north-group", "south-group"), groupNames(search(groups("thingGroupName:*group"))));
|
||||
assertEquals(List.of("north-group"), groupNames(search(groups("thingGroupName:north-group AND "
|
||||
+ "attributes.site:north"))));
|
||||
// Floci models static groups, so no group has a parent and no document carries the field.
|
||||
assertEquals(List.of(), groupNames(search(groups("parentGroupNames:*"))));
|
||||
// A thing's field is not a field of this index.
|
||||
assertSearchFails(groups("thingName:alpha-1"), "InvalidQueryException", 400,
|
||||
"Unable to parse query, invalid field name, field name: thingName, query string: thingName:alpha-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aThingGroupDocumentCarriesOnlyTheMembersTheGroupHas() {
|
||||
indexGroups();
|
||||
|
||||
ObjectNode plain = search(groups("thingGroupName:south-group")).items().get(0);
|
||||
assertEquals("south-group", plain.path("thingGroupName").asString());
|
||||
assertTrue(plain.path("thingGroupId").asString().matches("[0-9a-f-]{36}"), plain.toString());
|
||||
assertTrue(plain.path("thingGroupDescription").isMissingNode());
|
||||
assertTrue(plain.path("attributes").isMissingNode());
|
||||
assertTrue(plain.path("parentGroupNames").isMissingNode());
|
||||
|
||||
ObjectNode described = search(groups("thingGroupName:release")).items().get(0);
|
||||
assertEquals("canary releases", described.path("thingGroupDescription").asString());
|
||||
assertEquals("stable", described.path("attributes").path("release_channel").asString());
|
||||
}
|
||||
|
||||
/** The group index has its own cursor and its own token, so neither index's page continues the other's. */
|
||||
@Test
|
||||
void aThingGroupPageCarriesItsGroupNameAndItsOwnToken() {
|
||||
indexGroups();
|
||||
IotFleetIndexingService.SearchPage first = search(groups("*").put("maxResults", 2));
|
||||
assertEquals(List.of("north-group", "release"), groupNames(first));
|
||||
assertNotNull(first.nextToken());
|
||||
|
||||
assertEquals(List.of("south-group"),
|
||||
groupNames(search(groups("*").put("maxResults", 2).put("nextToken", first.nextToken()))));
|
||||
|
||||
update("""
|
||||
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY"}}
|
||||
""");
|
||||
iot.service.createThing("alpha-1", Map.of(), null, REGION);
|
||||
iot.service.createThing("alpha-2", Map.of(), null, REGION);
|
||||
String thingToken = search(query("*").put("maxResults", 1)).nextToken();
|
||||
assertNotNull(thingToken);
|
||||
assertSearchFails(groups("*").put("nextToken", thingToken), "InvalidRequestException", 400,
|
||||
"nextToken was from a request with different parameters");
|
||||
assertSearchFails(query("*").put("nextToken", first.nextToken()), "InvalidRequestException", 400,
|
||||
"nextToken was from a request with different parameters");
|
||||
}
|
||||
|
||||
/** The two indexes are enabled on their own: a group search needs no thing indexing. */
|
||||
@Test
|
||||
void thingGroupsAreSearchableWhileTheThingIndexIsOff() {
|
||||
update("""
|
||||
{"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "ON"}}
|
||||
""");
|
||||
iot.service.createThingGroup("release", json("""
|
||||
{"attributePayload": {"attributes": {"release_channel": "stable"}}}
|
||||
"""), REGION);
|
||||
|
||||
assertEquals(List.of("release"), groupNames(search(groups("attributes.release_channel:stable"))));
|
||||
assertSearchFails(query("*"), "ResourceNotFoundException", 404,
|
||||
"Index AWS_Things does not exist. Please enable index by calling UpdateIndexingConfiguration");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pagesCarryATokenUntilTheLastPage() {
|
||||
fleet();
|
||||
|
||||
IotService.Page<ObjectNode> first = search(query("thingName:alpha*").put("maxResults", 1));
|
||||
IotFleetIndexingService.SearchPage first = search(query("thingName:alpha*").put("maxResults", 1));
|
||||
assertEquals("alpha-1", first.items().get(0).path("thingName").asString());
|
||||
assertEquals(1, first.items().size());
|
||||
assertNotNull(first.nextToken());
|
||||
IotService.Page<ObjectNode> second =
|
||||
IotFleetIndexingService.SearchPage second =
|
||||
search(query("thingName:alpha*").put("maxResults", 1).put("nextToken", first.nextToken()));
|
||||
assertEquals("alpha-2", second.items().get(0).path("thingName").asString());
|
||||
assertNull(second.nextToken());
|
||||
@@ -1172,7 +1297,7 @@ class IotFleetIndexingServiceTest {
|
||||
fleet();
|
||||
String token = search(query("*").put("maxResults", 1)).nextToken();
|
||||
|
||||
IotService.Page<ObjectNode> rest =
|
||||
IotFleetIndexingService.SearchPage rest =
|
||||
search(query("*").put("maxResults", Integer.MAX_VALUE).put("nextToken", token));
|
||||
|
||||
assertEquals(List.of("alpha-2", "beta-1", "gamma"), thingNames(rest));
|
||||
@@ -1182,12 +1307,12 @@ class IotFleetIndexingServiceTest {
|
||||
@Test
|
||||
void aPageTokenContinuesAfterTheLastThingReturnedWhenEarlierThingsAreDeleted() {
|
||||
fleet();
|
||||
IotService.Page<ObjectNode> first = search(query("thingName:alpha*").put("maxResults", 1));
|
||||
IotFleetIndexingService.SearchPage first = search(query("thingName:alpha*").put("maxResults", 1));
|
||||
assertEquals(List.of("alpha-1"), thingNames(first));
|
||||
assertNotNull(first.nextToken());
|
||||
|
||||
iot.service.deleteThing("alpha-1", REGION);
|
||||
IotService.Page<ObjectNode> second =
|
||||
IotFleetIndexingService.SearchPage second =
|
||||
search(query("thingName:alpha*").put("maxResults", 1).put("nextToken", first.nextToken()));
|
||||
|
||||
assertEquals(List.of("alpha-2"), thingNames(second));
|
||||
@@ -1249,7 +1374,7 @@ class IotFleetIndexingServiceTest {
|
||||
fleet();
|
||||
|
||||
assertEquals(List.of("alpha-1"), thingNames(search(query("*").put("maxResults", 1.5))));
|
||||
IotService.Page<ObjectNode> all = search(query("*").put("maxResults", 2147483648L));
|
||||
IotFleetIndexingService.SearchPage all = search(query("*").put("maxResults", 2147483648L));
|
||||
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"), thingNames(all));
|
||||
assertNull(all.nextToken());
|
||||
assertEquals(4, search(query("*").put("maxResults", 500)).items().size());
|
||||
@@ -1263,7 +1388,7 @@ class IotFleetIndexingServiceTest {
|
||||
void maxResultsIsTruncatedAndSaturatedAtTheIntRange() {
|
||||
fleet();
|
||||
|
||||
IotService.Page<ObjectNode> all = search(query("*").put("maxResults", new BigInteger("9223372036854775808")));
|
||||
IotFleetIndexingService.SearchPage all = search(query("*").put("maxResults", new BigInteger("9223372036854775808")));
|
||||
assertEquals(List.of("alpha-1", "alpha-2", "beta-1", "gamma"), thingNames(all));
|
||||
assertNull(all.nextToken());
|
||||
assertEquals(4, search(query("*").put("maxResults", new BigDecimal("1e30"))).items().size());
|
||||
@@ -1317,7 +1442,7 @@ class IotFleetIndexingServiceTest {
|
||||
assertEquals(message, failure.getMessage(), body);
|
||||
}
|
||||
|
||||
private static List<String> thingNames(IotService.Page<ObjectNode> page) {
|
||||
private static List<String> thingNames(IotFleetIndexingService.SearchPage page) {
|
||||
return page.items().stream().map(thing -> thing.path("thingName").asString()).toList();
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user