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

@@ -7,7 +7,10 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
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.iot.model.IotTopicRule;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -21,15 +24,19 @@ import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -38,8 +45,8 @@ import static org.mockito.Mockito.when;
/**
* Rules engine behaviour of {@link IotService} with in-memory stores and mocked action targets:
* one failing action never fails the publish or the other actions, and the error action receives
* the failure document.
* one failing action never fails the publish or the other actions, the error action receives the
* failure document, and the {@code firehose} and {@code cloudwatchLogs} actions deliver the payload.
*/
class IotServiceTest {
@@ -54,6 +61,8 @@ class IotServiceTest {
private final SqsService sqs = mock(SqsService.class);
private final LambdaService lambda = mock(LambdaService.class);
private final DynamoDbService dynamoDb = mock(DynamoDbService.class);
private final FirehoseService firehose = mock(FirehoseService.class);
private final CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
private IotService service;
@BeforeEach
@@ -84,7 +93,9 @@ class IotServiceTest {
mock(S3Service.class),
mock(KinesisService.class),
dynamoDb,
lambda);
lambda,
firehose,
logs);
}
private IotTopicRule createRule(String name, String payloadJson) throws Exception {
@@ -199,6 +210,194 @@ class IotServiceTest {
assertEquals("metrics", failures.get(1).get("failedResource").asText());
}
private static String firehoseRule(String separator, boolean batchMode) {
String separatorMember = separator == null ? "" : ", \"separator\": \"" + separator + "\"";
return """
{
"sql": "SELECT * FROM 'devices/+/metrics'",
"actions": [{"firehose": {"deliveryStreamName": "metrics", "roleArn": "arn:aws:iam::000000000000:role/rule"%s, "batchMode": %s}}]
}
""".formatted(separatorMember, batchMode);
}
private static String text(Record record) {
return new String(record.getData(), StandardCharsets.UTF_8);
}
@Test
void firehoseActionPutsThePayloadWithTheSeparatorAppended() throws Exception {
createRule("metricsRule", firehoseRule("\\n", false));
publish("{\"v\":1}");
ArgumentCaptor<Record> record = ArgumentCaptor.forClass(Record.class);
verify(firehose).putRecord(eq("metrics"), record.capture());
assertEquals("{\"v\":1}\n", text(record.getValue()));
}
@Test
void firehoseActionWithoutASeparatorPutsThePayloadAsIs() throws Exception {
createRule("metricsRule", firehoseRule(null, false));
publish("{\"v\":1}");
ArgumentCaptor<Record> record = ArgumentCaptor.forClass(Record.class);
verify(firehose).putRecord(eq("metrics"), record.capture());
assertEquals("{\"v\":1}", text(record.getValue()));
}
@Test
void firehoseActionInBatchModeDeliversEachElementOfAJsonArrayAsOneRecord() throws Exception {
createRule("metricsRule", firehoseRule("\\n", true));
publish("[{\"v\":1},{\"v\":2}]");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Record>> records = ArgumentCaptor.forClass(List.class);
verify(firehose).putRecordBatch(eq("metrics"), records.capture());
assertEquals(List.of("{\"v\":1}\n", "{\"v\":2}\n"), records.getValue().stream().map(IotServiceTest::text).toList());
verify(firehose, never()).putRecord(anyString(), any());
}
@Test
void firehoseActionInBatchModeDeliversAnythingElseAsOneRecord() throws Exception {
createRule("metricsRule", firehoseRule(null, true));
publish("plain text");
ArgumentCaptor<Record> record = ArgumentCaptor.forClass(Record.class);
verify(firehose).putRecord(eq("metrics"), record.capture());
assertEquals("plain text", text(record.getValue()));
}
@Test
void firehoseActionAcceptsEverySeparatorTheApiAllows() throws Exception {
List<String> separators = List.of("\\n", "\\t", "\\r\\n", ",");
for (int i = 0; i < separators.size(); i++) {
createRule("rule" + i, firehoseRule(separators.get(i), false));
}
}
@Test
void firehoseActionRejectsAnySeparatorTheApiDoesNotAllow() {
for (String separator : List.of("|", ";", "", " ", "\\n\\n")) {
AwsException e = assertThrows(AwsException.class, () -> createRule("metricsRule", firehoseRule(separator, false)));
assertEquals("InvalidRequestException", e.getErrorCode(), separator);
assertEquals(400, e.getHttpStatus());
}
assertThrows(AwsException.class, () -> createRule("metricsRule", """
{"sql": "SELECT * FROM 'devices/+/metrics'", "actions": [],
"errorAction": {"firehose": {"deliveryStreamName": "errors", "roleArn": "arn:aws:iam::000000000000:role/rule", "separator": "|"}}}
"""));
}
@Test
void firehoseActionFailureIsReportedWithTheDeliveryStreamName() throws Exception {
createRule("metricsRule", """
{"sql": "SELECT * FROM 'devices/+/metrics'",
"actions": [{"firehose": {"deliveryStreamName": "metrics", "roleArn": "arn:aws:iam::000000000000:role/rule"}}],
"errorAction": %s}
""".formatted(lambdaErrorAction()));
doThrow(new AwsException("ResourceNotFoundException", "Delivery stream not found: metrics", 400))
.when(firehose).putRecord(eq("metrics"), any());
publish("{\"v\":1}");
JsonNode failure = capturedInvocationPayload(ERROR_FUNCTION_ARN).get("failures").get(0);
assertEquals("FirehoseAction", failure.get("failedAction").asText());
assertEquals("metrics", failure.get("failedResource").asText());
}
private static String cloudwatchLogsRule(boolean batchMode) {
return """
{
"sql": "SELECT * FROM 'devices/+/metrics'",
"actions": [{"cloudwatchLogs": {"logGroupName": "/iot/metrics", "roleArn": "arn:aws:iam::000000000000:role/rule", "batchMode": %s}}]
}
""".formatted(batchMode);
}
private List<Map<String, Object>> capturedLogEvents() {
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Map<String, Object>>> events = ArgumentCaptor.forClass(List.class);
verify(logs).putLogEvents(eq("/iot/metrics"), eq("metricsRule"), events.capture(), eq(REGION));
return events.getValue();
}
@Test
void cloudwatchLogsActionWritesThePayloadToAStreamNamedAfterTheRule() throws Exception {
createRule("metricsRule", cloudwatchLogsRule(false));
publish("{\"v\":1}");
verify(logs).createLogStream("/iot/metrics", "metricsRule", REGION);
List<Map<String, Object>> events = capturedLogEvents();
assertEquals(1, events.size());
assertEquals("{\"v\":1}", events.get(0).get("message"));
assertTrue(events.get(0).get("timestamp") instanceof Long);
}
@Test
void cloudwatchLogsActionReusesAnExistingStream() throws Exception {
createRule("metricsRule", cloudwatchLogsRule(false));
doThrow(new AwsException("ResourceAlreadyExistsException", "The specified log stream already exists", 400))
.when(logs).createLogStream("/iot/metrics", "metricsRule", REGION);
assertDoesNotThrow(() -> publish("{\"v\":1}"));
assertEquals("{\"v\":1}", capturedLogEvents().get(0).get("message"));
}
@Test
void cloudwatchLogsActionInBatchModeTakesTimestampAndMessageFromEachArrayElement() throws Exception {
createRule("metricsRule", cloudwatchLogsRule(true));
publish("""
[
{"timestamp": 1673520691093, "message": "Test message 1"},
{"timestamp": 1673520692879, "message": "Test message 2"},
{"timestamp": 1673520693442, "message": "Test message 3"}
]
""");
List<Map<String, Object>> events = capturedLogEvents();
assertEquals(List.of("Test message 1", "Test message 2", "Test message 3"),
events.stream().map(event -> event.get("message")).toList());
assertEquals(List.of(1673520691093L, 1673520692879L, 1673520693442L),
events.stream().map(event -> event.get("timestamp")).toList());
}
@Test
void cloudwatchLogsActionInBatchModeFallsBackToThePublishTimeAndTheElementText() throws Exception {
createRule("metricsRule", cloudwatchLogsRule(true));
long before = System.currentTimeMillis();
publish("[{\"v\":1}, {\"timestamp\": \"1673520691093\", \"message\": {\"nested\": true}}, \"plain\"]");
List<Map<String, Object>> events = capturedLogEvents();
assertEquals(List.of("{\"v\":1}", "{\"nested\":true}", "\"plain\""),
events.stream().map(event -> event.get("message")).toList());
events.forEach(event -> assertTrue((Long) event.get("timestamp") >= before));
}
@Test
void cloudwatchLogsActionFailsWhenTheLogGroupDoesNotExist() throws Exception {
createRule("metricsRule", """
{"sql": "SELECT * FROM 'devices/+/metrics'",
"actions": [{"cloudwatchLogs": {"logGroupName": "/iot/missing", "roleArn": "arn:aws:iam::000000000000:role/rule"}}],
"errorAction": %s}
""".formatted(lambdaErrorAction()));
doThrow(new AwsException("ResourceNotFoundException", "The specified log group does not exist: /iot/missing", 400))
.when(logs).createLogStream("/iot/missing", "metricsRule", REGION);
assertDoesNotThrow(() -> publish("{\"v\":1}"));
JsonNode failure = capturedInvocationPayload(ERROR_FUNCTION_ARN).get("failures").get(0);
assertEquals("CloudwatchLogsAction", failure.get("failedAction").asText());
assertEquals("/iot/missing", failure.get("failedResource").asText());
verify(logs, never()).putLogEvents(anyString(), anyString(), any(), anyString());
}
@Test
void topicRuleKeepsTheSqlVersionAndTheErrorAction() throws Exception {
createRule("versionedRule", """