feat(iot): evaluate the SQL subset of topic rules (#3021)

* feat(iot): evaluate the SQL subset of topic rules

Topic rules only extracted the FROM topic filter and sent the whole
payload to every action. The SELECT list and the WHERE clause were
ignored, so a rule fired on every matching topic and its actions never
received the projected document.

Add a small hand written parser and evaluator under services/iot/rules
for the SELECT/FROM/WHERE subset AWS rules use most: '*', dotted field
paths, topic() and topic(n) with optional AS aliases, and a WHERE of
startswith, endswith, comparison operators, AND, OR, NOT and
parentheses. A missing field or a mismatched type is Undefined as in
AWS, so an undefined predicate never fires the rule.

A statement outside the subset is not rejected. It is stored as sent and
keeps its previous behaviour, firing on every matching topic with the
whole payload, and logs one WARN naming the token that could not be
parsed. floci.services.iot.rule-sql-strict, off by default, rejects it
with SqlParseException the way AWS does.

Each rule is parsed once: the result is held on the rule object as a
transient field that is never persisted and is rebuilt on the first
publish after a restart.

* fix(iot): count real tokens in the rule SQL limit and compare numbers exactly

The token limit counted the end marker, so a statement with exactly 1000
tokens was rejected and the error named the end of input. Mixing a whole
number with a decimal literal went through double, so 9007199254740993
compared equal to 9007199254740992.0.

* fix(iot): keep rule SQL decimal literals exact

Double.parseDouble rounded a decimal literal before evaluation, so
level = 9007199254740993.0 matched a payload holding 9007199254740992.

* fix(iot): treat a rule SQL number too large for a double as Undefined

Comparing an infinity, which Jackson produces for a JSON number wider than
a double, converted both operands to the same infinity and made distinct
values compare equal.

* fix(iot): follow the AWS IoT SQL operator tables and harden the rule parser

The comparison and logic semantics did not match the operator tables in
the AWS IoT SQL reference: = and <> on mismatched types are false and
true rather than Undefined, JSON null is a value that equals only NULL,
the ordering operators convert numeric strings, AND, OR and NOT accept
the strings "true" and "false" and give Undefined for anything else
instead of three valued logic, and startswith and endswith convert
non-string arguments. String literals may use double quotes, as AWS's
own examples do, and an unsupported function is named before its
arguments are parsed so the WARN reports the function rather than a
token inside it.

Add a corpus of AWS reference statements sorted into parsed and
unparsed, a deterministic mutation fuzz that requires the parser to
raise nothing but RuleSqlParseException and the evaluator nothing at
all, and tables for keyword prefixed field names, spacing, associativity,
unicode and literal forms.

* fix(iot): treat a rule SQL numeric string with an overflowing exponent as Undefined

A payload string such as "1e-2147483648" matches the numeric string form
but BigDecimal cannot hold its exponent, and the NumberFormatException
escaped the publish path. It now evaluates as Undefined, and the fuzz
payloads carry such strings.

* docs(iot): name the AWS null functions, not IS NULL, in the rule SQL limitations

* fix(iot): read rule SQL payload numbers exactly instead of through a double

Jackson read payload floats as doubles, so 9007199254740993.0 arrived
as 9007199254740992, 1e-400 as 0 and 0.30000000000000004 as 0.3 before
the evaluator compared them against an exact literal, and a predicate
could fire or stay silent for the wrong reason. The representability
guard only caught the infinity case of that loss.

Payload numbers are now read as BigDecimal, kept as written, so every
comparison is exact at any size or precision as AWS's Decimal is, a
projected number keeps its text, and the infinity handling is gone
because no double is ever produced.

* docs(iot): awsIotSqlVersion is stored and echoed, only its array semantics are not modelled
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-06 14:30:36 -05:00
1 parent 94b9665c32
commit d45c64545d
19 files changed
+2335 -20

No files matched your search

@@ -764,6 +764,14 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
/**
* Reject a topic rule whose SQL falls outside the subset Floci evaluates, as AWS does.
* Off by default, so such a rule is stored and keeps firing on every matching topic
* with the whole payload.
*/
@WithDefault("false")
boolean ruleSqlStrict();
MqttConfig mqtt();
}
@@ -25,6 +25,10 @@ import io.github.hectorvent.floci.services.iot.model.IotThingType;
import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.iot.model.Thing;
import io.github.hectorvent.floci.services.iot.rules.RuleSql;
import io.github.hectorvent.floci.services.iot.rules.RuleSqlEvaluator;
import io.github.hectorvent.floci.services.iot.rules.RuleSqlParseException;
import io.github.hectorvent.floci.services.iot.rules.RuleSqlParser;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
@@ -102,6 +106,7 @@ public class IotService {
private final FirehoseService firehoseService;
private final CloudWatchLogsService cloudWatchLogsService;
private final FlociCertificateAuthority certificateAuthority;
private final RuleSqlEvaluator ruleSqlEvaluator;
@Inject
public IotService(StorageFactory storageFactory,
@@ -190,6 +195,7 @@ public class IotService {
this.firehoseService = firehoseService;
this.cloudWatchLogsService = cloudWatchLogsService;
this.certificateAuthority = certificateAuthority;
this.ruleSqlEvaluator = new RuleSqlEvaluator(objectMapper);
}
public String describeEndpoint(String endpointType) {
@@ -990,6 +996,7 @@ public class IotService {
validateAction(errorAction);
rule.setErrorActionJson(errorAction.isObject() ? errorAction.toString() : null);
rule.setCreatedAt(createdAt == null ? Instant.now() : createdAt);
rule.setCompiledSql(compileSql(ruleName, rule.getSql(), config.services().iot().ruleSqlStrict()));
topicRuleStore.put(topicRuleKey(region, ruleName), rule);
return rule;
}
@@ -1006,6 +1013,26 @@ public class IotService {
}
}
/**
* Parses a rule's SQL. A statement outside the subset Floci evaluates is not rejected by
* default: it is stored as it was sent and keeps the behaviour it had before this parser
* existed, firing on every publish matching its topic filter with the whole payload.
* Setting {@code floci.services.iot.rule-sql-strict} rejects it the way AWS does.
*/
private RuleSql.Compilation compileSql(String ruleName, String sql, boolean strict) {
try {
return RuleSql.Compilation.of(RuleSqlParser.parse(sql));
} catch (RuleSqlParseException e) {
if (strict) {
throw new AwsException("SqlParseException",
"Invalid topic rule SQL for " + ruleName + ": " + e.getMessage(), 400);
}
LOG.warnv("Topic rule {0} is not evaluated: its SQL is outside the subset Floci understands ({1}). "
+ "It keeps firing on every matching topic with the whole payload.", ruleName, e.getMessage());
return RuleSql.Compilation.PASSTHROUGH;
}
}
public IotTopicRule getTopicRule(String ruleName, String region) {
return topicRuleStore.get(topicRuleKey(region, ruleName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Topic rule not found: " + ruleName, 404));
@@ -1036,12 +1063,43 @@ public class IotService {
return;
}
for (IotTopicRule rule : rulesForPublish(region)) {
if (!rule.isRuleDisabled() && topicMatches(extractTopicPattern(rule.getSql()), topic)) {
executeTopicRule(rule, topic, eventPayload);
if (!rule.isRuleDisabled()) {
matchAndProject(rule, topic, eventPayload)
.ifPresent(document -> executeTopicRule(rule, topic, eventPayload, document));
}
}
}
/**
* Returns the document the rule's actions should receive, or empty when the rule does not
* fire for this message. Rules whose SQL could not be parsed take the pre-parser path: the
* topic filter is read straight out of the SQL and the payload is forwarded untouched.
*/
private Optional<byte[]> matchAndProject(IotTopicRule rule, String topic, byte[] payload) {
RuleSql query = ruleQuery(rule);
if (query == null) {
return topicMatches(extractTopicPattern(rule.getSql()), topic) ? Optional.of(payload) : Optional.empty();
}
if (!topicMatches(query.topicFilter(), topic)) {
return Optional.empty();
}
return ruleSqlEvaluator.evaluate(rule.getRuleName(), query, topic, payload);
}
/**
* The rule's parsed statement, or null when its SQL is outside the subset. A rule restored
* from storage is parsed here on its first publish; one written through the API already
* carries its parse.
*/
private RuleSql ruleQuery(IotTopicRule rule) {
RuleSql.Compilation compiled = rule.getCompiledSql();
if (compiled == null) {
compiled = compileSql(rule.getRuleName(), rule.getSql(), false);
rule.setCompiledSql(compiled);
}
return compiled.query();
}
private List<IotTopicRule> rulesForPublish(String region) {
if (region != null) {
return listTopicRules(region);
@@ -1140,11 +1198,12 @@ public class IotService {
}
/**
* Runs the actions of a matching rule. One failing action never fails the publish or the actions
* after it, as on AWS: the failure is logged, and once every action ran the rule's error action,
* if it has one, receives the failure document listing every action that failed.
* Runs the actions of a matching rule on the document its SQL produced. One failing action never
* fails the publish or the actions after it, as on AWS: the failure is logged, and once every
* action ran the rule's error action, if it has one, receives the failure document listing every
* action that failed, with the original payload as published.
*/
private void executeTopicRule(IotTopicRule rule, String topic, byte[] payload) {
private void executeTopicRule(IotTopicRule rule, String topic, byte[] originalPayload, byte[] document) {
String ruleRegion = AwsArnUtils.regionOrDefault(rule.getRuleArn(), config.defaultRegion());
List<ObjectNode> failures = new ArrayList<>();
for (JsonNode action : storedJson(rule.getRuleName(), rule.getActionsJson())) {
@@ -1155,7 +1214,7 @@ public class IotService {
}
JsonNode config = action.get(type);
try {
runAction(rule, type, config, payload, ruleRegion);
runAction(rule, type, config, document, ruleRegion);
} catch (RuntimeException e) {
LOG.warnv(e, "Action {0} of topic rule {1} failed", type, rule.getRuleName());
failures.add(failure(type, config, e));
@@ -1171,7 +1230,7 @@ public class IotService {
return;
}
try {
runAction(rule, type, errorAction.get(type), failureDocument(rule, topic, payload, failures), ruleRegion);
runAction(rule, type, errorAction.get(type), failureDocument(rule, topic, originalPayload, failures), ruleRegion);
} catch (RuntimeException e) {
LOG.warnv(e, "Error action {0} of topic rule {1} failed", type, rule.getRuleName());
}
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.iot.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.github.hectorvent.floci.services.iot.rules.RuleSql;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@@ -11,6 +13,14 @@ public class IotTopicRule {
private String ruleName;
private String ruleArn;
private String sql;
/**
* The parsed form of {@link #sql}, so a rule is parsed once instead of once per message.
* The SQL string stays the source of truth, so this is never persisted and is rebuilt on
* the first publish after a restart.
*/
@JsonIgnore
private transient volatile RuleSql.Compilation compiledSql;
private String description;
private boolean ruleDisabled;
private String actionsJson = "[]";
@@ -41,6 +51,15 @@ public class IotTopicRule {
public void setSql(String sql) {
this.sql = sql;
this.compiledSql = null;
}
public RuleSql.Compilation getCompiledSql() {
return compiledSql;
}
public void setCompiledSql(RuleSql.Compilation compiledSql) {
this.compiledSql = compiledSql;
}
public String getDescription() {
@@ -0,0 +1,115 @@
package io.github.hectorvent.floci.services.iot.rules;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.DecimalNode;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.TextNode;
import java.math.BigDecimal;
import java.util.List;
/**
* A parsed AWS IoT topic rule statement: the {@code SELECT} list, the {@code FROM} topic
* filter, and the optional {@code WHERE} predicate. Produced by {@link RuleSqlParser} and
* consumed by {@link RuleSqlEvaluator}.
*/
public record RuleSql(List<Projection> projections, String topicFilter, Expr where) {
public RuleSql {
projections = List.copyOf(projections);
}
/**
* True when {@code *} is the only select item. Such a rule forwards the published bytes
* unchanged instead of rebuilding a document, so the payload keeps its exact formatting
* and, when there is no {@code WHERE}, does not have to be JSON at all.
*/
public boolean isSelectAllOnly() {
return projections.size() == 1 && projections.getFirst() instanceof SelectAll;
}
/**
* The result of parsing a rule's SQL once. {@code query} is null when the statement is
* outside the subset Floci evaluates. Such a rule keeps the behaviour it had before this
* parser existed: it fires on every publish matching its topic filter and its actions
* receive the whole payload.
*/
public record Compilation(RuleSql query) {
public static final Compilation PASSTHROUGH = new Compilation(null);
public static Compilation of(RuleSql query) {
return new Compilation(query);
}
}
public sealed interface Projection permits SelectAll, Aliased {
}
/** The {@code *} select item: every field of the payload. */
public record SelectAll() implements Projection {
}
/** A select item written under {@code alias} in the projected document. */
public record Aliased(Expr expression, String alias) implements Projection {
}
public sealed interface Expr permits Path, Literal, Call, Comparison, Conjunction, Disjunction, Negation {
}
/** A dotted field path such as {@code state.reported.temperature}. */
public record Path(List<String> segments) implements Expr {
public Path {
segments = List.copyOf(segments);
}
}
public record Literal(JsonNode value) implements Expr {
}
/** A supported function call: {@code topic}, {@code startswith} or {@code endswith}. */
public record Call(String function, List<Expr> arguments) implements Expr {
public Call {
arguments = List.copyOf(arguments);
}
}
public record Comparison(Expr left, Operator operator, Expr right) implements Expr {
}
public record Conjunction(Expr left, Expr right) implements Expr {
}
public record Disjunction(Expr left, Expr right) implements Expr {
}
public record Negation(Expr operand) implements Expr {
}
public enum Operator {
EQUAL, NOT_EQUAL, LESS, LESS_OR_EQUAL, GREATER, GREATER_OR_EQUAL
}
public static Literal text(String value) {
return new Literal(TextNode.valueOf(value));
}
public static Literal number(long value) {
return new Literal(LongNode.valueOf(value));
}
/** Kept as a {@code BigDecimal} so a literal a double cannot hold exactly still compares exactly. */
public static Literal decimal(BigDecimal value) {
return new Literal(DecimalNode.valueOf(value));
}
public static Literal bool(boolean value) {
return new Literal(BooleanNode.valueOf(value));
}
public static Literal nullValue() {
return new Literal(NullNode.getInstance());
}
}
@@ -0,0 +1,276 @@
package io.github.hectorvent.floci.services.iot.rules;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Call;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Expr;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Literal;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Projection;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.SelectAll;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* Evaluates a parsed topic rule statement against one published message, following the
* operator and conversion tables of the AWS IoT SQL reference.
*
* <p>A value AWS reports as {@code Undefined} (a missing field, an out of range topic segment,
* a function argument that cannot be converted) is a {@code null} {@link JsonNode}. It spreads:
* a comparison, {@code AND}, {@code OR} or {@code NOT} with an undefined operand is undefined,
* and a rule fires only when its {@code WHERE} is true. JSON {@code null} is not undefined: it
* is a value that equals only itself.
*
* <p>Payload numbers are read as {@code BigDecimal}, never through a {@code double}, so they
* compare exactly at any size or precision, as AWS's Decimal does.
*/
public final class RuleSqlEvaluator {
private static final Logger LOG = Logger.getLogger(RuleSqlEvaluator.class);
/** The string forms AWS converts to a number when an ordering operator meets a string. */
private static final Pattern NUMERIC_STRING = Pattern.compile("-?\\d+(\\.\\d+)?([eE]-?\\d+)?");
private final ObjectMapper objectMapper;
private final ObjectReader payloadReader;
public RuleSqlEvaluator(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.payloadReader = objectMapper.reader()
.with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
.with(JsonNodeFactory.withExactBigDecimals(true));
}
/**
* Returns the document the rule's actions should receive, or empty when the rule does
* not fire for this message.
*/
public Optional<byte[]> evaluate(String ruleName, RuleSql query, String topic, byte[] payload) {
byte[] message = payload == null ? new byte[0] : payload;
if (query.isSelectAllOnly() && query.where() == null) {
return Optional.of(message);
}
ObjectNode document = readObject(message);
if (document == null) {
LOG.debugv("Topic rule {0} skipped a payload that is not a JSON object on topic {1}", ruleName, topic);
return Optional.empty();
}
if (query.where() != null && !Boolean.TRUE.equals(truth(value(query.where(), topic, document)))) {
return Optional.empty();
}
return Optional.of(query.isSelectAllOnly() ? message : project(query, topic, document));
}
private ObjectNode readObject(byte[] payload) {
if (payload.length == 0) {
return null;
}
try {
JsonNode document = payloadReader.readTree(payload);
return document instanceof ObjectNode object ? object : null;
} catch (IOException e) {
LOG.debugv(e, "Topic rule payload is not JSON");
return null;
}
}
/**
* Builds the projected document. Every payload field is copied first when {@code *} is
* present, so a select item whose alias collides with a payload field overwrites it,
* which is what AWS does for statements such as {@code SELECT *, topic() as topic}.
*/
private byte[] project(RuleSql query, String topic, ObjectNode document) {
ObjectNode projected = objectMapper.createObjectNode();
if (query.projections().stream().anyMatch(SelectAll.class::isInstance)) {
projected.setAll(document);
}
for (Projection projection : query.projections()) {
if (projection instanceof Aliased aliased) {
JsonNode value = value(aliased.expression(), topic, document);
if (value != null) {
projected.set(aliased.alias(), value);
}
}
}
return projected.toString().getBytes(StandardCharsets.UTF_8);
}
private JsonNode value(Expr expression, String topic, ObjectNode document) {
return switch (expression) {
case Literal literal -> literal.value();
case Path path -> resolve(path, document);
case Call call -> call(call, topic, document);
case Comparison comparison -> compare(comparison, topic, document);
case Conjunction conjunction -> booleanNode(and(
truth(value(conjunction.left(), topic, document)),
truth(value(conjunction.right(), topic, document))));
case Disjunction disjunction -> booleanNode(or(
truth(value(disjunction.left(), topic, document)),
truth(value(disjunction.right(), topic, document))));
case Negation negation -> {
Boolean operand = truth(value(negation.operand(), topic, document));
yield operand == null ? null : booleanNode(!operand);
}
};
}
private JsonNode resolve(Path path, ObjectNode document) {
JsonNode current = document;
for (String segment : path.segments()) {
if (!(current instanceof ObjectNode object)) {
return null;
}
current = object.get(segment);
if (current == null) {
return null;
}
}
return current;
}
private JsonNode call(Call call, String topic, ObjectNode document) {
if (call.function().equals("topic")) {
if (call.arguments().isEmpty()) {
return TextNode.valueOf(topic);
}
return call.arguments().getFirst() instanceof Literal position
? topicSegment(topic, position.value().asLong())
: null;
}
String subject = text(value(call.arguments().get(0), topic, document));
String argument = text(value(call.arguments().get(1), topic, document));
if (subject == null || argument == null) {
return null;
}
return booleanNode(call.function().equals("startswith")
? subject.startsWith(argument)
: subject.endsWith(argument));
}
private JsonNode topicSegment(String topic, long position) {
String[] segments = topic.split("/", -1);
return position < 1 || position > segments.length ? null : TextNode.valueOf(segments[(int) position - 1]);
}
/**
* AWS's standard conversion to String: numbers, booleans, arrays and objects convert,
* {@code null} and Undefined do not.
*/
private String text(JsonNode value) {
if (value == null || value.isNull()) {
return null;
}
if (value.isTextual()) {
return value.textValue();
}
return value.isContainerNode() ? value.toString() : value.asText();
}
private JsonNode compare(Comparison comparison, String topic, ObjectNode document) {
JsonNode left = value(comparison.left(), topic, document);
JsonNode right = value(comparison.right(), topic, document);
if (left == null || right == null) {
return null;
}
Operator operator = comparison.operator();
if (operator == Operator.EQUAL || operator == Operator.NOT_EQUAL) {
return booleanNode(equal(left, right) == (operator == Operator.EQUAL));
}
BigDecimal leftNumber = decimal(left);
BigDecimal rightNumber = decimal(right);
return leftNumber == null || rightNumber == null
? null
: booleanNode(matches(operator, leftNumber.compareTo(rightNumber)));
}
/**
* AWS compares two numbers by value and everything else by type and value, so operands
* of different types are simply not equal, and {@code null} equals only {@code null}.
*/
private boolean equal(JsonNode left, JsonNode right) {
if (left.isNumber() && right.isNumber()) {
return left.decimalValue().compareTo(right.decimalValue()) == 0;
}
return left.getNodeType() == right.getNodeType() && left.equals(right);
}
/**
* The ordering operators convert both operands to a number: numbers as they are, strings
* when they look like a number, anything else is Undefined. A string whose exponent is
* beyond what a BigDecimal can hold looks like a number but is not one either.
*/
private BigDecimal decimal(JsonNode value) {
if (value.isNumber()) {
return value.decimalValue();
}
if (value.isTextual() && NUMERIC_STRING.matcher(value.textValue()).matches()) {
try {
return new BigDecimal(value.textValue());
} catch (NumberFormatException e) {
LOG.debugv("Numeric string {0} is out of range and evaluates as Undefined", value.textValue());
return null;
}
}
return null;
}
private boolean matches(Operator operator, int comparison) {
return switch (operator) {
case EQUAL -> comparison == 0;
case NOT_EQUAL -> comparison != 0;
case LESS -> comparison < 0;
case LESS_OR_EQUAL -> comparison <= 0;
case GREATER -> comparison > 0;
case GREATER_OR_EQUAL -> comparison >= 0;
};
}
/** AWS gives Undefined for {@code AND} and {@code OR} unless both operands convert to a boolean. */
private Boolean and(Boolean left, Boolean right) {
return left == null || right == null ? null : left && right;
}
private Boolean or(Boolean left, Boolean right) {
return left == null || right == null ? null : left || right;
}
/** A boolean, or the strings {@code "true"} and {@code "false"} in any case; anything else is Undefined. */
private Boolean truth(JsonNode value) {
if (value == null) {
return null;
}
if (value.isBoolean()) {
return value.booleanValue();
}
if (value.isTextual()) {
if (value.textValue().equalsIgnoreCase("true")) {
return Boolean.TRUE;
}
if (value.textValue().equalsIgnoreCase("false")) {
return Boolean.FALSE;
}
}
return null;
}
private JsonNode booleanNode(Boolean value) {
return value == null ? null : BooleanNode.valueOf(value);
}
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.iot.rules;
/**
* Raised when a topic rule statement falls outside the SQL subset Floci evaluates. The
* offending token and its zero-based offset in the statement are carried so callers can
* name them in a warning or in an AWS {@code SqlParseException}.
*/
public class RuleSqlParseException extends RuntimeException {
private final String token;
private final int position;
public RuleSqlParseException(String reason, String token, int position) {
super(reason + ": '" + token + "' at position " + position);
this.token = token;
this.position = position;
}
public String token() {
return token;
}
public int position() {
return position;
}
}
@@ -0,0 +1,404 @@
package io.github.hectorvent.floci.services.iot.rules;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Call;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Expr;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Literal;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Projection;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.SelectAll;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
* Recursive descent parser for the subset of the AWS IoT rules SQL dialect Floci evaluates:
*
* <pre>
* statement := SELECT item (',' item)* FROM string [WHERE expr]
* item := '*' | operand [AS identifier]
* expr := term (OR term)*
* term := factor (AND factor)*
* factor := NOT factor | '(' expr ')' | operand [comparison operand]
* comparison := '=' | '<>' | '!=' | '<' | '<=' | '>' | '>='
* operand := path | literal | call
* call := topic '(' [integer] ')' | (startswith | endswith) '(' operand ',' operand ')'
* path := identifier ('.' identifier)*
* literal := 'string' | "string" | number | TRUE | FALSE | NULL
* </pre>
*
* Keywords and function names are case insensitive, field names are case sensitive, and anything
* outside the grammar raises {@link RuleSqlParseException} naming the offending token.
*/
public final class RuleSqlParser {
private static final Set<String> KEYWORDS =
Set.of("SELECT", "FROM", "WHERE", "AS", "AND", "OR", "NOT", "TRUE", "FALSE", "NULL");
/**
* Bounds the work one statement can cost, counting real tokens only: {@link #tokenize} appends
* an end marker. Real rules are a few dozen tokens, so this only stops a pathological statement
* from driving the recursive descent, or the equally recursive evaluation of the tree it
* produces, into a stack overflow.
*/
private static final int MAX_TOKENS = 1000;
private static final String TOPIC = "topic";
private static final Set<String> STRING_PREDICATES = Set.of("startswith", "endswith");
private final List<Token> tokens;
private int index;
private RuleSqlParser(List<Token> tokens) {
this.tokens = tokens;
}
public static RuleSql parse(String sql) {
if (sql == null || sql.isBlank()) {
throw new RuleSqlParseException("Empty topic rule SQL statement", "", 0);
}
List<Token> tokens = tokenize(sql);
if (tokens.size() - 1 > MAX_TOKENS) {
Token beyondLimit = tokens.get(MAX_TOKENS);
throw new RuleSqlParseException("Statement has more than " + MAX_TOKENS + " tokens",
beyondLimit.text(), beyondLimit.position());
}
return new RuleSqlParser(tokens).statement();
}
private RuleSql statement() {
expectKeyword("SELECT");
List<Projection> projections = new ArrayList<>();
projections.add(projection());
while (matchSymbol(",")) {
projections.add(projection());
}
expectKeyword("FROM");
Token filter = peek();
if (filter.kind() != Kind.STRING || filter.text().isBlank()) {
throw fail("Expected a quoted topic filter after FROM", filter);
}
advance();
Expr where = matchKeyword("WHERE") ? expression() : null;
Token trailing = peek();
if (trailing.kind() != Kind.END) {
throw fail("Unsupported trailing input", trailing);
}
return new RuleSql(projections, filter.text(), where);
}
private Projection projection() {
if (matchSymbol("*")) {
return new SelectAll();
}
Token start = peek();
Expr expression = operand();
if (matchKeyword("AS")) {
Token alias = peek();
if (alias.kind() != Kind.IDENTIFIER) {
throw fail("Expected an alias after AS", alias);
}
advance();
return new Aliased(expression, alias.text());
}
return new Aliased(expression, defaultAlias(expression, start));
}
private String defaultAlias(Expr expression, Token start) {
return switch (expression) {
case Path path -> path.segments().getLast();
case Call call -> call.function();
default -> throw fail("Select item needs an AS alias", start);
};
}
private Expr expression() {
Expr left = term();
while (matchKeyword("OR")) {
left = new Disjunction(left, term());
}
return left;
}
private Expr term() {
Expr left = factor();
while (matchKeyword("AND")) {
left = new Conjunction(left, factor());
}
return left;
}
private Expr factor() {
if (matchKeyword("NOT")) {
return new Negation(factor());
}
if (matchSymbol("(")) {
Expr grouped = expression();
expectSymbol(")");
return grouped;
}
Expr left = operand();
Operator operator = comparisonOperator();
return operator == null ? left : new Comparison(left, operator, operand());
}
private Operator comparisonOperator() {
Token token = peek();
if (token.kind() != Kind.SYMBOL) {
return null;
}
Operator operator = switch (token.text()) {
case "=" -> Operator.EQUAL;
case "<>", "!=" -> Operator.NOT_EQUAL;
case "<" -> Operator.LESS;
case "<=" -> Operator.LESS_OR_EQUAL;
case ">" -> Operator.GREATER;
case ">=" -> Operator.GREATER_OR_EQUAL;
default -> null;
};
if (operator != null) {
advance();
}
return operator;
}
private Expr operand() {
Token token = peek();
switch (token.kind()) {
case STRING -> {
advance();
return RuleSql.text(token.text());
}
case NUMBER -> {
advance();
return numberLiteral(token);
}
case KEYWORD -> {
String keyword = token.text().toUpperCase(Locale.ROOT);
if (keyword.equals("TRUE") || keyword.equals("FALSE")) {
advance();
return RuleSql.bool(keyword.equals("TRUE"));
}
if (keyword.equals("NULL")) {
advance();
return RuleSql.nullValue();
}
throw fail("Unexpected keyword", token);
}
case IDENTIFIER -> {
advance();
return peekIsSymbol("(") ? call(token) : path(token);
}
default -> throw fail("Expected a field, literal or function", token);
}
}
private Literal numberLiteral(Token token) {
try {
return token.text().indexOf('.') < 0
? RuleSql.number(Long.parseLong(token.text()))
: RuleSql.decimal(new BigDecimal(token.text()));
} catch (NumberFormatException e) {
throw fail("Number is out of range", token);
}
}
private Expr path(Token first) {
List<String> segments = new ArrayList<>();
segments.add(first.text());
while (matchSymbol(".")) {
Token segment = peek();
if (segment.kind() != Kind.IDENTIFIER) {
throw fail("Expected a field name after '.'", segment);
}
advance();
segments.add(segment.text());
}
return new Path(segments);
}
private Expr call(Token name) {
String function = name.text().toLowerCase(Locale.ROOT);
if (!TOPIC.equals(function) && !STRING_PREDICATES.contains(function)) {
throw fail("Unsupported function", name);
}
expectSymbol("(");
List<Expr> arguments = new ArrayList<>();
if (!peekIsSymbol(")")) {
arguments.add(operand());
while (matchSymbol(",")) {
arguments.add(operand());
}
}
expectSymbol(")");
if (TOPIC.equals(function)) {
validateTopicArguments(arguments, name);
} else if (arguments.size() != 2) {
throw fail("Function " + name.text() + " takes two arguments", name);
}
return new Call(function, arguments);
}
private void validateTopicArguments(List<Expr> arguments, Token name) {
if (arguments.isEmpty()) {
return;
}
if (arguments.size() != 1
|| !(arguments.getFirst() instanceof Literal literal)
|| !literal.value().isIntegralNumber()
|| literal.value().asLong() < 1) {
throw fail("topic() takes no argument or a segment number starting at 1", name);
}
}
private Token peek() {
return tokens.get(index);
}
private void advance() {
if (peek().kind() != Kind.END) {
index++;
}
}
private boolean peekIsSymbol(String symbol) {
return peek().kind() == Kind.SYMBOL && peek().text().equals(symbol);
}
private boolean matchSymbol(String symbol) {
if (!peekIsSymbol(symbol)) {
return false;
}
advance();
return true;
}
private void expectSymbol(String symbol) {
if (!matchSymbol(symbol)) {
throw fail("Expected '" + symbol + "'", peek());
}
}
private boolean matchKeyword(String keyword) {
if (peek().kind() != Kind.KEYWORD || !peek().text().equalsIgnoreCase(keyword)) {
return false;
}
advance();
return true;
}
private void expectKeyword(String keyword) {
if (!matchKeyword(keyword)) {
throw fail("Expected " + keyword, peek());
}
}
private RuleSqlParseException fail(String reason, Token token) {
return new RuleSqlParseException(reason, token.text(), token.position());
}
private static List<Token> tokenize(String sql) {
List<Token> tokens = new ArrayList<>();
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (Character.isWhitespace(c)) {
i++;
} else if (c == '\'' || c == '"') {
i = readString(sql, i, tokens);
} else if (isNumberStart(sql, i)) {
i = readNumber(sql, i, tokens);
} else if (Character.isLetter(c) || c == '_') {
i = readWord(sql, i, tokens);
} else {
i = readSymbol(sql, i, tokens);
}
}
tokens.add(new Token(Kind.END, "", sql.length()));
return tokens;
}
private static boolean isNumberStart(String sql, int i) {
char c = sql.charAt(i);
return Character.isDigit(c) || (c == '-' && i + 1 < sql.length() && Character.isDigit(sql.charAt(i + 1)));
}
/** A string in single or double quotes, as AWS's own examples use both; the quote is doubled to escape it. */
private static int readString(String sql, int start, List<Token> tokens) {
char quote = sql.charAt(start);
StringBuilder value = new StringBuilder();
int i = start + 1;
while (i < sql.length()) {
char c = sql.charAt(i);
if (c != quote) {
value.append(c);
i++;
} else if (i + 1 < sql.length() && sql.charAt(i + 1) == quote) {
value.append(quote);
i += 2;
} else {
tokens.add(new Token(Kind.STRING, value.toString(), start));
return i + 1;
}
}
throw new RuleSqlParseException("Unterminated string literal", String.valueOf(quote), start);
}
private static int readNumber(String sql, int start, List<Token> tokens) {
int i = start + 1;
boolean decimalPoint = false;
while (i < sql.length()) {
char c = sql.charAt(i);
if (Character.isDigit(c)) {
i++;
} else if (c == '.' && !decimalPoint && i + 1 < sql.length() && Character.isDigit(sql.charAt(i + 1))) {
decimalPoint = true;
i++;
} else {
break;
}
}
tokens.add(new Token(Kind.NUMBER, sql.substring(start, i), start));
return i;
}
private static int readWord(String sql, int start, List<Token> tokens) {
int i = start;
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
i++;
}
String word = sql.substring(start, i);
Kind kind = KEYWORDS.contains(word.toUpperCase(Locale.ROOT)) ? Kind.KEYWORD : Kind.IDENTIFIER;
tokens.add(new Token(kind, word, start));
return i;
}
private static int readSymbol(String sql, int start, List<Token> tokens) {
String two = start + 1 < sql.length() ? sql.substring(start, start + 2) : "";
if (two.equals("<>") || two.equals("<=") || two.equals(">=") || two.equals("!=")) {
tokens.add(new Token(Kind.SYMBOL, two, start));
return start + 2;
}
String one = sql.substring(start, start + 1);
if (!",.()*=<>".contains(one)) {
throw new RuleSqlParseException("Unsupported character", one, start);
}
tokens.add(new Token(Kind.SYMBOL, one, start));
return start + 1;
}
private enum Kind {
IDENTIFIER, KEYWORD, STRING, NUMBER, SYMBOL, END
}
private record Token(Kind kind, String text, int position) {
}
}