feat(iot): firehose and cloudwatchLogs rule actions (#3013)

* feat(iot): firehose and cloudwatchLogs rule actions

A topic rule can now deliver to a Kinesis Data Firehose delivery stream
(separator appended to each record, batchMode splitting a JSON array
into one record per element) and to CloudWatch Logs (one log event per
publish, or per array element with batchMode, in a stream named after
the rule that is created in the log group on first use).

* fix(iot): take timestamp and message from each batched cloudwatchLogs element and check the firehose separator

With batchMode the cloudwatchLogs action wrote every array element as one
log event whose message was the element's JSON text and whose timestamp was
the publish time. AWS requires a batched payload to be an array of
{"timestamp": <epoch ms>, "message": "<text>"} objects and takes both from
each element. The action now does the same; an element without a numeric
timestamp is stamped with the publish time and one without a message is
logged as its JSON text, so a batch that ignores the format still lands.

CreateTopicRule and ReplaceTopicRule reject a firehose separator that is
not a newline, tab, Windows newline or comma, the FirehoseSeparator pattern
of the IoT API model, with InvalidRequestException.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-05 14:02:24 -05:00
1 parent 173ff45b12
commit ebdf092cce
3 files changed
+339 -11

No files matched your search

@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.github.hectorvent.floci.services.iot.model.IotJob;
@@ -23,6 +24,8 @@ import io.github.hectorvent.floci.services.iot.model.IotThingType;
import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
import io.github.hectorvent.floci.services.iot.model.Thing;
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;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -33,10 +36,12 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashSet;
@@ -58,6 +63,8 @@ public class IotService {
static final String DEFAULT_ENDPOINT_TYPE = "iot:Data-ATS";
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
/** The {@code FirehoseSeparator} shape of the IoT API model. */
private static final Pattern FIREHOSE_SEPARATOR = Pattern.compile("([\\n\\t])|(\\r\\n)|(,)");
private final StorageBackend<String, Thing> thingStore;
private final StorageBackend<String, IotCertificate> certificateStore;
@@ -83,6 +90,8 @@ public class IotService {
private final KinesisService kinesisService;
private final DynamoDbService dynamoDbService;
private final LambdaService lambdaService;
private final FirehoseService firehoseService;
private final CloudWatchLogsService cloudWatchLogsService;
@Inject
public IotService(StorageFactory storageFactory,
@@ -96,7 +105,9 @@ public class IotService {
S3Service s3Service,
KinesisService kinesisService,
DynamoDbService dynamoDbService,
LambdaService lambdaService) {
LambdaService lambdaService,
FirehoseService firehoseService,
CloudWatchLogsService cloudWatchLogsService) {
this(storageFactory.create("iot", "iot-things.json", new TypeReference<Map<String, Thing>>() {}),
storageFactory.create("iot", "iot-certificates.json", new TypeReference<Map<String, IotCertificate>>() {}),
storageFactory.create("iot", "iot-policies.json", new TypeReference<Map<String, IotPolicy>>() {}),
@@ -111,7 +122,7 @@ public class IotService {
storageFactory.create("iot", "iot-thing-groups.json", new TypeReference<Map<String, IotThingGroup>>() {}),
storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference<Map<String, Set<String>>>() {}),
config, regionResolver, objectMapper, publishEventRecorder, mqttBrokerService, sqsService, snsService,
s3Service, kinesisService, dynamoDbService, lambdaService);
s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService);
}
IotService(StorageBackend<String, Thing> thingStore,
@@ -137,7 +148,9 @@ public class IotService {
S3Service s3Service,
KinesisService kinesisService,
DynamoDbService dynamoDbService,
LambdaService lambdaService) {
LambdaService lambdaService,
FirehoseService firehoseService,
CloudWatchLogsService cloudWatchLogsService) {
this.thingStore = thingStore;
this.certificateStore = certificateStore;
this.policyStore = policyStore;
@@ -162,6 +175,8 @@ public class IotService {
this.kinesisService = kinesisService;
this.dynamoDbService = dynamoDbService;
this.lambdaService = lambdaService;
this.firehoseService = firehoseService;
this.cloudWatchLogsService = cloudWatchLogsService;
}
public String describeEndpoint(String endpointType) {
@@ -867,15 +882,29 @@ public class IotService {
rule.setDescription(payload.path("description").asText(null));
rule.setRuleDisabled(payload.path("ruleDisabled").asBoolean(false));
JsonNode actions = payload.path("actions");
actions.forEach(IotService::validateAction);
rule.setActionsJson(actions.isArray() ? actions.toString() : "[]");
rule.setAwsIotSqlVersion(payload.path("awsIotSqlVersion").asText(null));
JsonNode errorAction = payload.path("errorAction");
validateAction(errorAction);
rule.setErrorActionJson(errorAction.isObject() ? errorAction.toString() : null);
rule.setCreatedAt(createdAt == null ? Instant.now() : createdAt);
topicRuleStore.put(topicRuleKey(region, ruleName), rule);
return rule;
}
/** The API model restricts the firehose {@code separator} to a newline, tab, Windows newline or comma. */
private static void validateAction(JsonNode action) {
JsonNode separator = action.path("firehose").path("separator");
if (separator.isMissingNode() || separator.isNull()) {
return;
}
if (!FIREHOSE_SEPARATOR.matcher(separator.asText()).matches()) {
throw new AwsException("InvalidRequestException",
"Invalid firehose separator. Valid values are: '\\n' (newline), '\\t' (tab), '\\r\\n' (Windows newline), ',' (comma)", 400);
}
}
public IotTopicRule getTopicRule(String ruleName, String region) {
return topicRuleStore.get(topicRuleKey(region, ruleName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Topic rule not found: " + ruleName, 404));
@@ -1025,7 +1054,7 @@ public class IotService {
}
JsonNode config = action.get(type);
try {
runAction(type, config, payload, ruleRegion);
runAction(rule, 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));
@@ -1041,7 +1070,7 @@ public class IotService {
return;
}
try {
runAction(type, errorAction.get(type), failureDocument(rule, topic, payload, failures), ruleRegion);
runAction(rule, 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());
}
@@ -1071,7 +1100,7 @@ public class IotService {
return null;
}
private void runAction(String type, JsonNode action, byte[] payload, String region) {
private void runAction(IotTopicRule rule, String type, JsonNode action, byte[] payload, String region) {
switch (type) {
case "republish" -> {
String targetTopic = action.path("topic").asText(null);
@@ -1121,6 +1150,18 @@ public class IotService {
lambdaService.invoke(region, functionArn, payload, InvocationType.Event);
}
}
case "firehose" -> {
String deliveryStreamName = action.path("deliveryStreamName").asText(null);
if (deliveryStreamName != null && !deliveryStreamName.isBlank()) {
deliverToFirehose(deliveryStreamName, action, payload);
}
}
case "cloudwatchLogs" -> {
String logGroupName = action.path("logGroupName").asText(null);
if (logGroupName != null && !logGroupName.isBlank()) {
putLogEvents(logGroupName, rule.getRuleName(), action, payload, region);
}
}
default -> LOG.debugv("Topic rule action {0} is not supported and was skipped", type);
}
}
@@ -1143,6 +1184,8 @@ public class IotService {
case "kinesis" -> action.path("streamName").asText("");
case "dynamoDBv2" -> action.path("putItem").path("tableName").asText("");
case "lambda" -> action.path("functionArn").asText("");
case "firehose" -> action.path("deliveryStreamName").asText("");
case "cloudwatchLogs" -> action.path("logGroupName").asText("");
default -> "";
};
}
@@ -1157,6 +1200,90 @@ public class IotService {
return document.toString().getBytes(StandardCharsets.UTF_8);
}
/**
* The firehose action appends {@code separator} to every record. With {@code batchMode} a JSON
* array payload becomes one record per element, as the rule's SQL result would on AWS; any other
* payload is one record either way.
*/
private void deliverToFirehose(String deliveryStreamName, JsonNode action, byte[] payload) {
byte[] separator = action.path("separator").asText("").getBytes(StandardCharsets.UTF_8);
JsonNode batch = action.path("batchMode").asBoolean(false) ? jsonArrayOrNull(payload) : null;
if (batch == null) {
firehoseService.putRecord(deliveryStreamName, new Record(withSeparator(payload, separator)));
return;
}
List<Record> records = new ArrayList<>();
for (JsonNode element : batch) {
records.add(new Record(withSeparator(element.toString().getBytes(StandardCharsets.UTF_8), separator)));
}
if (!records.isEmpty()) {
firehoseService.putRecordBatch(deliveryStreamName, records);
}
}
/**
* The cloudwatchLogs action writes the payload as one log event to a stream named after the
* rule, creating the stream in the given group on first use. The group itself must exist, as
* on AWS. With {@code batchMode} a JSON array payload becomes one event per element, each
* element carrying its own {@code timestamp} and {@code message} as the AWS message format
* for batched device logs requires.
*/
private void putLogEvents(String logGroupName, String logStreamName, JsonNode action, byte[] payload, String region) {
JsonNode batch = action.path("batchMode").asBoolean(false) ? jsonArrayOrNull(payload) : null;
long now = Instant.now().toEpochMilli();
List<Map<String, Object>> events = new ArrayList<>();
if (batch == null) {
events.add(Map.of("timestamp", now, "message", new String(payload, StandardCharsets.UTF_8)));
} else {
batch.forEach(element -> events.add(batchedLogEvent(element, now)));
}
if (events.isEmpty()) {
return;
}
try {
cloudWatchLogsService.createLogStream(logGroupName, logStreamName, region);
} catch (AwsException e) {
if (!"ResourceAlreadyExistsException".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Log stream {0}/{1} already exists", logGroupName, logStreamName);
}
cloudWatchLogsService.putLogEvents(logGroupName, logStreamName, events, region);
}
/**
* One batched element is {@code {"timestamp": <epoch milliseconds>, "message": "<text>"}}. An
* element without a numeric timestamp is stamped with the publish time and one without a
* message is logged as its own JSON text, so a batch that ignores the format still reaches
* the log group instead of failing the action.
*/
private static Map<String, Object> batchedLogEvent(JsonNode element, long now) {
JsonNode timestamp = element.path("timestamp");
JsonNode message = element.path("message");
String text = message.isMissingNode() ? element.toString()
: message.isValueNode() ? message.asText() : message.toString();
return Map.of("timestamp", timestamp.isNumber() ? timestamp.asLong() : now, "message", text);
}
private JsonNode jsonArrayOrNull(byte[] payload) {
try {
JsonNode node = objectMapper.readTree(payload);
return node != null && node.isArray() ? node : null;
} catch (IOException e) {
LOG.debugv("Payload is not JSON and is delivered as one record: {0}", e.getMessage());
return null;
}
}
private static byte[] withSeparator(byte[] data, byte[] separator) {
if (separator.length == 0) {
return data;
}
byte[] record = Arrays.copyOf(data, data.length + separator.length);
System.arraycopy(separator, 0, record, data.length, separator.length);
return record;
}
private ObjectNode toDynamoDbItem(byte[] payload) {
try {
JsonNode document = objectMapper.readTree(payload);