mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(logs): deliver log events through subscription filters (#5021)
This commit is contained in:
1 parent
8ea033d9fd
commit
b2e3870c06
5 files changed
+904
-8
No files matched your search
@@ -33,7 +33,7 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics.
|
||||
| `TagResource` | Tag a log group by ARN |
|
||||
| `UntagResource` | Remove tags from a log group by ARN |
|
||||
| `ListTagsForResource` | List tags for a log group ARN |
|
||||
| `PutSubscriptionFilter` | Create or update a subscription filter (stored only, see note below) |
|
||||
| `PutSubscriptionFilter` | Create or update a subscription filter (see [Subscription filters](#subscription-filters)) |
|
||||
| `DescribeSubscriptionFilters` | List subscription filters on a log group |
|
||||
| `DeleteSubscriptionFilter` | Delete a subscription filter |
|
||||
| `PutMetricFilter` | Create or replace a metric filter on a log group (see [Metric filters](#metric-filters)) |
|
||||
@@ -55,16 +55,31 @@ Log group deletion protection defaults to disabled and is persisted with the log
|
||||
enabled, `DeleteLogGroup` returns `ValidationException` until protection is explicitly disabled
|
||||
with `PutLogGroupDeletionProtection`.
|
||||
|
||||
Three actions are currently simplified:
|
||||
Two actions are currently simplified:
|
||||
|
||||
- **`PutSubscriptionFilter`** stores the filter so that `DescribeSubscriptionFilters`
|
||||
returns it, but log events are **not** forwarded to the destination ARN. Lambda,
|
||||
Kinesis, and Firehose subscription destinations are not wired up.
|
||||
- **`GetDataProtectionPolicy`** does not model data-protection policies. It returns
|
||||
HTTP 200 with the resolved `logGroupIdentifier` and no `policyDocument` — including for
|
||||
HTTP 200 with the resolved `logGroupIdentifier` and no `policyDocument`, including for
|
||||
a log group that does not exist, where real AWS returns `ResourceNotFoundException`.
|
||||
- **`FilterLogEvents`** matches `filterPattern` as a plain substring of the message. The full
|
||||
filter pattern syntax described below is applied by metric filters.
|
||||
filter pattern syntax described below is applied by metric filters and subscription filters.
|
||||
|
||||
### Subscription filters {#subscription-filters}
|
||||
|
||||
Subscription filters deliver newly ingested log events to a downstream destination. Floci delivers
|
||||
matching events to Lambda functions, Kinesis data streams, and Firehose delivery streams. Delivery
|
||||
happens synchronously on the calling thread when `PutLogEvents` persists events. A destination error,
|
||||
missing destination stream/function, or unresolvable destination ARN is logged and does not fail the
|
||||
log ingestion request.
|
||||
|
||||
The delivered payload is a gzip-compressed JSON object containing `messageType` (`DATA_MESSAGE`),
|
||||
`owner` (the account ID), `logGroup`, `logStream`, `subscriptionFilters` (the matched filter names),
|
||||
and `logEvents` (an array of `{id, timestamp, message}`). Lambda receives the payload base64-encoded
|
||||
under `awslogs.data`. Kinesis and Firehose receive the gzip-compressed JSON bytes directly as record data.
|
||||
|
||||
For Kinesis destinations, `distribution` controls the partition key: `ByLogStream` uses the log stream
|
||||
name, while `Random` assigns a randomized UUID partition key. Cross-account Logs destinations
|
||||
(`PutDestination`), IAM role permission checks, and the `CONTROL_MESSAGE` ping on filter creation
|
||||
are deferred.
|
||||
|
||||
### Metric filters {#metric-filters}
|
||||
|
||||
|
||||
+5
-1
@@ -1120,6 +1120,10 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
return metricFilterStore;
|
||||
}
|
||||
|
||||
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore() {
|
||||
return subscriptionFilterStore;
|
||||
}
|
||||
|
||||
static FilterPattern requireFilterPattern(String filterPattern) {
|
||||
if (filterPattern == null) {
|
||||
throw invalid("filterPattern is required.");
|
||||
@@ -1310,7 +1314,7 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
: eventKey.substring(groupPrefix.length(), timestampSeparator);
|
||||
}
|
||||
|
||||
private static String subscriptionFilterKeyPrefix(String region, String logGroupName) {
|
||||
static String subscriptionFilterKeyPrefix(String region, String logGroupName) {
|
||||
return region + "::" + logGroupName + "::filter::";
|
||||
}
|
||||
|
||||
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.filter.FilterPattern;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.SubscriptionFilter;
|
||||
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.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
/**
|
||||
* Delivers matching log events to CloudWatch Logs subscription filter destinations
|
||||
* (Lambda, Kinesis Data Streams, and Firehose Delivery Streams) upon log event ingestion.
|
||||
*
|
||||
* <p>Delivery occurs synchronously on the calling ingestion thread without failing the log write.
|
||||
* Subscription filter payloads are gzip-compressed JSON DATA_MESSAGE records matching the AWS wire format.
|
||||
*
|
||||
* <p>Note: FirehoseCompression is package-private to the firehose package and models S3 delivery formats,
|
||||
* while FlowLogService gzip helper is private in ec2. This compact gzip helper avoids coupling across service
|
||||
* internals.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsSubscriptionDeliveryService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchLogsSubscriptionDeliveryService.class);
|
||||
private static final String DATA_MESSAGE = "DATA_MESSAGE";
|
||||
private static final String LAMBDA_LOG_PREFIX = "/aws/lambda/";
|
||||
/** Max compressed record size for Kinesis and Firehose delivery (1 MB). */
|
||||
private static final int MAX_RECORD_PAYLOAD_BYTES = 1_000_000;
|
||||
|
||||
private final StorageBackend<String, SubscriptionFilter> store;
|
||||
private final LambdaService lambdaService;
|
||||
private final KinesisService kinesisService;
|
||||
private final FirehoseService firehoseService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsSubscriptionDeliveryService(CloudWatchLogsService logsService,
|
||||
LambdaService lambdaService,
|
||||
KinesisService kinesisService,
|
||||
FirehoseService firehoseService,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.store = logsService.subscriptionFilterStore();
|
||||
this.lambdaService = lambdaService;
|
||||
this.kinesisService = kinesisService;
|
||||
this.firehoseService = firehoseService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record SubscriptionPayload(
|
||||
String messageType,
|
||||
String owner,
|
||||
String logGroup,
|
||||
String logStream,
|
||||
List<String> subscriptionFilters,
|
||||
List<SubscriptionLogEvent> logEvents) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record SubscriptionLogEvent(
|
||||
String id,
|
||||
long timestamp,
|
||||
String message) {
|
||||
}
|
||||
|
||||
void onLogEventsIngested(@Observes LogEventsIngested event) {
|
||||
if (event == null || event.events() == null || event.events().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String account = event.accountId() == null || event.accountId().isBlank()
|
||||
? regionResolver.getAccountId() : event.accountId();
|
||||
try {
|
||||
List<SubscriptionFilter> filters = filtersOf(event.logGroupName(), event.region(), account);
|
||||
for (SubscriptionFilter filter : filters) {
|
||||
try {
|
||||
deliver(filter, event, account);
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Cannot deliver subscription filter events: account={0}, region={1}, group={2}, filter={3}",
|
||||
account, event.region(), event.logGroupName(), filter.getFilterName());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Cannot load subscription filters; delivery skipped: account={0}, region={1}, group={2}",
|
||||
account, event.region(), event.logGroupName());
|
||||
}
|
||||
}
|
||||
|
||||
private List<SubscriptionFilter> filtersOf(String logGroupName, String region, String accountId) {
|
||||
String prefix = CloudWatchLogsService.subscriptionFilterKeyPrefix(region, logGroupName);
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<?> rawAware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<SubscriptionFilter> aware =
|
||||
(AccountAwareStorageBackend<SubscriptionFilter>) rawAware;
|
||||
return aware.scanForAccount(accountId, key -> key.startsWith(prefix));
|
||||
}
|
||||
return store.scan(key -> key.startsWith(prefix));
|
||||
}
|
||||
|
||||
private void deliver(SubscriptionFilter filter, LogEventsIngested event, String account) throws IOException {
|
||||
FilterPattern pattern = FilterPattern.parse(filter.getFilterPattern());
|
||||
List<SubscriptionLogEvent> matching = new ArrayList<>();
|
||||
for (LogEvent logEvent : event.events()) {
|
||||
if (pattern.match(logEvent.getMessage()).matched()) {
|
||||
matching.add(new SubscriptionLogEvent(
|
||||
logEvent.getEventId(),
|
||||
logEvent.getTimestamp(),
|
||||
logEvent.getMessage()));
|
||||
}
|
||||
}
|
||||
if (matching.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String destinationArn = filter.getDestinationArn();
|
||||
if (destinationArn == null || !AwsArnUtils.isArn(destinationArn)) {
|
||||
LOG.warnv("Cannot deliver to unresolvable destinationArn: {0}", destinationArn);
|
||||
return;
|
||||
}
|
||||
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(destinationArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.warnv("Cannot parse destinationArn: {0}", destinationArn);
|
||||
return;
|
||||
}
|
||||
|
||||
// Direct cross-account delivery without a Logs Destination (PutDestination) is unauthorized in AWS
|
||||
if (!arn.accountId().isBlank() && !arn.accountId().equals(account)) {
|
||||
LOG.warnv("Cross-account subscription delivery is unauthorized without a Logs destination: destinationAccount={0}, groupAccount={1}",
|
||||
arn.accountId(), account);
|
||||
return;
|
||||
}
|
||||
|
||||
String targetRegion = (arn.region() != null && !arn.region().isBlank())
|
||||
? arn.region() : event.region();
|
||||
String service = arn.service();
|
||||
|
||||
if ("lambda".equals(service)) {
|
||||
if (isSelfSubscribedLambda(event.logGroupName(), destinationArn)) {
|
||||
LOG.warnv("Skipping delivery to Lambda destination {0} to prevent recursive loop on its own log group {1}",
|
||||
destinationArn, event.logGroupName());
|
||||
return;
|
||||
}
|
||||
deliverChunks(filter, event, account, matching, gzipped -> deliverToLambda(destinationArn, gzipped));
|
||||
} else if ("kinesis".equals(service)) {
|
||||
deliverChunks(filter, event, account, matching, gzipped ->
|
||||
deliverToKinesis(arn, filter, gzipped, event.logStreamName(), account, targetRegion));
|
||||
} else if ("firehose".equals(service)) {
|
||||
deliverChunks(filter, event, account, matching, gzipped ->
|
||||
deliverToFirehose(arn, gzipped, account, targetRegion));
|
||||
} else {
|
||||
LOG.warnv("Unsupported subscription filter destination service: {0}", service);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSelfSubscribedLambda(String logGroupName, String functionArn) {
|
||||
if (logGroupName == null || functionArn == null || !logGroupName.startsWith(LAMBDA_LOG_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
String logFunctionName = logGroupName.substring(LAMBDA_LOG_PREFIX.length());
|
||||
try {
|
||||
String targetFunctionName = LambdaArnUtils.resolve(functionArn).name();
|
||||
return logFunctionName.equals(targetFunctionName);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface PayloadConsumer {
|
||||
void accept(byte[] gzippedBytes) throws Exception;
|
||||
}
|
||||
|
||||
private void deliverChunks(SubscriptionFilter filter, LogEventsIngested event,
|
||||
String account, List<SubscriptionLogEvent> matching,
|
||||
PayloadConsumer consumer) {
|
||||
int start = 0;
|
||||
int currentBytes = 0;
|
||||
for (int i = 0; i < matching.size(); i++) {
|
||||
SubscriptionLogEvent logEvent = matching.get(i);
|
||||
int eventBytes = (logEvent.message() != null ? logEvent.message().length() : 0) + 64;
|
||||
if (i > start && (i - start >= 500 || currentBytes + eventBytes > 500_000)) {
|
||||
deliverSlice(filter, event, account, matching.subList(start, i), consumer);
|
||||
start = i;
|
||||
currentBytes = 0;
|
||||
}
|
||||
currentBytes += eventBytes;
|
||||
}
|
||||
if (start < matching.size()) {
|
||||
deliverSlice(filter, event, account, matching.subList(start, matching.size()), consumer);
|
||||
}
|
||||
}
|
||||
|
||||
private void deliverSlice(SubscriptionFilter filter, LogEventsIngested event,
|
||||
String account, List<SubscriptionLogEvent> slice,
|
||||
PayloadConsumer consumer) {
|
||||
if (slice.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
byte[] gzippedBytes;
|
||||
try {
|
||||
SubscriptionPayload payload = new SubscriptionPayload(
|
||||
DATA_MESSAGE,
|
||||
account,
|
||||
event.logGroupName(),
|
||||
event.logStreamName(),
|
||||
List.of(filter.getFilterName()),
|
||||
slice);
|
||||
byte[] jsonBytes = objectMapper.writeValueAsBytes(payload);
|
||||
gzippedBytes = gzip(jsonBytes);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Cannot serialize subscription payload: filter={0}", filter.getFilterName());
|
||||
return;
|
||||
}
|
||||
|
||||
if (gzippedBytes.length <= MAX_RECORD_PAYLOAD_BYTES || slice.size() <= 1) {
|
||||
try {
|
||||
consumer.accept(gzippedBytes);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Cannot deliver subscription filter chunk: filter={0}, destination={1}",
|
||||
filter.getFilterName(), filter.getDestinationArn());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
int mid = slice.size() / 2;
|
||||
deliverSlice(filter, event, account, slice.subList(0, mid), consumer);
|
||||
deliverSlice(filter, event, account, slice.subList(mid, slice.size()), consumer);
|
||||
}
|
||||
|
||||
private void deliverToLambda(String functionArn, byte[] gzippedBytes) throws JsonProcessingException {
|
||||
if (lambdaService == null) {
|
||||
LOG.warnv("Cannot deliver to Lambda; service not available: {0}", functionArn);
|
||||
return;
|
||||
}
|
||||
String base64Data = Base64.getEncoder().encodeToString(gzippedBytes);
|
||||
Map<String, Map<String, String>> lambdaEvent = Map.of(
|
||||
"awslogs", Map.of("data", base64Data));
|
||||
byte[] payloadBytes = objectMapper.writeValueAsBytes(lambdaEvent);
|
||||
lambdaService.invokeArn(functionArn, payloadBytes, InvocationType.Event);
|
||||
LOG.debugv("Subscription filter delivered to Lambda: {0}", functionArn);
|
||||
}
|
||||
|
||||
private void deliverToKinesis(AwsArnUtils.Arn arn, SubscriptionFilter filter, byte[] gzippedBytes,
|
||||
String logStreamName, String targetAccount, String targetRegion) {
|
||||
if (kinesisService == null) {
|
||||
LOG.warnv("Cannot deliver to Kinesis; service not available: {0}", arn);
|
||||
return;
|
||||
}
|
||||
String streamName = arn.resource().startsWith("stream/")
|
||||
? arn.resource().substring("stream/".length()) : arn.resource();
|
||||
String partitionKey = "Random".equalsIgnoreCase(filter.getDistribution())
|
||||
? UUID.randomUUID().toString()
|
||||
: (logStreamName != null ? logStreamName : "");
|
||||
kinesisService.putRecordForAccount(targetAccount, streamName, gzippedBytes, partitionKey, targetRegion);
|
||||
LOG.debugv("Subscription filter delivered to Kinesis stream {0} partitionKey {1}", streamName, partitionKey);
|
||||
}
|
||||
|
||||
private void deliverToFirehose(AwsArnUtils.Arn arn, byte[] gzippedBytes,
|
||||
String targetAccount, String targetRegion) {
|
||||
if (firehoseService == null) {
|
||||
LOG.warnv("Cannot deliver to Firehose; service not available: {0}", arn);
|
||||
return;
|
||||
}
|
||||
String streamName = arn.resource().startsWith("deliverystream/")
|
||||
? arn.resource().substring("deliverystream/".length()) : arn.resource();
|
||||
Record record = new Record(gzippedBytes);
|
||||
firehoseService.putRecord(targetAccount, targetRegion, streamName, record);
|
||||
LOG.debugv("Subscription filter delivered to Firehose delivery stream: {0}", streamName);
|
||||
}
|
||||
|
||||
static byte[] gzip(byte[] input) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(64, input.length / 2));
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
|
||||
gzip.write(input);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
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;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
class CloudWatchLogsSubscriptionDeliveryServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String GROUP = "/app/production";
|
||||
private static final String STREAM = "backend-stream";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private CloudWatchLogsService logsService;
|
||||
private CloudWatchLogsSubscriptionDeliveryService deliveryService;
|
||||
private LambdaService lambdaService;
|
||||
private KinesisService kinesisService;
|
||||
private FirehoseService firehoseService;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
|
||||
Event<LogEventsIngested> ingestedEvent = mock(Event.class);
|
||||
|
||||
logsService = new CloudWatchLogsService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
10_000,
|
||||
Integer.MAX_VALUE,
|
||||
regionResolver,
|
||||
0L,
|
||||
System::currentTimeMillis,
|
||||
ingestedEvent,
|
||||
null
|
||||
);
|
||||
|
||||
lambdaService = mock(LambdaService.class);
|
||||
kinesisService = mock(KinesisService.class);
|
||||
firehoseService = mock(FirehoseService.class);
|
||||
|
||||
deliveryService = new CloudWatchLogsSubscriptionDeliveryService(
|
||||
logsService,
|
||||
lambdaService,
|
||||
kinesisService,
|
||||
firehoseService,
|
||||
regionResolver,
|
||||
MAPPER
|
||||
);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
LogEventsIngested event = invocation.getArgument(0);
|
||||
deliveryService.onLogEventsIngested(event);
|
||||
return null;
|
||||
}).when(ingestedEvent).fire(any());
|
||||
|
||||
logsService.createLogGroup(GROUP, null, null, REGION);
|
||||
logsService.createLogStream(GROUP, STREAM, REGION);
|
||||
}
|
||||
|
||||
private static byte[] decompress(byte[] compressed) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
|
||||
in.transferTo(out);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliversMatchingEventToLambda() throws Exception {
|
||||
String lambdaArn = "arn:aws:lambda:us-east-1:123456789012:function:log-processor";
|
||||
logsService.putSubscriptionFilter(GROUP, "lambda-filter", "ERROR", lambdaArn, null, REGION);
|
||||
|
||||
long timestamp = 1759406400000L;
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", timestamp, "message", "ERROR: database connection timed out"),
|
||||
Map.of("timestamp", timestamp + 10, "message", "INFO: retry successful")
|
||||
), REGION);
|
||||
|
||||
ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(lambdaArn), captor.capture(), eq(InvocationType.Event));
|
||||
|
||||
JsonNode lambdaRoot = MAPPER.readTree(captor.getValue());
|
||||
assertTrue(lambdaRoot.has("awslogs"));
|
||||
String base64Data = lambdaRoot.path("awslogs").path("data").asText();
|
||||
assertNotNull(base64Data);
|
||||
|
||||
byte[] decompressedBytes = decompress(Base64.getDecoder().decode(base64Data));
|
||||
JsonNode payload = MAPPER.readTree(decompressedBytes);
|
||||
|
||||
assertEquals("DATA_MESSAGE", payload.get("messageType").asText());
|
||||
assertEquals(ACCOUNT, payload.get("owner").asText());
|
||||
assertEquals(GROUP, payload.get("logGroup").asText());
|
||||
assertEquals(STREAM, payload.get("logStream").asText());
|
||||
assertEquals(1, payload.get("subscriptionFilters").size());
|
||||
assertEquals("lambda-filter", payload.get("subscriptionFilters").get(0).asText());
|
||||
|
||||
JsonNode logEvents = payload.get("logEvents");
|
||||
assertEquals(1, logEvents.size());
|
||||
assertEquals("ERROR: database connection timed out", logEvents.get(0).get("message").asText());
|
||||
assertEquals(timestamp, logEvents.get(0).get("timestamp").asLong());
|
||||
assertNotNull(logEvents.get(0).get("id").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliversMatchingEventToKinesisWithByLogStreamDistribution() throws Exception {
|
||||
String kinesisArn = "arn:aws:kinesis:us-east-1:123456789012:stream/order-events";
|
||||
logsService.putSubscriptionFilter(GROUP, "kinesis-filter", "", kinesisArn, "ByLogStream", REGION);
|
||||
|
||||
long timestamp = 1759406401000L;
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", timestamp, "message", "user logged in")
|
||||
), REGION);
|
||||
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
ArgumentCaptor<String> partitionKeyCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(kinesisService).putRecordForAccount(
|
||||
eq(ACCOUNT),
|
||||
eq("order-events"),
|
||||
dataCaptor.capture(),
|
||||
partitionKeyCaptor.capture(),
|
||||
eq(REGION)
|
||||
);
|
||||
|
||||
assertEquals(STREAM, partitionKeyCaptor.getValue());
|
||||
|
||||
byte[] decompressedBytes = decompress(dataCaptor.getValue());
|
||||
JsonNode payload = MAPPER.readTree(decompressedBytes);
|
||||
|
||||
assertEquals("DATA_MESSAGE", payload.get("messageType").asText());
|
||||
assertEquals(ACCOUNT, payload.get("owner").asText());
|
||||
assertEquals(GROUP, payload.get("logGroup").asText());
|
||||
assertEquals(STREAM, payload.get("logStream").asText());
|
||||
assertEquals("kinesis-filter", payload.get("subscriptionFilters").get(0).asText());
|
||||
assertEquals(1, payload.get("logEvents").size());
|
||||
assertEquals("user logged in", payload.get("logEvents").get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliversMatchingEventToKinesisWithRandomDistribution() throws Exception {
|
||||
String kinesisArn = "arn:aws:kinesis:us-east-1:123456789012:stream/order-events";
|
||||
logsService.putSubscriptionFilter(GROUP, "kinesis-filter", "", kinesisArn, "Random", REGION);
|
||||
|
||||
long timestamp = 1759406402000L;
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", timestamp, "message", "payment processed")
|
||||
), REGION);
|
||||
|
||||
ArgumentCaptor<String> partitionKeyCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(kinesisService).putRecordForAccount(
|
||||
eq(ACCOUNT),
|
||||
eq("order-events"),
|
||||
any(byte[].class),
|
||||
partitionKeyCaptor.capture(),
|
||||
eq(REGION)
|
||||
);
|
||||
|
||||
String partitionKey = partitionKeyCaptor.getValue();
|
||||
assertFalse(partitionKey.equals(STREAM));
|
||||
assertNotNull(UUID.fromString(partitionKey));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliversMatchingEventToFirehose() throws Exception {
|
||||
String firehoseArn = "arn:aws:firehose:us-east-1:123456789012:deliverystream/app-logs-sink";
|
||||
logsService.putSubscriptionFilter(GROUP, "firehose-filter", "CRITICAL", firehoseArn, null, REGION);
|
||||
|
||||
long timestamp = 1759406403000L;
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", timestamp, "message", "CRITICAL: out of memory")
|
||||
), REGION);
|
||||
|
||||
ArgumentCaptor<Record> recordCaptor = ArgumentCaptor.forClass(Record.class);
|
||||
|
||||
verify(firehoseService).putRecord(
|
||||
eq(ACCOUNT),
|
||||
eq(REGION),
|
||||
eq("app-logs-sink"),
|
||||
recordCaptor.capture()
|
||||
);
|
||||
|
||||
byte[] decompressedBytes = decompress(recordCaptor.getValue().getData());
|
||||
JsonNode payload = MAPPER.readTree(decompressedBytes);
|
||||
|
||||
assertEquals("DATA_MESSAGE", payload.get("messageType").asText());
|
||||
assertEquals(ACCOUNT, payload.get("owner").asText());
|
||||
assertEquals(GROUP, payload.get("logGroup").asText());
|
||||
assertEquals(STREAM, payload.get("logStream").asText());
|
||||
assertEquals("firehose-filter", payload.get("subscriptionFilters").get(0).asText());
|
||||
assertEquals(1, payload.get("logEvents").size());
|
||||
assertEquals("CRITICAL: out of memory", payload.get("logEvents").get(0).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonMatchingEventDeliversNothing() {
|
||||
String lambdaArn = "arn:aws:lambda:us-east-1:123456789012:function:log-processor";
|
||||
logsService.putSubscriptionFilter(GROUP, "error-filter", "ERROR", lambdaArn, null, REGION);
|
||||
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", System.currentTimeMillis(), "message", "INFO: everything normal")
|
||||
), REGION);
|
||||
|
||||
verifyNoInteractions(lambdaService);
|
||||
verifyNoInteractions(kinesisService);
|
||||
verifyNoInteractions(firehoseService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterPatternSelectingPartOfBatchDeliversOnlyMatches() throws Exception {
|
||||
String lambdaArn = "arn:aws:lambda:us-east-1:123456789012:function:log-processor";
|
||||
logsService.putSubscriptionFilter(GROUP, "warn-filter", "WARN", lambdaArn, null, REGION);
|
||||
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", 1000L, "message", "WARN: disk usage high"),
|
||||
Map.of("timestamp", 1001L, "message", "INFO: status check"),
|
||||
Map.of("timestamp", 1002L, "message", "WARN: memory usage high")
|
||||
), REGION);
|
||||
|
||||
ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(lambdaArn), captor.capture(), eq(InvocationType.Event));
|
||||
|
||||
JsonNode root = MAPPER.readTree(captor.getValue());
|
||||
byte[] decompressed = decompress(Base64.getDecoder().decode(root.path("awslogs").path("data").asText()));
|
||||
JsonNode payload = MAPPER.readTree(decompressed);
|
||||
|
||||
JsonNode events = payload.get("logEvents");
|
||||
assertEquals(2, events.size());
|
||||
assertEquals("WARN: disk usage high", events.get(0).get("message").asText());
|
||||
assertEquals("WARN: memory usage high", events.get(1).get("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoFiltersOnOneLogGroupBothFire() {
|
||||
String lambdaArn = "arn:aws:lambda:us-east-1:123456789012:function:error-handler";
|
||||
String kinesisArn = "arn:aws:kinesis:us-east-1:123456789012:stream/all-events";
|
||||
|
||||
logsService.putSubscriptionFilter(GROUP, "filter-lambda", "ERROR", lambdaArn, null, REGION);
|
||||
logsService.putSubscriptionFilter(GROUP, "filter-kinesis", "", kinesisArn, null, REGION);
|
||||
|
||||
logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", System.currentTimeMillis(), "message", "ERROR: fatal crash")
|
||||
), REGION);
|
||||
|
||||
verify(lambdaService).invokeArn(eq(lambdaArn), any(byte[].class), eq(InvocationType.Event));
|
||||
verify(kinesisService).putRecordForAccount(eq(ACCOUNT), eq("all-events"), any(byte[].class), any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unresolvableDestinationLeavesPutLogEventsSuccessful() {
|
||||
String brokenArn = "arn:aws:kinesis:us-east-1:123456789012:stream/nonexistent";
|
||||
logsService.putSubscriptionFilter(GROUP, "broken-filter", "", brokenArn, null, REGION);
|
||||
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Stream not found", 400))
|
||||
.when(kinesisService).putRecordForAccount(any(), any(), any(), any(), any());
|
||||
|
||||
String nextToken = logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", 1000L, "message", "persisted message")
|
||||
), REGION);
|
||||
|
||||
assertNotNull(nextToken);
|
||||
|
||||
CloudWatchLogsService.LogEventsResult result =
|
||||
logsService.getLogEvents(GROUP, STREAM, null, null, 10, false, null, REGION);
|
||||
assertEquals(1, result.events().size());
|
||||
assertEquals("persisted message", result.events().getFirst().getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unparseableDestinationArnLeavesPutLogEventsSuccessful() {
|
||||
logsService.putSubscriptionFilter(GROUP, "invalid-arn-filter", "", "not-an-arn", null, REGION);
|
||||
|
||||
String nextToken = logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", 2000L, "message", "still stored")
|
||||
), REGION);
|
||||
|
||||
assertNotNull(nextToken);
|
||||
verifyNoInteractions(lambdaService);
|
||||
verifyNoInteractions(kinesisService);
|
||||
verifyNoInteractions(firehoseService);
|
||||
|
||||
CloudWatchLogsService.LogEventsResult result =
|
||||
logsService.getLogEvents(GROUP, STREAM, null, null, 10, false, null, REGION);
|
||||
assertEquals(1, result.events().size());
|
||||
assertEquals("still stored", result.events().getFirst().getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void logGroupWithNoFiltersBehavesNormally() {
|
||||
String otherGroup = "/app/unsubscribed";
|
||||
logsService.createLogGroup(otherGroup, null, null, REGION);
|
||||
logsService.createLogStream(otherGroup, "stream1", REGION);
|
||||
|
||||
String nextToken = logsService.putLogEvents(otherGroup, "stream1", List.of(
|
||||
Map.of("timestamp", 3000L, "message", "unsubscribed event")
|
||||
), REGION);
|
||||
|
||||
assertNotNull(nextToken);
|
||||
verifyNoInteractions(lambdaService);
|
||||
verifyNoInteractions(kinesisService);
|
||||
verifyNoInteractions(firehoseService);
|
||||
|
||||
CloudWatchLogsService.LogEventsResult result =
|
||||
logsService.getLogEvents(otherGroup, "stream1", null, null, 10, false, null, REGION);
|
||||
assertEquals(1, result.events().size());
|
||||
assertEquals("unsubscribed event", result.events().getFirst().getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountDestinationWithoutLogsDestinationIsSkipped() {
|
||||
String otherAccountArn = "arn:aws:kinesis:us-east-1:999999999999:stream/other-stream";
|
||||
logsService.putSubscriptionFilter(GROUP, "cross-acct-filter", "", otherAccountArn, null, REGION);
|
||||
|
||||
String nextToken = logsService.putLogEvents(GROUP, STREAM, List.of(
|
||||
Map.of("timestamp", 4000L, "message", "message for foreign stream")
|
||||
), REGION);
|
||||
|
||||
assertNotNull(nextToken);
|
||||
verifyNoInteractions(kinesisService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void selfSubscribedLambdaSkipsDeliveryToPreventRecursiveLoop() {
|
||||
String fnName = "my-worker";
|
||||
String selfGroup = "/aws/lambda/" + fnName;
|
||||
String selfArn = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:" + fnName;
|
||||
|
||||
logsService.createLogGroup(selfGroup, null, null, REGION);
|
||||
logsService.createLogStream(selfGroup, "stream1", REGION);
|
||||
logsService.putSubscriptionFilter(selfGroup, "loop-filter", "", selfArn, null, REGION);
|
||||
|
||||
String nextToken = logsService.putLogEvents(selfGroup, "stream1", List.of(
|
||||
Map.of("timestamp", 5000L, "message", "lambda container log line")
|
||||
), REGION);
|
||||
|
||||
assertNotNull(nextToken);
|
||||
verifyNoInteractions(lambdaService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void largeBatchExceedingPayloadLimitIsChunkedAcrossMultipleRecords() {
|
||||
String kinesisArn = "arn:aws:kinesis:us-east-1:" + ACCOUNT + ":stream/large-stream";
|
||||
logsService.putSubscriptionFilter(GROUP, "chunk-filter", "", kinesisArn, null, REGION);
|
||||
|
||||
// Generate events with random content so gzip payload exceeds 1,000,000 bytes
|
||||
Random rnd = new Random(42);
|
||||
List<Map<String, Object>> events = new ArrayList<>();
|
||||
for (int i = 0; i < 30; i++) {
|
||||
byte[] bytes = new byte[40_000];
|
||||
rnd.nextBytes(bytes);
|
||||
String message = Base64.getEncoder().encodeToString(bytes);
|
||||
events.add(Map.of("timestamp", 6000L + i, "message", message));
|
||||
}
|
||||
|
||||
logsService.putLogEvents(GROUP, STREAM, events, REGION);
|
||||
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(kinesisService, atLeast(2)).putRecordForAccount(
|
||||
eq(ACCOUNT),
|
||||
eq("large-stream"),
|
||||
dataCaptor.capture(),
|
||||
any(),
|
||||
eq(REGION)
|
||||
);
|
||||
|
||||
for (byte[] recordBytes : dataCaptor.getAllValues()) {
|
||||
assertTrue(recordBytes.length <= 1_000_000, "Delivered record exceeds maximum payload bytes");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedChunkDoesNotStopDeliveryOfRemainingChunks() {
|
||||
String kinesisArn = "arn:aws:kinesis:us-east-1:" + ACCOUNT + ":stream/isolated-stream";
|
||||
logsService.putSubscriptionFilter(GROUP, "resilient-filter", "", kinesisArn, null, REGION);
|
||||
|
||||
Random rnd = new Random(42);
|
||||
List<Map<String, Object>> events = new ArrayList<>();
|
||||
for (int i = 0; i < 30; i++) {
|
||||
byte[] bytes = new byte[40_000];
|
||||
rnd.nextBytes(bytes);
|
||||
String message = Base64.getEncoder().encodeToString(bytes);
|
||||
events.add(Map.of("timestamp", 7000L + i, "message", message));
|
||||
}
|
||||
|
||||
doThrow(new AwsException("ProvisionedThroughputExceededException", "Rate exceeded", 400))
|
||||
.doReturn("seq-ok")
|
||||
.when(kinesisService).putRecordForAccount(any(), any(), any(), any(), any());
|
||||
|
||||
String nextToken = logsService.putLogEvents(GROUP, STREAM, events, REGION);
|
||||
assertNotNull(nextToken);
|
||||
|
||||
verify(kinesisService, atLeast(2)).putRecordForAccount(
|
||||
eq(ACCOUNT),
|
||||
eq("isolated-stream"),
|
||||
any(byte[].class),
|
||||
any(),
|
||||
eq(REGION)
|
||||
);
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/**
|
||||
* End-to-end integration test verifying that PutLogEvents delivers matching log events
|
||||
* to a Kinesis data stream destination configured through PutSubscriptionFilter.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudWatchLogsSubscriptionFilterIntegrationTest {
|
||||
|
||||
private static final String KINESIS_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String LOGS_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static Response kinesis(String action, String body) {
|
||||
return given()
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "Kinesis_20131202." + action)
|
||||
.body(body)
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static Response logs(String action, String body) {
|
||||
return given()
|
||||
.contentType(LOGS_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "Logs_20140328." + action)
|
||||
.body(body)
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static byte[] decompress(byte[] compressed) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
|
||||
in.transferTo(out);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliversIngestedLogEventsToKinesisDestination() throws Exception {
|
||||
String streamName = "sub-stream-" + System.nanoTime();
|
||||
kinesis("CreateStream", "{\"StreamName\":\"" + streamName + "\",\"ShardCount\":1}")
|
||||
.then().statusCode(200);
|
||||
|
||||
String streamArn = kinesis("DescribeStreamSummary", "{\"StreamName\":\"" + streamName + "\"}")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("StreamDescriptionSummary.StreamARN");
|
||||
assertNotNull(streamArn);
|
||||
|
||||
String group = "/sub/kinesis-" + System.nanoTime();
|
||||
String stream = "app-stream";
|
||||
logs("CreateLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200);
|
||||
logs("CreateLogStream", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"" + stream + "\"}")
|
||||
.then().statusCode(200);
|
||||
|
||||
logs("PutSubscriptionFilter", """
|
||||
{"logGroupName":"%s","filterName":"kinesis-sink","filterPattern":"ERROR","destinationArn":"%s"}
|
||||
""".formatted(group, streamArn))
|
||||
.then().statusCode(200);
|
||||
|
||||
long timestamp = 1759406400000L;
|
||||
logs("PutLogEvents", """
|
||||
{"logGroupName":"%s","logStreamName":"%s","logEvents":[
|
||||
{"timestamp":%d,"message":"ERROR: database connection timed out"},
|
||||
{"timestamp":%d,"message":"INFO: application started"}
|
||||
]}
|
||||
""".formatted(group, stream, timestamp, timestamp + 10))
|
||||
.then().statusCode(200);
|
||||
|
||||
String iterator = kinesis("GetShardIterator", """
|
||||
{"StreamName":"%s","ShardId":"shardId-000000000000","ShardIteratorType":"TRIM_HORIZON"}
|
||||
""".formatted(streamName))
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ShardIterator");
|
||||
assertNotNull(iterator);
|
||||
|
||||
Response getRecordsResponse = kinesis("GetRecords", """
|
||||
{"ShardIterator":"%s"}
|
||||
""".formatted(iterator))
|
||||
.then().statusCode(200)
|
||||
.extract().response();
|
||||
|
||||
List<Map<String, Object>> records = getRecordsResponse.jsonPath().getList("Records");
|
||||
assertEquals(1, records.size());
|
||||
assertEquals(stream, records.getFirst().get("PartitionKey"));
|
||||
|
||||
String base64Data = (String) records.getFirst().get("Data");
|
||||
assertNotNull(base64Data);
|
||||
|
||||
byte[] compressed = Base64.getDecoder().decode(base64Data);
|
||||
byte[] decompressed = decompress(compressed);
|
||||
JsonNode root = MAPPER.readTree(decompressed);
|
||||
|
||||
assertEquals("DATA_MESSAGE", root.path("messageType").asText());
|
||||
assertEquals(group, root.path("logGroup").asText());
|
||||
assertEquals(stream, root.path("logStream").asText());
|
||||
assertEquals(1, root.path("subscriptionFilters").size());
|
||||
assertEquals("kinesis-sink", root.path("subscriptionFilters").get(0).asText());
|
||||
|
||||
JsonNode logEvents = root.path("logEvents");
|
||||
assertEquals(1, logEvents.size());
|
||||
assertEquals("ERROR: database connection timed out", logEvents.get(0).path("message").asText());
|
||||
assertEquals(timestamp, logEvents.get(0).path("timestamp").asLong());
|
||||
assertNotNull(logEvents.get(0).path("id").asText());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user