feat(iot): search the supported fleet index subset (#4913)

Floci served the fleet indexing configuration but not SearchIndex, so
an application that finds its things by name, type, group or attribute
got "Unknown operation: POST /indices/search".

SearchIndex now runs on POST /indices/search over the things of the
caller's account and region, in thing name order. Its page token names
the last thing returned, so a page continues after it even when things
before it were deleted, as measured on AWS. Like AWS's, a token
continues only the request that issued it: another queryString, or an
indexName or queryVersion sent differently, is "nextToken was from a
request with different parameters", and an empty, forged, edited or
truncated token is "Invalid nextToken". A new parser,
IotFleetIndexQuery, evaluates field:value terms with case-insensitive
values, case-sensitive field names, * and ? wildcards, existence and
match-all, quoted values, AND, OR and NOT with their symbolic forms,
leading - negation and parentheses. Precedence is the one measured on
AWS, where whitespace is an AND that binds looser than OR. The fields
are thingName, thingId, thingTypeName, thingGroupNames and attributes.*.

Requests are validated with the messages and in the order measured on
AWS: a body that is not a JSON object and every member type, member
constraints, index name, query version, a disabled index, the query,
then the page token. Within the query a syntax error comes first, then
the 12-term limit, in which each value of a field group counts and the
field does not, then the first other error, where the field of a group
is checked like any other field. A range counts as one term, and a
malformed range or an unescaped bracket outside one is a syntax error.
AWS's limits hold: a queryString of at most 1000 characters, at most 12
terms, at most two * wildcards in a value and no value starting with ?.
maxResults takes any number, truncated toward zero and capped at the int
range as on AWS. A classic shadow field needs REGISTRY_AND_SHADOW
indexing, and a named shadow field named shadow indexing and a shadow in
its filter, or it is AWS's invalid field name. Constructs AWS accepts
but Floci does not evaluate, such as ranges, comparisons, free text,
field grouping and shadow or Device Defender fields, are refused with
InvalidQueryException instead of matching nothing, and so is a search of
AWS_ThingGroups. Connectivity fields are refused like shadow and Device
Defender fields: AWS's InvalidRequestException while connectivity
indexing is off, InvalidQueryException once it is on. Documents leave
out the members a thing lacks and never carry a shadow or a
connectivity member, where AWS adds connectivity while connectivity
indexing is on.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-10 13:56:54 -04:00
1 parent 2015d01864
commit 1082941bc2
8 files changed
+1667 -23

No files matched your search

@@ -63,6 +63,7 @@ import software.amazon.awssdk.services.iot.model.GetPolicyRequest;
import software.amazon.awssdk.services.iot.model.GetPolicyResponse;
import software.amazon.awssdk.services.iot.model.GetTopicRuleRequest;
import software.amazon.awssdk.services.iot.model.GetTopicRuleResponse;
import software.amazon.awssdk.services.iot.model.IndexNotReadyException;
import software.amazon.awssdk.services.iot.model.IndexStatus;
import software.amazon.awssdk.services.iot.model.InvalidRequestException;
import software.amazon.awssdk.services.iot.model.ListCertificatesRequest;
@@ -88,17 +89,21 @@ import software.amazon.awssdk.services.iot.model.NamedShadowIndexingMode;
import software.amazon.awssdk.services.iot.model.RemoveThingFromThingGroupRequest;
import software.amazon.awssdk.services.iot.model.ResourceAlreadyExistsException;
import software.amazon.awssdk.services.iot.model.ResourceNotFoundException;
import software.amazon.awssdk.services.iot.model.SearchIndexRequest;
import software.amazon.awssdk.services.iot.model.SearchIndexResponse;
import software.amazon.awssdk.services.iot.model.ServerCertificateStatus;
import software.amazon.awssdk.services.iot.model.ServiceType;
import software.amazon.awssdk.services.iot.model.SqsAction;
import software.amazon.awssdk.services.iot.model.Tag;
import software.amazon.awssdk.services.iot.model.TagResourceRequest;
import software.amazon.awssdk.services.iot.model.ThingConnectivityIndexingMode;
import software.amazon.awssdk.services.iot.model.ThingDocument;
import software.amazon.awssdk.services.iot.model.ThingGroupIndexingConfiguration;
import software.amazon.awssdk.services.iot.model.ThingGroupIndexingMode;
import software.amazon.awssdk.services.iot.model.ThingGroupProperties;
import software.amazon.awssdk.services.iot.model.ThingIndexingConfiguration;
import software.amazon.awssdk.services.iot.model.ThingIndexingMode;
import software.amazon.awssdk.services.iot.model.ThingTypeDefinition;
import software.amazon.awssdk.services.iot.model.ThingTypeProperties;
import software.amazon.awssdk.services.iot.model.TopicRulePayload;
import software.amazon.awssdk.services.iot.model.UntagResourceRequest;
@@ -140,8 +145,14 @@ import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -359,6 +370,173 @@ class IotTest {
}
}
@Test
void fleetIndexSearch() throws InterruptedException {
String prefix = "fleetsearch" + Long.toString(System.currentTimeMillis(), 36);
String group = prefix + "group";
String provider = prefix + "p";
// AWS keeps a deprecated thing type for five minutes before it can be deleted, so on AWS the
// test borrows a test thing type the account already has rather than creating one.
String thingType = TestFixtures.isRealAws() ? existingTestThingType() : prefix + "type";
GetIndexingConfigurationResponse prior =
iot.getIndexingConfiguration(GetIndexingConfigurationRequest.builder().build());
try {
iot.updateIndexingConfiguration(UpdateIndexingConfigurationRequest.builder()
.thingIndexingConfiguration(ThingIndexingConfiguration.builder()
.thingIndexingMode(ThingIndexingMode.REGISTRY)
.thingConnectivityIndexingMode(ThingConnectivityIndexingMode.STATUS)
.build())
.build());
if (!TestFixtures.isRealAws()) {
iot.createThingType(CreateThingTypeRequest.builder().thingTypeName(thingType).build());
}
iot.createThingGroup(CreateThingGroupRequest.builder().thingGroupName(group).build());
iot.createThing(CreateThingRequest.builder()
.thingName(prefix + "a")
.thingTypeName(thingType)
.attributePayload(AttributePayload.builder()
.attributes(Map.of("provider", provider + "1", "site", "north"))
.build())
.build());
iot.createThing(CreateThingRequest.builder()
.thingName(prefix + "b")
.attributePayload(AttributePayload.builder().attributes(Map.of("provider", provider + "1")).build())
.build());
iot.createThing(CreateThingRequest.builder()
.thingName(prefix + "c")
.attributePayload(AttributePayload.builder().attributes(Map.of("provider", provider + "2")).build())
.build());
iot.addThingToThingGroup(AddThingToThingGroupRequest.builder()
.thingGroupName(group)
.thingName(prefix + "a")
.build());
List<ThingDocument> all = awaitSearch("thingName:" + prefix + "*", prefix, "a", "b", "c");
ThingDocument typed = all.get(0);
assertThat(typed.thingTypeName()).isEqualTo(thingType);
assertThat(typed.thingGroupNames()).containsExactly(group);
assertThat(typed.attributes()).containsOnly(Map.entry("provider", provider + "1"), Map.entry("site", "north"));
assertThat(typed.shadow()).isNull();
ThingDocument plain = all.get(1);
assertThat(plain.thingTypeName()).isNull();
assertThat(plain.hasThingGroupNames()).isFalse();
assertThat(plain.attributes()).containsOnly(Map.entry("provider", provider + "1"));
for (ThingDocument thing : all) {
assertThat(thing.thingId()).isNotBlank();
}
awaitSearch("attributes.provider:" + provider + "1", prefix, "a", "b");
awaitSearch("thingName:" + prefix + "c", prefix, "c");
if (thingType != null) {
awaitSearch("thingTypeName:" + thingType, prefix, "a");
awaitSearch("thingTypeName:" + thingType + " AND attributes.provider:" + provider + "1", prefix, "a");
}
awaitSearch("attributes.provider:" + provider + "2 OR thingName:" + prefix + "a", prefix, "a", "c");
awaitSearch("thingName:" + prefix + "* AND NOT attributes.provider:" + provider + "1", prefix, "c");
awaitSearch("attributes.provider:" + provider + "?", prefix, "a", "b", "c");
awaitSearch("thingGroupNames:" + group, prefix, "a");
Set<String> paged = new TreeSet<>();
String nextToken = null;
int pages = 0;
do {
SearchIndexResponse page = iot.searchIndex(SearchIndexRequest.builder()
.queryString("thingName:" + prefix + "*")
.maxResults(1)
.nextToken(nextToken)
.build());
assertThat(page.things()).hasSizeLessThanOrEqualTo(1);
page.things().forEach(thing -> paged.add(thing.thingName()));
nextToken = page.nextToken();
pages++;
} while (nextToken != null && pages < 10);
assertThat(paged).containsExactly(prefix + "a", prefix + "b", prefix + "c");
assertThat(pages).isBetween(3, 4);
assertThatThrownBy(() -> iot.searchIndex(SearchIndexRequest.builder()
.queryString("thingName:" + prefix + "*")
.nextToken("bogus")
.build()))
.isInstanceOf(InvalidRequestException.class)
.hasMessageContaining("Invalid nextToken");
assertThatThrownBy(() -> iot.searchIndex(SearchIndexRequest.builder()
.queryString("thingName:" + prefix + "*")
.queryVersion("2017-09-31")
.build()))
.isInstanceOf(InvalidRequestException.class)
.hasMessageContaining("Invalid queryVersion. Expected one of: [2017-09-30]");
} finally {
for (String suffix : List.of("a", "b", "c")) {
deleteIfPresent(() -> iot.deleteThing(DeleteThingRequest.builder().thingName(prefix + suffix).build()));
}
deleteIfPresent(() -> iot.deleteThingGroup(DeleteThingGroupRequest.builder().thingGroupName(group).build()));
if (!TestFixtures.isRealAws()) {
deleteIfPresent(() -> iot.deleteThingType(DeleteThingTypeRequest.builder().thingTypeName(thingType).build()));
}
// Indexing is account wide on AWS: put back whatever the account had before this test.
iot.updateIndexingConfiguration(UpdateIndexingConfigurationRequest.builder()
.thingIndexingConfiguration(prior.thingIndexingConfiguration())
.thingGroupIndexingConfiguration(prior.thingGroupIndexingConfiguration())
.build());
}
}
/** A thing type of the account meant for tests and not deprecated, or null when it has none. */
private String existingTestThingType() {
return iot.listThingTypesPaginator(ListThingTypesRequest.builder().build()).thingTypes().stream()
.filter(type -> !Boolean.TRUE.equals(type.thingTypeMetadata().deprecated()))
.map(ThingTypeDefinition::thingTypeName)
.filter(name -> name.contains("test"))
.sorted()
.findFirst()
.orElse(null);
}
/**
* This test's things a query finds, in name order. On AWS the search is polled until they are the
* expected ones: AWS indexes a change a few seconds after it and refuses searches while a new
* index builds. Floci answers at once, so against Floci the search runs once.
*/
private List<ThingDocument> awaitSearch(String query, String prefix, String... expectedSuffixes)
throws InterruptedException {
List<String> expected = Arrays.stream(expectedSuffixes).map(suffix -> prefix + suffix).toList();
Instant deadline = Instant.now().plusSeconds(120);
while (true) {
List<ThingDocument> found = new ArrayList<>();
String notReady = null;
try {
String nextToken = null;
do {
SearchIndexResponse page = iot.searchIndex(SearchIndexRequest.builder()
.queryString(query)
.nextToken(nextToken)
.build());
page.things().stream().filter(thing -> thing.thingName().startsWith(prefix)).forEach(found::add);
nextToken = page.nextToken();
} while (nextToken != null);
} catch (IndexNotReadyException e) {
notReady = e.getMessage();
}
found.sort(Comparator.comparing(ThingDocument::thingName));
List<String> names = found.stream().map(ThingDocument::thingName).toList();
if (!TestFixtures.isRealAws() || notReady == null && names.equals(expected)
|| Instant.now().isAfter(deadline)) {
assertThat(notReady).as("index not ready").isNull();
assertThat(names).as(query).isEqualTo(expected);
return found;
}
Thread.sleep(2_000);
}
}
private static void deleteIfPresent(Runnable delete) {
try {
delete.run();
} catch (ResourceNotFoundException ignored) {
// The test failed before creating it.
}
}
private static void assertIndexStatus(IndexStatus status) {
if (TestFixtures.isRealAws()) {
// AWS builds the index in the background after a mode change; Floci has it ready at once.