mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
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:
1 parent
2015d01864
commit
1082941bc2
8 files changed
+1667
-23
No files matched your search
@@ -0,0 +1,381 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.ThingIndexing;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
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
|
||||
* {@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.
|
||||
*/
|
||||
final class IotFleetIndexQuery {
|
||||
|
||||
private static final Set<String> FIELDS = Set.of("thingName", "thingId", "thingTypeName", "thingGroupNames");
|
||||
private static final String ATTRIBUTES = "attributes.";
|
||||
private static final Set<String> OPERATORS = Set.of("AND", "OR", "NOT", "-", ")");
|
||||
private static final Pattern COMPARISON = Pattern.compile("[<>]");
|
||||
private static final String RANGE_BOUND = "(\"(?:\\\\.|[^\"\\\\])*\"|[^ \\]}]+)";
|
||||
private static final Pattern RANGE = Pattern.compile("[\\[{] *" + RANGE_BOUND + " +(?:TO +)?" + RANGE_BOUND
|
||||
+ " *[\\]}]");
|
||||
private static final int MAX_TERMS = 12;
|
||||
private static final int MAX_WILDCARDS = 2;
|
||||
|
||||
private final String queryString;
|
||||
private final ThingIndexing indexing;
|
||||
private final List<String> tokens;
|
||||
private int position;
|
||||
private int terms;
|
||||
private AwsException deferred;
|
||||
|
||||
private IotFleetIndexQuery(String queryString, ThingIndexing indexing) {
|
||||
this.queryString = queryString;
|
||||
this.indexing = indexing;
|
||||
this.tokens = tokenize();
|
||||
}
|
||||
|
||||
static Predicate<JsonNode> parse(String queryString, ThingIndexing indexing) {
|
||||
IotFleetIndexQuery parser = new IotFleetIndexQuery(queryString, indexing);
|
||||
Predicate<JsonNode> query = parser.clauses();
|
||||
if (parser.position < parser.tokens.size()) {
|
||||
throw parser.syntaxError();
|
||||
}
|
||||
if (parser.terms > MAX_TERMS) {
|
||||
throw parser.parseError("number of terms cannot exceed " + MAX_TERMS + ", terms found: " + parser.terms);
|
||||
}
|
||||
if (parser.deferred != null) {
|
||||
throw parser.deferred;
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Words, quoted runs kept inside their word, parentheses, and a leading - or ! as negation. A
|
||||
* range opened right after a field's colon, or at the start of a word, runs to its closing
|
||||
* bracket as one word.
|
||||
*/
|
||||
private List<String> tokenize() {
|
||||
List<String> found = new ArrayList<>();
|
||||
int i = 0;
|
||||
while (i < queryString.length()) {
|
||||
char c = queryString.charAt(i);
|
||||
if (Character.isWhitespace(c)) {
|
||||
i++;
|
||||
} else if (c == '(' || c == ')') {
|
||||
found.add(String.valueOf(c));
|
||||
i++;
|
||||
} else if (c == '-' || c == '!') {
|
||||
found.add("-");
|
||||
i++;
|
||||
} else {
|
||||
int start = i;
|
||||
boolean quoted = false;
|
||||
boolean range = false;
|
||||
while (i < queryString.length()) {
|
||||
char next = queryString.charAt(i);
|
||||
if (next == '\\') {
|
||||
i++;
|
||||
} else if (next == '"') {
|
||||
quoted = !quoted;
|
||||
} else if (!quoted && range && (next == ']' || next == '}')) {
|
||||
i++;
|
||||
break;
|
||||
} else if (!quoted && !range && (next == '[' || next == '{')
|
||||
&& (i == start || queryString.charAt(i - 1) == ':')) {
|
||||
range = true;
|
||||
} else if (!quoted && !range && (Character.isWhitespace(next) || next == '(' || next == ')')) {
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (quoted) {
|
||||
throw syntaxError();
|
||||
}
|
||||
String word = queryString.substring(start, Math.min(i, queryString.length()));
|
||||
found.add(switch (word) {
|
||||
case "&&" -> "AND";
|
||||
case "||" -> "OR";
|
||||
default -> word;
|
||||
});
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Clauses joined by whitespace, which AWS treats as an AND binding looser than OR. */
|
||||
private Predicate<JsonNode> clauses() {
|
||||
Predicate<JsonNode> query = or();
|
||||
while (position < tokens.size() && !")".equals(tokens.get(position))) {
|
||||
query = query.and(or());
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private Predicate<JsonNode> or() {
|
||||
Predicate<JsonNode> query = and();
|
||||
while (accept("OR")) {
|
||||
query = query.or(and());
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private Predicate<JsonNode> and() {
|
||||
Predicate<JsonNode> query = unary();
|
||||
while (accept("AND")) {
|
||||
query = query.and(unary());
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private Predicate<JsonNode> unary() {
|
||||
if (accept("NOT") || accept("-")) {
|
||||
return primary().negate();
|
||||
}
|
||||
return primary();
|
||||
}
|
||||
|
||||
private Predicate<JsonNode> primary() {
|
||||
if (position >= tokens.size()) {
|
||||
throw syntaxError();
|
||||
}
|
||||
String token = tokens.get(position++);
|
||||
if ("(".equals(token)) {
|
||||
Predicate<JsonNode> group = clauses();
|
||||
if (!accept(")")) {
|
||||
throw syntaxError();
|
||||
}
|
||||
return group;
|
||||
}
|
||||
if (OPERATORS.contains(token)) {
|
||||
throw syntaxError();
|
||||
}
|
||||
return term(token);
|
||||
}
|
||||
|
||||
private Predicate<JsonNode> term(String token) {
|
||||
int colon = token.indexOf(':');
|
||||
String value = colon < 0 ? "" : token.substring(colon + 1);
|
||||
if (colon >= 0 && value.isEmpty()) {
|
||||
if (hasBracket(token) || !accept("(")) {
|
||||
throw syntaxError();
|
||||
}
|
||||
// AWS counts each value of a field group as a term, but not the field, and checks the field first.
|
||||
Predicate<JsonNode> refused;
|
||||
try {
|
||||
checkField(token.substring(0, colon));
|
||||
refused = defer(unsupported("field grouping"));
|
||||
} catch (AwsException e) {
|
||||
refused = defer(e);
|
||||
}
|
||||
clauses();
|
||||
if (!accept(")")) {
|
||||
throw syntaxError();
|
||||
}
|
||||
return refused;
|
||||
}
|
||||
terms++;
|
||||
boolean quoted = value.startsWith("\"");
|
||||
String rangeText = colon < 0 ? token : value;
|
||||
boolean range = rangeText.startsWith("[") || rangeText.startsWith("{");
|
||||
if ((quoted && (value.length() < 2 || !value.endsWith("\"")))
|
||||
|| (!quoted && (value.startsWith("<") || value.startsWith(">")))
|
||||
|| hasBracket(range ? token.substring(0, token.length() - rangeText.length()) : token)
|
||||
|| (range && !isRange(rangeText))) {
|
||||
throw syntaxError();
|
||||
}
|
||||
try {
|
||||
return match(token, colon, value);
|
||||
} catch (AwsException e) {
|
||||
return defer(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Predicate<JsonNode> match(String token, int colon, String value) {
|
||||
if ("*".equals(token)) {
|
||||
return document -> true;
|
||||
}
|
||||
if (token.startsWith("+")) {
|
||||
throw parseError("unsupported operator - \"+\"");
|
||||
}
|
||||
Matcher comparison = COMPARISON.matcher(token);
|
||||
if (comparison.find() && (colon < 0 || comparison.start() < colon)) {
|
||||
checkField(token.substring(0, comparison.start()));
|
||||
throw unsupported("comparisons");
|
||||
}
|
||||
if (colon < 0) {
|
||||
throw unsupported("free text terms");
|
||||
}
|
||||
String field = token.substring(0, colon);
|
||||
checkField(field);
|
||||
Pattern pattern = valuePattern(field, value);
|
||||
return document -> {
|
||||
int dot = field.indexOf('.');
|
||||
JsonNode node = dot < 0 ? document.path(field)
|
||||
: document.path(field.substring(0, dot)).path(field.substring(dot + 1));
|
||||
Iterable<JsonNode> values = node.isArray() ? node : node.isMissingNode() ? List.of() : List.of(node);
|
||||
for (JsonNode candidate : values) {
|
||||
if (pattern.matcher(candidate.asText()).matches()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private void checkField(String field) {
|
||||
if (field.startsWith(ATTRIBUTES) && field.length() > ATTRIBUTES.length()) {
|
||||
return;
|
||||
}
|
||||
String attribute;
|
||||
boolean enabled;
|
||||
if (field.startsWith("connectivity.")) {
|
||||
attribute = "Connectivity";
|
||||
enabled = "STATUS".equals(indexing.thingConnectivityIndexingMode());
|
||||
} else if (field.startsWith("shadow.")) {
|
||||
attribute = "Shadow";
|
||||
boolean named = "shadow.name".equals(field) || field.startsWith("shadow.name.");
|
||||
enabled = "REGISTRY_AND_SHADOW".equals(indexing.thingIndexingMode())
|
||||
|| named && "ON".equals(indexing.namedShadowIndexingMode());
|
||||
if (enabled && named) {
|
||||
// shadow.name.<shadow>.<field> exists only for a shadow in the named shadow filter.
|
||||
String[] parts = field.split("\\.", 4);
|
||||
if (parts.length < 4 || !"ON".equals(indexing.namedShadowIndexingMode())
|
||||
|| !indexing.namedShadowNames().contains(parts[2])) {
|
||||
throw parseError("invalid field name, field name: " + field);
|
||||
}
|
||||
}
|
||||
} else if (field.startsWith("deviceDefender.")) {
|
||||
attribute = "Devicedefender";
|
||||
enabled = "VIOLATIONS".equals(indexing.deviceDefenderIndexingMode());
|
||||
} else if (FIELDS.contains(field)) {
|
||||
return;
|
||||
} else {
|
||||
throw parseError("invalid field name, field name: " + field);
|
||||
}
|
||||
if (!enabled) {
|
||||
throw new AwsException("InvalidRequestException", "Query includes one or more constraints for "
|
||||
+ attribute + " attribute, but " + attribute + " indexing is not enabled for AWS_Things index", 400);
|
||||
}
|
||||
if (!FIELDS.contains(field)) {
|
||||
throw unsupported("the field " + field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A quoted value matches literally; otherwise * and ? are wildcards and a backslash escapes.
|
||||
* As on AWS an unquoted value takes at most two unescaped * and cannot start with an unescaped ?.
|
||||
*/
|
||||
private Pattern valuePattern(String field, String value) {
|
||||
boolean quoted = value.startsWith("\"");
|
||||
if (!quoted) {
|
||||
switch (value.charAt(0)) {
|
||||
case '[', '{' -> throw unsupported("range queries");
|
||||
case '/' -> throw parseError("unsupported query type - regular expression");
|
||||
case '?' -> throw invalidValue("wildcard character (?) is not allowed at the start of the value",
|
||||
field, value);
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
String text = quoted ? value.substring(1, value.length() - 1) : value;
|
||||
StringBuilder regex = new StringBuilder();
|
||||
int wildcards = 0;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c == '\\' && i + 1 < text.length()) {
|
||||
regex.append(Pattern.quote(String.valueOf(text.charAt(++i))));
|
||||
} else if (!quoted && c == '*') {
|
||||
wildcards++;
|
||||
regex.append(".*");
|
||||
} else if (!quoted && c == '?') {
|
||||
regex.append('.');
|
||||
} else if (!quoted && c == '~') {
|
||||
throw parseError("unsupported query type - fuzzy");
|
||||
} else if (!quoted && c == '^') {
|
||||
throw parseError("unsupported query type - boost");
|
||||
} else {
|
||||
regex.append(Pattern.quote(String.valueOf(c)));
|
||||
}
|
||||
}
|
||||
if (wildcards > MAX_WILDCARDS) {
|
||||
throw invalidValue("too many wildcards (*). The maximum allowed per term is " + MAX_WILDCARDS,
|
||||
field, value);
|
||||
}
|
||||
return Pattern.compile(regex.toString(), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
|
||||
}
|
||||
|
||||
/** A [, ], { or } that is neither escaped nor quoted, which AWS's parser rejects outside a range. */
|
||||
private static boolean hasBracket(String text) {
|
||||
boolean quoted = false;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
} else if (c == '"') {
|
||||
quoted = !quoted;
|
||||
} else if (!quoted && "[]{}".indexOf(c) >= 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Two bounds, optionally joined by TO, in [ or { and ] or }, where TO itself is no bound. */
|
||||
private static boolean isRange(String text) {
|
||||
Matcher range = RANGE.matcher(text);
|
||||
return range.matches() && !"TO".equals(range.group(1)) && !"TO".equals(range.group(2));
|
||||
}
|
||||
|
||||
/** Records the first error AWS reports only once the query parses and its terms are counted. */
|
||||
private Predicate<JsonNode> defer(AwsException error) {
|
||||
if (deferred == null) {
|
||||
deferred = error;
|
||||
}
|
||||
return document -> false;
|
||||
}
|
||||
|
||||
private boolean accept(String token) {
|
||||
if (position < tokens.size() && token.equals(tokens.get(position))) {
|
||||
position++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private AwsException syntaxError() {
|
||||
return parseError("invalid syntax");
|
||||
}
|
||||
|
||||
private AwsException parseError(String reason) {
|
||||
return new AwsException("InvalidQueryException",
|
||||
"Unable to parse query, " + reason + ", query string: " + queryString, 400);
|
||||
}
|
||||
|
||||
private AwsException invalidValue(String reason, String field, String value) {
|
||||
return parseError("invalid value - " + reason + ", field name: " + field + ", value: " + value);
|
||||
}
|
||||
|
||||
private AwsException unsupported(String construct) {
|
||||
return new AwsException("InvalidQueryException",
|
||||
"Floci does not support " + construct + " in fleet index queries, query string: " + queryString, 400);
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -22,7 +22,7 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* REST-JSON routes for AWS IoT fleet indexing: UpdateIndexingConfiguration,
|
||||
* GetIndexingConfiguration and DescribeIndex, on the paths and shapes the AWS SDKs use.
|
||||
* GetIndexingConfiguration, DescribeIndex and SearchIndex, on the paths and shapes the AWS SDKs use.
|
||||
*/
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -93,4 +93,17 @@ public class IotFleetIndexingController {
|
||||
response.put("schema", schema);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/indices/search")
|
||||
public Response searchIndex(@Context HttpHeaders headers, String body) {
|
||||
IotService.Page<ObjectNode> page = fleetIndexingService.searchIndex(IotRequestBody.read(objectMapper, body),
|
||||
regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.putArray("things").addAll(page.items());
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
}
|
||||
+187
-15
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeType;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -11,21 +13,30 @@ 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;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.ThingIndexing;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotThingGroup;
|
||||
import io.github.hectorvent.floci.services.iot.model.Thing;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* AWS IoT fleet indexing configuration: UpdateIndexingConfiguration, GetIndexingConfiguration and
|
||||
* DescribeIndex. One configuration per account and region; a region never updated is OFF.
|
||||
* AWS IoT fleet indexing: UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex and
|
||||
* a bounded SearchIndex. One configuration per account and region; a region never updated is OFF.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IotFleetIndexingService {
|
||||
@@ -33,6 +44,9 @@ public class IotFleetIndexingService {
|
||||
static final String THINGS_INDEX = "AWS_Things";
|
||||
static final String THING_GROUPS_INDEX = "AWS_ThingGroups";
|
||||
|
||||
private static final int MAX_QUERY_STRING_LENGTH = 1000;
|
||||
private static final Pattern PAGE_TOKEN = Pattern.compile("([0-9a-f-]{36})([0-9a-f-]{36})(.+)", Pattern.DOTALL);
|
||||
|
||||
// Enum value sets in the order AWS prints them in its validation messages.
|
||||
private static final List<String> THING_INDEXING_MODES = List.of("REGISTRY_AND_SHADOW", "OFF", "REGISTRY");
|
||||
private static final List<String> CONNECTIVITY_MODES = List.of("OFF", "STATUS");
|
||||
@@ -81,17 +95,19 @@ public class IotFleetIndexingService {
|
||||
new Field("thingGroupId", "String"));
|
||||
|
||||
private final StorageBackend<String, IotIndexingConfiguration> store;
|
||||
private final IotService iotService;
|
||||
/** 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) {
|
||||
public IotFleetIndexingService(StorageFactory storageFactory, IotService iotService) {
|
||||
this(storageFactory.create("iot", "iot-indexing-configuration.json",
|
||||
new TypeReference<Map<String, IotIndexingConfiguration>>() {}));
|
||||
new TypeReference<Map<String, IotIndexingConfiguration>>() {}), iotService);
|
||||
}
|
||||
|
||||
IotFleetIndexingService(StorageBackend<String, IotIndexingConfiguration> store) {
|
||||
IotFleetIndexingService(StorageBackend<String, IotIndexingConfiguration> store, IotService iotService) {
|
||||
this.store = store;
|
||||
this.iotService = iotService;
|
||||
}
|
||||
|
||||
public void updateIndexingConfiguration(JsonNode request, String region) {
|
||||
@@ -114,10 +130,7 @@ public class IotFleetIndexingService {
|
||||
List<Field> groupManagedFields = fields(groupNode.path("managedFields"), groupPrefix + ".managedFields",
|
||||
errors);
|
||||
fields(groupNode.path("customFields"), groupPrefix + ".customFields", errors);
|
||||
if (!errors.isEmpty()) {
|
||||
throw invalid(errors.size() + (errors.size() == 1 ? " validation error" : " validation errors")
|
||||
+ " detected: " + String.join("; ", errors));
|
||||
}
|
||||
rejectViolations(errors);
|
||||
if (thing != null) {
|
||||
thing = validateThing(thing, managedFields);
|
||||
}
|
||||
@@ -137,18 +150,170 @@ public class IotFleetIndexingService {
|
||||
|
||||
/** The schema of an enabled index. */
|
||||
public String describeIndex(String indexName, String region) {
|
||||
IotIndexingConfiguration configuration = getIndexingConfiguration(region);
|
||||
String schema = switch (indexName) {
|
||||
case THINGS_INDEX -> thingsSchema(configuration.thing());
|
||||
case THING_GROUPS_INDEX -> "OFF".equals(configuration.thingGroupIndexingMode()) ? null : "REGISTRY";
|
||||
default -> throw invalid("Unrecognized indexName " + indexName);
|
||||
};
|
||||
String schema = schema(indexName, getIndexingConfiguration(region));
|
||||
if (schema == null) {
|
||||
throw new AwsException("ResourceNotFoundException", "Index " + indexName + " does not exist", 404);
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public IotService.Page<ObjectNode> searchIndex(JsonNode request, String region) {
|
||||
if (!request.isObject()) {
|
||||
throw serializationError("request body", JsonNodeType.OBJECT);
|
||||
}
|
||||
String queryString = text(request.path("queryString"), "queryString");
|
||||
JsonNode maxResults = request.path("maxResults");
|
||||
if (present(maxResults) && !maxResults.isNumber()) {
|
||||
throw serializationError("maxResults", JsonNodeType.NUMBER);
|
||||
}
|
||||
// AWS truncates maxResults toward zero and saturates it at the int range, as this cast does.
|
||||
int pageSize = present(maxResults) ? (int) maxResults.asDouble() : Integer.MAX_VALUE;
|
||||
String requestedIndexName = text(request.path("indexName"), "indexName");
|
||||
String queryVersion = text(request.path("queryVersion"), "queryVersion");
|
||||
String nextToken = text(request.path("nextToken"), "nextToken");
|
||||
List<String> errors = new ArrayList<>();
|
||||
if (queryString == null) {
|
||||
errors.add("Value null at 'queryString' failed to satisfy constraint: Member must not be null");
|
||||
} else if (queryString.isEmpty()) {
|
||||
errors.add("Value '' at 'queryString' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 1");
|
||||
} else if (queryString.codePointCount(0, queryString.length()) > MAX_QUERY_STRING_LENGTH) {
|
||||
errors.add("Value '" + queryString + "' at 'queryString' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to " + MAX_QUERY_STRING_LENGTH);
|
||||
}
|
||||
if (pageSize < 1) {
|
||||
errors.add("Value '" + pageSize + "' at 'maxResults' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 1");
|
||||
}
|
||||
rejectViolations(errors);
|
||||
String indexName = requestedIndexName == null ? THINGS_INDEX : requestedIndexName;
|
||||
if (indexName.isEmpty()) {
|
||||
throw invalid("indexName cannot be empty.");
|
||||
}
|
||||
if (queryVersion != null && !"2017-09-30".equals(queryVersion)) {
|
||||
throw invalid("Invalid queryVersion. Expected one of: [2017-09-30]");
|
||||
}
|
||||
IotIndexingConfiguration configuration = getIndexingConfiguration(region);
|
||||
if (schema(indexName, configuration) == null) {
|
||||
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);
|
||||
String parameters = pageParameters(requestedIndexName, queryVersion, queryString);
|
||||
String after = pageAfter(nextToken, parameters);
|
||||
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 (query.test(document)) {
|
||||
matches.add(document);
|
||||
if (matches.size() > pageSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (matches.size() <= pageSize) {
|
||||
return new IotService.Page<>(matches, null);
|
||||
}
|
||||
matches.removeLast();
|
||||
return new IotService.Page<>(matches, pageToken(parameters, matches.getLast().path("thingName").asText()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A digest of the members a page token is bound to, each as sent: AWS treats an omitted index
|
||||
* name or version as different from its explicit default.
|
||||
*/
|
||||
private static String pageParameters(String indexName, String queryVersion, String queryString) {
|
||||
// The index name and version were validated against closed sets, so only the query can hold a newline.
|
||||
return UUID.nameUUIDFromBytes((indexName + "\n" + queryVersion + "\n" + queryString)
|
||||
.getBytes(StandardCharsets.UTF_8)).toString();
|
||||
}
|
||||
|
||||
/** The thing name a page token continues after, null for the first page. */
|
||||
private static String pageAfter(String nextToken, String parameters) {
|
||||
if (nextToken == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher token;
|
||||
try {
|
||||
token = PAGE_TOKEN.matcher(new String(Base64.getUrlDecoder().decode(nextToken), StandardCharsets.UTF_8));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalid("Invalid nextToken");
|
||||
}
|
||||
if (!token.matches() || !token.group(2).equals(pageCheck(token.group(1), token.group(3)))) {
|
||||
throw invalid("Invalid nextToken");
|
||||
}
|
||||
if (!token.group(1).equals(parameters)) {
|
||||
throw invalid("nextToken was from a request with different parameters");
|
||||
}
|
||||
return token.group(3);
|
||||
}
|
||||
|
||||
private static String pageToken(String parameters, String thingName) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
(parameters + pageCheck(parameters, thingName) + thingName).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** 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();
|
||||
}
|
||||
|
||||
/** The thing groups each thing of the region is a direct member of, in group name order. */
|
||||
private Map<String, List<String>> thingGroupNames(String region) {
|
||||
Map<String, List<String>> groups = new HashMap<>();
|
||||
for (IotThingGroup group : iotService.listThingGroups(region, null, null).items()) {
|
||||
for (String thingName : iotService.listThingsInThingGroup(group.getThingGroupName(), region)) {
|
||||
groups.computeIfAbsent(thingName, ignored -> new ArrayList<>()).add(group.getThingGroupName());
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
/** A thing's index document; like AWS it leaves out a member the thing does not have. */
|
||||
private static ObjectNode document(Thing thing, List<String> thingGroupNames) {
|
||||
ObjectNode document = JsonNodeFactory.instance.objectNode();
|
||||
document.put("thingName", thing.getThingName());
|
||||
document.put("thingId", thing.getThingId());
|
||||
if (thing.getThingTypeName() != null) {
|
||||
document.put("thingTypeName", thing.getThingTypeName());
|
||||
}
|
||||
if (!thingGroupNames.isEmpty()) {
|
||||
thingGroupNames.forEach(document.putArray("thingGroupNames")::add);
|
||||
}
|
||||
if (thing.getAttributes() != null && !thing.getAttributes().isEmpty()) {
|
||||
ObjectNode attributes = document.putObject("attributes");
|
||||
thing.getAttributes().forEach(attributes::put);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
/** The schema of the named index, null while it is disabled. */
|
||||
private static String schema(String indexName, IotIndexingConfiguration configuration) {
|
||||
return switch (indexName) {
|
||||
case THINGS_INDEX -> thingsSchema(configuration.thing());
|
||||
case THING_GROUPS_INDEX -> "OFF".equals(configuration.thingGroupIndexingMode()) ? null : "REGISTRY";
|
||||
default -> throw invalid("Unrecognized indexName " + indexName);
|
||||
};
|
||||
}
|
||||
|
||||
/** The managed fields AWS derives from the thing indexing modes; none while indexing is OFF. */
|
||||
public static List<Field> thingManagedFields(ThingIndexing thing) {
|
||||
if ("OFF".equals(thing.thingIndexingMode())) {
|
||||
@@ -289,6 +454,13 @@ public class IotFleetIndexingService {
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void rejectViolations(List<String> errors) {
|
||||
if (!errors.isEmpty()) {
|
||||
throw invalid(errors.size() + (errors.size() == 1 ? " validation error" : " validation errors")
|
||||
+ " detected: " + String.join("; ", errors));
|
||||
}
|
||||
}
|
||||
|
||||
private static String enumError(String value, String path, List<String> allowed) {
|
||||
return "Value '" + value + "' at '" + path
|
||||
+ "' failed to satisfy constraint: Member must satisfy enum value set: " + allowed;
|
||||
|
||||
Reference in new issue
Block a user