mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(iot): rule SQL message functions, isNull, isUndefined, IN and array literals (#3036)
Add clientid(), timestamp(), accountid() and newuuid(), the isNull() and isUndefined() functions, the IN operator against a payload array or an array literal, and array literals such as [lat, long], each following the tables in the AWS IoT SQL reference. Equality extends to arrays (element by element, in order) and objects (by key, in any order). clientid() needs the MQTT client that published, so publish and handlePublish carry the client id: the broker passes its session's client id and an IoT Data Publish over HTTP passes none, which the function reports as n/a as AWS does. principal() stays unparsed: it returns the certificate a device authenticated with, and the broker does not verify one yet.
This commit is contained in:
1 parent
90fa707145
commit
b88034cd1d
18 files changed
+665
-104
No files matched your search
@@ -91,7 +91,7 @@ public class IotDataController {
|
||||
byte[] payload) {
|
||||
// Unsigned or non-SigV4 publishes carry no usable region; both count as unresolved
|
||||
String region = regionResolver.resolveRegionFromAuthOrNull(headers.getHeaderString("Authorization"));
|
||||
iotService.publish(topic, payload == null ? new byte[0] : payload, Boolean.TRUE.equals(retain), qos == null ? 0 : qos, region);
|
||||
iotService.publish(topic, payload == null ? new byte[0] : payload, Boolean.TRUE.equals(retain), qos == null ? 0 : qos, region, null);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
|
||||
@@ -446,7 +446,7 @@ public class IotMqttBrokerService {
|
||||
return;
|
||||
}
|
||||
|
||||
iotService.get().publish(topic, payload, message.isRetain(), message.qosLevel().value(), null);
|
||||
iotService.get().publish(topic, payload, message.isRetain(), message.qosLevel().value(), null, session.clientId());
|
||||
fanOut(topic, payload, false);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ 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.RuleSqlContext;
|
||||
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;
|
||||
@@ -52,6 +53,7 @@ import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateEncodingException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -214,7 +216,7 @@ public class IotService {
|
||||
this.cloudWatchLogsService = cloudWatchLogsService;
|
||||
this.certificateAuthority = certificateAuthority;
|
||||
this.policyEvaluator = policyEvaluator;
|
||||
this.ruleSqlEvaluator = new RuleSqlEvaluator(objectMapper);
|
||||
this.ruleSqlEvaluator = new RuleSqlEvaluator(objectMapper, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public String describeEndpoint(String endpointType) {
|
||||
@@ -876,10 +878,11 @@ public class IotService {
|
||||
}
|
||||
|
||||
public void publish(String topic, byte[] payload) {
|
||||
publish(topic, payload, false, 0, null);
|
||||
publish(topic, payload, false, 0, null, null);
|
||||
}
|
||||
|
||||
public void publish(String topic, byte[] payload, boolean retain, int qos, String region) {
|
||||
/** {@code clientId} is the MQTT client that published, or null for a message that did not come over MQTT. */
|
||||
public void publish(String topic, byte[] payload, boolean retain, int qos, String region, String clientId) {
|
||||
byte[] eventPayload = payload == null ? new byte[0] : payload;
|
||||
if (retain) {
|
||||
if (eventPayload.length == 0) {
|
||||
@@ -893,7 +896,7 @@ public class IotService {
|
||||
retainedMessageStore.put(retainedMessageKey(topic), retained);
|
||||
}
|
||||
}
|
||||
handlePublish(topic, eventPayload, true, region);
|
||||
handlePublish(topic, eventPayload, true, region, clientId);
|
||||
}
|
||||
|
||||
public void deleteConnection(String clientId, boolean cleanSession) {
|
||||
@@ -1277,7 +1280,7 @@ public class IotService {
|
||||
topicRuleStore.put(topicRuleKey(region, ruleName), rule);
|
||||
}
|
||||
|
||||
void handlePublish(String topic, byte[] payload, boolean evaluateRules, String region) {
|
||||
void handlePublish(String topic, byte[] payload, boolean evaluateRules, String region, String clientId) {
|
||||
byte[] eventPayload = payload == null ? new byte[0] : payload;
|
||||
publishEventRecorder.record(topic, eventPayload);
|
||||
if (!evaluateRules) {
|
||||
@@ -1285,7 +1288,7 @@ public class IotService {
|
||||
}
|
||||
for (IotTopicRule rule : rulesForPublish(region)) {
|
||||
if (!rule.isRuleDisabled()) {
|
||||
matchAndProject(rule, topic, eventPayload)
|
||||
matchAndProject(rule, topic, clientId, eventPayload)
|
||||
.ifPresent(document -> executeTopicRule(rule, topic, eventPayload, document));
|
||||
}
|
||||
}
|
||||
@@ -1296,7 +1299,7 @@ public class IotService {
|
||||
* 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) {
|
||||
private Optional<byte[]> matchAndProject(IotTopicRule rule, String topic, String clientId, byte[] payload) {
|
||||
RuleSql query = ruleQuery(rule);
|
||||
if (query == null) {
|
||||
return topicMatches(extractTopicPattern(rule.getSql()), topic) ? Optional.of(payload) : Optional.empty();
|
||||
@@ -1304,7 +1307,9 @@ public class IotService {
|
||||
if (!topicMatches(query.topicFilter(), topic)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return ruleSqlEvaluator.evaluate(rule.getRuleName(), query, topic, payload);
|
||||
RuleSqlContext context = new RuleSqlContext(topic, clientId,
|
||||
AwsArnUtils.accountOrDefault(rule.getRuleArn(), config.defaultAccountId()));
|
||||
return ruleSqlEvaluator.evaluate(rule.getRuleName(), query, context, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1486,7 +1491,7 @@ public class IotService {
|
||||
case "republish" -> {
|
||||
String targetTopic = action.path("topic").asText(null);
|
||||
if (targetTopic != null && !targetTopic.isBlank()) {
|
||||
handlePublish(targetTopic, payload, false, region);
|
||||
handlePublish(targetTopic, payload, false, region, null);
|
||||
mqttBrokerService.publish(targetTopic, payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,8 @@ public record RuleSql(List<Projection> projections, String topicFilter, Expr whe
|
||||
public record Aliased(Expr expression, String alias) implements Projection {
|
||||
}
|
||||
|
||||
public sealed interface Expr permits Path, Literal, Call, Comparison, Conjunction, Disjunction, Negation {
|
||||
public sealed interface Expr
|
||||
permits Path, Literal, Call, ArrayLiteral, Comparison, Membership, Conjunction, Disjunction, Negation {
|
||||
}
|
||||
|
||||
/** A dotted field path such as {@code state.reported.temperature}. */
|
||||
@@ -69,16 +70,27 @@ public record RuleSql(List<Projection> projections, String topicFilter, Expr whe
|
||||
public record Literal(JsonNode value) implements Expr {
|
||||
}
|
||||
|
||||
/** A supported function call: {@code topic}, {@code startswith} or {@code endswith}. */
|
||||
/** A supported function call under the name AWS documents, such as {@code topic} or {@code isNull}. */
|
||||
public record Call(String function, List<Expr> arguments) implements Expr {
|
||||
public Call {
|
||||
arguments = List.copyOf(arguments);
|
||||
}
|
||||
}
|
||||
|
||||
/** A JSON array written in the statement, such as {@code [lat, long]}. */
|
||||
public record ArrayLiteral(List<Expr> elements) implements Expr {
|
||||
public ArrayLiteral {
|
||||
elements = List.copyOf(elements);
|
||||
}
|
||||
}
|
||||
|
||||
public record Comparison(Expr left, Operator operator, Expr right) implements Expr {
|
||||
}
|
||||
|
||||
/** {@code element IN array}: true when the array holds a value equal to the element. */
|
||||
public record Membership(Expr element, Expr array) implements Expr {
|
||||
}
|
||||
|
||||
public record Conjunction(Expr left, Expr right) implements Expr {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.iot.rules;
|
||||
|
||||
/**
|
||||
* What a rule can ask about the message beyond its payload: the topic it was published on,
|
||||
* the MQTT client that sent it ({@code null} when it did not arrive over MQTT, which
|
||||
* {@code clientid()} reports as {@code n/a} as AWS does), and the account that owns the rule.
|
||||
*/
|
||||
public record RuleSqlContext(String topic, String clientId, String accountId) {
|
||||
}
|
||||
+118
-36
@@ -4,17 +4,21 @@ 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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.BooleanNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.LongNode;
|
||||
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.ArrayLiteral;
|
||||
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.Membership;
|
||||
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;
|
||||
@@ -25,18 +29,21 @@ import org.jboss.logging.Logger;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
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.
|
||||
* operator, function 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.
|
||||
* a comparison, {@code IN}, {@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.
|
||||
@@ -48,34 +55,40 @@ public final class RuleSqlEvaluator {
|
||||
/** 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+)?");
|
||||
|
||||
/** What {@code clientid()} returns for a message that did not arrive over MQTT, as AWS documents. */
|
||||
private static final String NO_MQTT_CLIENT = "n/a";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ObjectReader payloadReader;
|
||||
private final Clock clock;
|
||||
|
||||
public RuleSqlEvaluator(ObjectMapper objectMapper) {
|
||||
public RuleSqlEvaluator(ObjectMapper objectMapper, Clock clock) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.payloadReader = objectMapper.reader()
|
||||
.with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
|
||||
.with(JsonNodeFactory.withExactBigDecimals(true));
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
public Optional<byte[]> evaluate(String ruleName, RuleSql query, RuleSqlContext context, 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);
|
||||
LOG.debugv("Topic rule {0} skipped a payload that is not a JSON object on topic {1}",
|
||||
ruleName, context.topic());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (query.where() != null && !Boolean.TRUE.equals(truth(value(query.where(), topic, document)))) {
|
||||
if (query.where() != null && !Boolean.TRUE.equals(truth(value(query.where(), context, document)))) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(query.isSelectAllOnly() ? message : project(query, topic, document));
|
||||
return Optional.of(query.isSelectAllOnly() ? message : project(query, context, document));
|
||||
}
|
||||
|
||||
private ObjectNode readObject(byte[] payload) {
|
||||
@@ -96,14 +109,14 @@ public final class RuleSqlEvaluator {
|
||||
* 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) {
|
||||
private byte[] project(RuleSql query, RuleSqlContext context, 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);
|
||||
JsonNode value = value(aliased.expression(), context, document);
|
||||
if (value != null) {
|
||||
projected.set(aliased.alias(), value);
|
||||
}
|
||||
@@ -112,20 +125,24 @@ public final class RuleSqlEvaluator {
|
||||
return projected.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private JsonNode value(Expr expression, String topic, ObjectNode document) {
|
||||
private JsonNode value(Expr expression, RuleSqlContext context, 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 Call call -> call(call, context, document);
|
||||
case ArrayLiteral array -> array(array, context, document);
|
||||
case Comparison comparison -> compare(comparison, context, document);
|
||||
case Membership membership -> contains(
|
||||
value(membership.element(), context, document),
|
||||
value(membership.array(), context, document));
|
||||
case Conjunction conjunction -> booleanNode(and(
|
||||
truth(value(conjunction.left(), topic, document)),
|
||||
truth(value(conjunction.right(), topic, document))));
|
||||
truth(value(conjunction.left(), context, document)),
|
||||
truth(value(conjunction.right(), context, document))));
|
||||
case Disjunction disjunction -> booleanNode(or(
|
||||
truth(value(disjunction.left(), topic, document)),
|
||||
truth(value(disjunction.right(), topic, document))));
|
||||
truth(value(disjunction.left(), context, document)),
|
||||
truth(value(disjunction.right(), context, document))));
|
||||
case Negation negation -> {
|
||||
Boolean operand = truth(value(negation.operand(), topic, document));
|
||||
Boolean operand = truth(value(negation.operand(), context, document));
|
||||
yield operand == null ? null : booleanNode(!operand);
|
||||
}
|
||||
};
|
||||
@@ -145,17 +162,37 @@ public final class RuleSqlEvaluator {
|
||||
return current;
|
||||
}
|
||||
|
||||
private JsonNode call(Call call, String topic, ObjectNode document) {
|
||||
if (call.function().equals("topic")) {
|
||||
if (call.arguments().isEmpty()) {
|
||||
return TextNode.valueOf(topic);
|
||||
private JsonNode call(Call call, RuleSqlContext context, ObjectNode document) {
|
||||
return switch (call.function()) {
|
||||
case "topic" -> topic(call, context);
|
||||
case "clientid" -> TextNode.valueOf(context.clientId() == null ? NO_MQTT_CLIENT : context.clientId());
|
||||
case "timestamp" -> LongNode.valueOf(clock.millis());
|
||||
case "accountid" -> TextNode.valueOf(context.accountId());
|
||||
case "newuuid" -> TextNode.valueOf(UUID.randomUUID().toString());
|
||||
case "isNull" -> {
|
||||
JsonNode argument = value(call.arguments().getFirst(), context, document);
|
||||
yield BooleanNode.valueOf(argument != null && argument.isNull());
|
||||
}
|
||||
return call.arguments().getFirst() instanceof Literal position
|
||||
? topicSegment(topic, position.value().asLong())
|
||||
: null;
|
||||
case "isUndefined" -> BooleanNode.valueOf(value(call.arguments().getFirst(), context, document) == null);
|
||||
default -> stringPredicate(call, context, document);
|
||||
};
|
||||
}
|
||||
|
||||
private JsonNode topic(Call call, RuleSqlContext context) {
|
||||
if (call.arguments().isEmpty()) {
|
||||
return TextNode.valueOf(context.topic());
|
||||
}
|
||||
String subject = text(value(call.arguments().get(0), topic, document));
|
||||
String argument = text(value(call.arguments().get(1), topic, document));
|
||||
if (!(call.arguments().getFirst() instanceof Literal position)) {
|
||||
return null;
|
||||
}
|
||||
String[] segments = context.topic().split("/", -1);
|
||||
long index = position.value().asLong();
|
||||
return index < 1 || index > segments.length ? null : TextNode.valueOf(segments[(int) index - 1]);
|
||||
}
|
||||
|
||||
private JsonNode stringPredicate(Call call, RuleSqlContext context, ObjectNode document) {
|
||||
String subject = text(value(call.arguments().get(0), context, document));
|
||||
String argument = text(value(call.arguments().get(1), context, document));
|
||||
if (subject == null || argument == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -164,9 +201,17 @@ public final class RuleSqlEvaluator {
|
||||
: 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]);
|
||||
/** An array literal is undefined as a whole when any element is, so a position is never silently dropped. */
|
||||
private JsonNode array(ArrayLiteral literal, RuleSqlContext context, ObjectNode document) {
|
||||
ArrayNode array = objectMapper.createArrayNode();
|
||||
for (Expr element : literal.elements()) {
|
||||
JsonNode value = value(element, context, document);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
array.add(value);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -183,9 +228,9 @@ public final class RuleSqlEvaluator {
|
||||
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);
|
||||
private JsonNode compare(Comparison comparison, RuleSqlContext context, ObjectNode document) {
|
||||
JsonNode left = value(comparison.left(), context, document);
|
||||
JsonNode right = value(comparison.right(), context, document);
|
||||
if (left == null || right == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -200,14 +245,51 @@ public final class RuleSqlEvaluator {
|
||||
: booleanNode(matches(operator, leftNumber.compareTo(rightNumber)));
|
||||
}
|
||||
|
||||
/** {@code IN} needs a defined element and an array; it is then a plain search with the equality rules. */
|
||||
private JsonNode contains(JsonNode element, JsonNode array) {
|
||||
if (element == null || array == null || !array.isArray()) {
|
||||
return null;
|
||||
}
|
||||
for (JsonNode candidate : array) {
|
||||
if (equal(element, candidate)) {
|
||||
return BooleanNode.TRUE;
|
||||
}
|
||||
}
|
||||
return BooleanNode.FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}.
|
||||
* AWS compares two numbers by value, arrays element by element in order, objects by key
|
||||
* regardless of order, 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;
|
||||
}
|
||||
if (left.isArray() && right.isArray()) {
|
||||
if (left.size() != right.size()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < left.size(); i++) {
|
||||
if (!equal(left.get(i), right.get(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (left.isObject() && right.isObject()) {
|
||||
if (left.size() != right.size()) {
|
||||
return false;
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> property : left.properties()) {
|
||||
JsonNode other = right.get(property.getKey());
|
||||
if (other == null || !equal(property.getValue(), other)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return left.getNodeType() == right.getNodeType() && left.equals(right);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
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.ArrayLiteral;
|
||||
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.Membership;
|
||||
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;
|
||||
@@ -17,7 +19,11 @@ import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Recursive descent parser for the subset of the AWS IoT rules SQL dialect Floci evaluates:
|
||||
@@ -27,10 +33,12 @@ import java.util.Set;
|
||||
* item := '*' | operand [AS identifier]
|
||||
* expr := term (OR term)*
|
||||
* term := factor (AND factor)*
|
||||
* factor := NOT factor | '(' expr ')' | operand [comparison operand]
|
||||
* factor := NOT factor | '(' expr ')' | operand [comparison operand | IN operand]
|
||||
* comparison := '=' | '<>' | '!=' | '<' | '<=' | '>' | '>='
|
||||
* operand := path | literal | call
|
||||
* operand := path | literal | array | call
|
||||
* array := '[' [operand (',' operand)*] ']'
|
||||
* call := topic '(' [integer] ')' | (startswith | endswith) '(' operand ',' operand ')'
|
||||
* | (clientid | timestamp | accountid | newuuid) '(' ')' | (isNull | isUndefined) '(' operand ')'
|
||||
* path := identifier ('.' identifier)*
|
||||
* literal := 'string' | "string" | number | TRUE | FALSE | NULL
|
||||
* </pre>
|
||||
@@ -41,7 +49,7 @@ import java.util.Set;
|
||||
public final class RuleSqlParser {
|
||||
|
||||
private static final Set<String> KEYWORDS =
|
||||
Set.of("SELECT", "FROM", "WHERE", "AS", "AND", "OR", "NOT", "TRUE", "FALSE", "NULL");
|
||||
Set.of("SELECT", "FROM", "WHERE", "AS", "AND", "OR", "NOT", "IN", "TRUE", "FALSE", "NULL");
|
||||
|
||||
/**
|
||||
* Bounds the work one statement can cost, counting real tokens only: {@link #tokenize} appends
|
||||
@@ -51,8 +59,12 @@ public final class RuleSqlParser {
|
||||
*/
|
||||
private static final int MAX_TOKENS = 1000;
|
||||
|
||||
private static final String TOPIC = "topic";
|
||||
private static final Set<String> STRING_PREDICATES = Set.of("startswith", "endswith");
|
||||
/** The supported functions by lower case name: the spelling AWS documents and the arguments each takes. */
|
||||
private static final Map<String, Signature> FUNCTIONS = Stream.of(
|
||||
new Signature("topic", 0, 1), new Signature("startswith", 2, 2), new Signature("endswith", 2, 2),
|
||||
new Signature("clientid", 0, 0), new Signature("timestamp", 0, 0), new Signature("accountid", 0, 0),
|
||||
new Signature("newuuid", 0, 0), new Signature("isNull", 1, 1), new Signature("isUndefined", 1, 1))
|
||||
.collect(Collectors.toMap(signature -> signature.name().toLowerCase(Locale.ROOT), Function.identity()));
|
||||
|
||||
private final List<Token> tokens;
|
||||
private int index;
|
||||
@@ -146,6 +158,9 @@ public final class RuleSqlParser {
|
||||
return grouped;
|
||||
}
|
||||
Expr left = operand();
|
||||
if (matchKeyword("IN")) {
|
||||
return new Membership(left, operand());
|
||||
}
|
||||
Operator operator = comparisonOperator();
|
||||
return operator == null ? left : new Comparison(left, operator, operand());
|
||||
}
|
||||
@@ -197,10 +212,27 @@ public final class RuleSqlParser {
|
||||
advance();
|
||||
return peekIsSymbol("(") ? call(token) : path(token);
|
||||
}
|
||||
default -> throw fail("Expected a field, literal or function", token);
|
||||
default -> {
|
||||
if (matchSymbol("[")) {
|
||||
return arrayLiteral();
|
||||
}
|
||||
throw fail("Expected a field, literal, array or function", token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Expr arrayLiteral() {
|
||||
List<Expr> elements = new ArrayList<>();
|
||||
if (!matchSymbol("]")) {
|
||||
elements.add(operand());
|
||||
while (matchSymbol(",")) {
|
||||
elements.add(operand());
|
||||
}
|
||||
expectSymbol("]");
|
||||
}
|
||||
return new ArrayLiteral(elements);
|
||||
}
|
||||
|
||||
private Literal numberLiteral(Token token) {
|
||||
try {
|
||||
return token.text().indexOf('.') < 0
|
||||
@@ -226,8 +258,8 @@ public final class RuleSqlParser {
|
||||
}
|
||||
|
||||
private Expr call(Token name) {
|
||||
String function = name.text().toLowerCase(Locale.ROOT);
|
||||
if (!TOPIC.equals(function) && !STRING_PREDICATES.contains(function)) {
|
||||
Signature signature = FUNCTIONS.get(name.text().toLowerCase(Locale.ROOT));
|
||||
if (signature == null) {
|
||||
throw fail("Unsupported function", name);
|
||||
}
|
||||
expectSymbol("(");
|
||||
@@ -239,22 +271,17 @@ public final class RuleSqlParser {
|
||||
}
|
||||
}
|
||||
expectSymbol(")");
|
||||
if (TOPIC.equals(function)) {
|
||||
validateTopicArguments(arguments, name);
|
||||
} else if (arguments.size() != 2) {
|
||||
throw fail("Function " + name.text() + " takes two arguments", name);
|
||||
if (arguments.size() < signature.minArguments() || arguments.size() > signature.maxArguments()) {
|
||||
throw fail("Function " + signature.name() + " does not take " + arguments.size() + " arguments", name);
|
||||
}
|
||||
return new Call(function, arguments);
|
||||
if (signature.name().equals("topic") && !arguments.isEmpty()) {
|
||||
validateTopicSegment(arguments.getFirst(), name);
|
||||
}
|
||||
return new Call(signature.name(), 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) {
|
||||
private void validateTopicSegment(Expr argument, Token name) {
|
||||
if (!(argument instanceof Literal literal) || !literal.value().isIntegralNumber() || literal.value().asLong() < 1) {
|
||||
throw fail("topic() takes no argument or a segment number starting at 1", name);
|
||||
}
|
||||
}
|
||||
@@ -388,7 +415,7 @@ public final class RuleSqlParser {
|
||||
return start + 2;
|
||||
}
|
||||
String one = sql.substring(start, start + 1);
|
||||
if (!",.()*=<>".contains(one)) {
|
||||
if (!",.()[]*=<>".contains(one)) {
|
||||
throw new RuleSqlParseException("Unsupported character", one, start);
|
||||
}
|
||||
tokens.add(new Token(Kind.SYMBOL, one, start));
|
||||
@@ -401,4 +428,7 @@ public final class RuleSqlParser {
|
||||
|
||||
private record Token(Kind kind, String text, int position) {
|
||||
}
|
||||
|
||||
private record Signature(String name, int minArguments, int maxArguments) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user