mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 14:30:28 -05:00
fix(iot): isolate topic rule actions and run the error action (#3012)
* fix(iot): isolate topic rule actions and run the error action One failing action of a topic rule no longer fails the publish or the actions after it. The failure is logged, and once every action ran the rule's errorAction receives the AWS failure document (ruleName, topic, base64OriginalPayload, failures). CreateTopicRule and ReplaceTopicRule keep awsIotSqlVersion and errorAction, and GetTopicRule returns them. * fix(iot): map nested payload values to DynamoDB maps and lists in the dynamoDBv2 action Objects and arrays in a payload were flattened to empty strings, which also emptied the failures list of the error action's failure document. They now become DynamoDB M and L attribute values, as on AWS. * fix(iot): skip a topic rule action without a type and keep the stack trace of a failed action An action object without a recognisable member is skipped with a warning before anything is dispatched, so the failure document can never see a missing type, and the warnings for a failed action, error action or unparsable stored rule now carry the exception.
This commit is contained in:
1 parent
c3d977a3e3
commit
7ec4c89d0f
6 files changed
+546
-68
No files matched your search
@@ -31,6 +31,7 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -43,6 +44,8 @@ import java.util.Map;
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class IotController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IotController.class);
|
||||
|
||||
private final IotService iotService;
|
||||
private final IotTagHandler iotTagHandler;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -1119,6 +1122,16 @@ public class IotController {
|
||||
} catch (JsonProcessingException e) {
|
||||
response.putArray("actions");
|
||||
}
|
||||
if (rule.getAwsIotSqlVersion() != null) {
|
||||
response.put("awsIotSqlVersion", rule.getAwsIotSqlVersion());
|
||||
}
|
||||
if (rule.getErrorActionJson() != null) {
|
||||
try {
|
||||
response.set("errorAction", objectMapper.readTree(rule.getErrorActionJson()));
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.warnv(e, "Stored error action of topic rule {0} is not JSON", rule.getRuleName());
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
@@ -29,13 +31,16 @@ import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -48,6 +53,8 @@ import java.util.regex.Pattern;
|
||||
@ApplicationScoped
|
||||
public class IotService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IotService.class);
|
||||
|
||||
static final String DEFAULT_ENDPOINT_TYPE = "iot:Data-ATS";
|
||||
|
||||
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
|
||||
@@ -861,6 +868,9 @@ public class IotService {
|
||||
rule.setRuleDisabled(payload.path("ruleDisabled").asBoolean(false));
|
||||
JsonNode actions = payload.path("actions");
|
||||
rule.setActionsJson(actions.isArray() ? actions.toString() : "[]");
|
||||
rule.setAwsIotSqlVersion(payload.path("awsIotSqlVersion").asText(null));
|
||||
JsonNode errorAction = payload.path("errorAction");
|
||||
rule.setErrorActionJson(errorAction.isObject() ? errorAction.toString() : null);
|
||||
rule.setCreatedAt(createdAt == null ? Instant.now() : createdAt);
|
||||
topicRuleStore.put(topicRuleKey(region, ruleName), rule);
|
||||
return rule;
|
||||
@@ -897,7 +907,7 @@ public class IotService {
|
||||
}
|
||||
for (IotTopicRule rule : rulesForPublish(region)) {
|
||||
if (!rule.isRuleDisabled() && topicMatches(extractTopicPattern(rule.getSql()), topic)) {
|
||||
executeTopicRule(rule, eventPayload);
|
||||
executeTopicRule(rule, topic, eventPayload);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -999,73 +1009,152 @@ public class IotService {
|
||||
}
|
||||
}
|
||||
|
||||
private void executeTopicRule(IotTopicRule rule, byte[] payload) {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private void executeTopicRule(IotTopicRule rule, String topic, byte[] payload) {
|
||||
String ruleRegion = AwsArnUtils.regionOrDefault(rule.getRuleArn(), config.defaultRegion());
|
||||
try {
|
||||
JsonNode actions = objectMapper.readTree(rule.getActionsJson());
|
||||
if (!actions.isArray()) {
|
||||
return;
|
||||
List<ObjectNode> failures = new ArrayList<>();
|
||||
for (JsonNode action : storedJson(rule.getRuleName(), rule.getActionsJson())) {
|
||||
String type = actionType(action);
|
||||
if (type == null) {
|
||||
LOG.warnv("Topic rule {0} has an action without a type, skipping it: {1}", rule.getRuleName(), action);
|
||||
continue;
|
||||
}
|
||||
for (JsonNode action : actions) {
|
||||
JsonNode republish = action.path("republish");
|
||||
if (republish.isObject()) {
|
||||
String targetTopic = republish.path("topic").asText(null);
|
||||
if (targetTopic != null && !targetTopic.isBlank()) {
|
||||
handlePublish(targetTopic, payload, false, ruleRegion);
|
||||
mqttBrokerService.publish(targetTopic, payload);
|
||||
}
|
||||
}
|
||||
JsonNode sqs = action.path("sqs");
|
||||
if (sqs.isObject()) {
|
||||
String queueUrl = sqs.path("queueUrl").asText(null);
|
||||
if (queueUrl != null && !queueUrl.isBlank()) {
|
||||
String body = sqs.path("useBase64").asBoolean(false)
|
||||
? Base64.getEncoder().encodeToString(payload)
|
||||
: new String(payload, StandardCharsets.UTF_8);
|
||||
sqsService.sendMessage(queueUrl, body, 0, ruleRegion);
|
||||
}
|
||||
}
|
||||
JsonNode sns = action.path("sns");
|
||||
if (sns.isObject()) {
|
||||
String targetArn = sns.path("targetArn").asText(null);
|
||||
if (targetArn != null && !targetArn.isBlank()) {
|
||||
snsService.publish(targetArn, null, new String(payload, StandardCharsets.UTF_8), null, ruleRegion);
|
||||
}
|
||||
}
|
||||
JsonNode s3 = action.path("s3");
|
||||
if (s3.isObject()) {
|
||||
String bucketName = s3.path("bucketName").asText(null);
|
||||
String key = s3.path("key").asText(null);
|
||||
if (bucketName != null && !bucketName.isBlank() && key != null && !key.isBlank()) {
|
||||
s3Service.putObject(bucketName, key, payload, "application/octet-stream", Map.of());
|
||||
}
|
||||
}
|
||||
JsonNode kinesis = action.path("kinesis");
|
||||
if (kinesis.isObject()) {
|
||||
String streamName = kinesis.path("streamName").asText(null);
|
||||
String partitionKey = kinesis.path("partitionKey").asText("floci-iot");
|
||||
if (streamName != null && !streamName.isBlank()) {
|
||||
kinesisService.putRecord(streamName, payload, partitionKey, ruleRegion);
|
||||
}
|
||||
}
|
||||
JsonNode dynamoDBv2 = action.path("dynamoDBv2");
|
||||
if (dynamoDBv2.isObject()) {
|
||||
String tableName = dynamoDBv2.path("putItem").path("tableName").asText(null);
|
||||
if (tableName != null && !tableName.isBlank()) {
|
||||
dynamoDbService.putItem(tableName, toDynamoDbItem(payload), ruleRegion);
|
||||
}
|
||||
}
|
||||
JsonNode lambda = action.path("lambda");
|
||||
if (lambda.isObject()) {
|
||||
String functionArn = lambda.path("functionArn").asText(null);
|
||||
if (functionArn != null && !functionArn.isBlank()) {
|
||||
lambdaService.invoke(ruleRegion, functionArn, payload, InvocationType.Event);
|
||||
}
|
||||
}
|
||||
JsonNode config = action.get(type);
|
||||
try {
|
||||
runAction(type, config, payload, ruleRegion);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Action {0} of topic rule {1} failed", type, rule.getRuleName());
|
||||
failures.add(failure(type, config, e));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InvalidRequestException", "Invalid topic rule action for " + rule.getRuleName() + ": " + e.getMessage(), 400);
|
||||
}
|
||||
if (failures.isEmpty() || rule.getErrorActionJson() == null) {
|
||||
return;
|
||||
}
|
||||
JsonNode errorAction = storedJson(rule.getRuleName(), rule.getErrorActionJson());
|
||||
String type = actionType(errorAction);
|
||||
if (type == null) {
|
||||
LOG.warnv("Topic rule {0} has an error action without a type, skipping it", rule.getRuleName());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
runAction(type, errorAction.get(type), failureDocument(rule, topic, payload, failures), ruleRegion);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Error action {0} of topic rule {1} failed", type, rule.getRuleName());
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode storedJson(String ruleName, String json) {
|
||||
try {
|
||||
return objectMapper.readTree(json);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.warnv(e, "Stored actions of topic rule {0} are not JSON and were skipped", ruleName);
|
||||
return objectMapper.createArrayNode();
|
||||
}
|
||||
}
|
||||
|
||||
/** The one member an action object carries, naming its kind, or null when it carries none. */
|
||||
private static String actionType(JsonNode action) {
|
||||
if (action == null || !action.isObject()) {
|
||||
return null;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = action.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
if (field.getValue().isObject()) {
|
||||
return field.getKey();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void runAction(String type, JsonNode action, byte[] payload, String region) {
|
||||
switch (type) {
|
||||
case "republish" -> {
|
||||
String targetTopic = action.path("topic").asText(null);
|
||||
if (targetTopic != null && !targetTopic.isBlank()) {
|
||||
handlePublish(targetTopic, payload, false, region);
|
||||
mqttBrokerService.publish(targetTopic, payload);
|
||||
}
|
||||
}
|
||||
case "sqs" -> {
|
||||
String queueUrl = action.path("queueUrl").asText(null);
|
||||
if (queueUrl != null && !queueUrl.isBlank()) {
|
||||
String body = action.path("useBase64").asBoolean(false)
|
||||
? Base64.getEncoder().encodeToString(payload)
|
||||
: new String(payload, StandardCharsets.UTF_8);
|
||||
sqsService.sendMessage(queueUrl, body, 0, region);
|
||||
}
|
||||
}
|
||||
case "sns" -> {
|
||||
String targetArn = action.path("targetArn").asText(null);
|
||||
if (targetArn != null && !targetArn.isBlank()) {
|
||||
snsService.publish(targetArn, null, new String(payload, StandardCharsets.UTF_8), null, region);
|
||||
}
|
||||
}
|
||||
case "s3" -> {
|
||||
String bucketName = action.path("bucketName").asText(null);
|
||||
String key = action.path("key").asText(null);
|
||||
if (bucketName != null && !bucketName.isBlank() && key != null && !key.isBlank()) {
|
||||
s3Service.putObject(bucketName, key, payload, "application/octet-stream", Map.of());
|
||||
}
|
||||
}
|
||||
case "kinesis" -> {
|
||||
String streamName = action.path("streamName").asText(null);
|
||||
String partitionKey = action.path("partitionKey").asText("floci-iot");
|
||||
if (streamName != null && !streamName.isBlank()) {
|
||||
kinesisService.putRecord(streamName, payload, partitionKey, region);
|
||||
}
|
||||
}
|
||||
case "dynamoDBv2" -> {
|
||||
String tableName = action.path("putItem").path("tableName").asText(null);
|
||||
if (tableName != null && !tableName.isBlank()) {
|
||||
dynamoDbService.putItem(tableName, toDynamoDbItem(payload), region);
|
||||
}
|
||||
}
|
||||
case "lambda" -> {
|
||||
String functionArn = action.path("functionArn").asText(null);
|
||||
if (functionArn != null && !functionArn.isBlank()) {
|
||||
lambdaService.invoke(region, functionArn, payload, InvocationType.Event);
|
||||
}
|
||||
}
|
||||
default -> LOG.debugv("Topic rule action {0} is not supported and was skipped", type);
|
||||
}
|
||||
}
|
||||
|
||||
/** One entry of the failure document: the action kind and target as AWS names them. */
|
||||
private ObjectNode failure(String type, JsonNode action, RuntimeException e) {
|
||||
ObjectNode failure = objectMapper.createObjectNode();
|
||||
failure.put("failedAction", Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Action");
|
||||
failure.put("failedResource", targetOf(type, action));
|
||||
failure.put("errorMessage", e.getMessage() == null ? e.toString() : e.getMessage());
|
||||
return failure;
|
||||
}
|
||||
|
||||
private static String targetOf(String type, JsonNode action) {
|
||||
return switch (type) {
|
||||
case "republish" -> action.path("topic").asText("");
|
||||
case "sqs" -> action.path("queueUrl").asText("");
|
||||
case "sns" -> action.path("targetArn").asText("");
|
||||
case "s3" -> action.path("bucketName").asText("");
|
||||
case "kinesis" -> action.path("streamName").asText("");
|
||||
case "dynamoDBv2" -> action.path("putItem").path("tableName").asText("");
|
||||
case "lambda" -> action.path("functionArn").asText("");
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
private byte[] failureDocument(IotTopicRule rule, String topic, byte[] payload, List<ObjectNode> failures) {
|
||||
ObjectNode document = objectMapper.createObjectNode();
|
||||
document.put("ruleName", rule.getRuleName());
|
||||
document.put("topic", topic);
|
||||
document.put("base64OriginalPayload", Base64.getEncoder().encodeToString(payload));
|
||||
ArrayNode list = document.putArray("failures");
|
||||
failures.forEach(list::add);
|
||||
return document.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private ObjectNode toDynamoDbItem(byte[] payload) {
|
||||
@@ -1084,6 +1173,7 @@ public class IotService {
|
||||
}
|
||||
}
|
||||
|
||||
/** A JSON value as a DynamoDB attribute value; objects and arrays become maps and lists, as on AWS. */
|
||||
private ObjectNode toDynamoDbAttribute(JsonNode value) {
|
||||
ObjectNode attribute = objectMapper.createObjectNode();
|
||||
if (value == null || value.isNull()) {
|
||||
@@ -1092,6 +1182,12 @@ public class IotService {
|
||||
attribute.put("BOOL", value.asBoolean());
|
||||
} else if (value.isNumber()) {
|
||||
attribute.put("N", value.asText());
|
||||
} else if (value.isObject()) {
|
||||
ObjectNode map = attribute.putObject("M");
|
||||
value.fields().forEachRemaining(entry -> map.set(entry.getKey(), toDynamoDbAttribute(entry.getValue())));
|
||||
} else if (value.isArray()) {
|
||||
ArrayNode list = attribute.putArray("L");
|
||||
value.forEach(element -> list.add(toDynamoDbAttribute(element)));
|
||||
} else {
|
||||
attribute.put("S", value.asText());
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ public class IotTopicRule {
|
||||
private String description;
|
||||
private boolean ruleDisabled;
|
||||
private String actionsJson = "[]";
|
||||
private String awsIotSqlVersion;
|
||||
private String errorActionJson;
|
||||
private Instant createdAt;
|
||||
private Map<String, String> tags = new TreeMap<>();
|
||||
|
||||
@@ -65,6 +67,22 @@ public class IotTopicRule {
|
||||
this.actionsJson = actionsJson;
|
||||
}
|
||||
|
||||
public String getAwsIotSqlVersion() {
|
||||
return awsIotSqlVersion;
|
||||
}
|
||||
|
||||
public void setAwsIotSqlVersion(String awsIotSqlVersion) {
|
||||
this.awsIotSqlVersion = awsIotSqlVersion;
|
||||
}
|
||||
|
||||
public String getErrorActionJson() {
|
||||
return errorActionJson;
|
||||
}
|
||||
|
||||
public void setErrorActionJson(String errorActionJson) {
|
||||
this.errorActionJson = errorActionJson;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user