feat(firehose): run the Lambda processor of a Redshift destination (#7230)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-01 22:27:39 -04:00
1 parent 1cbf58a8ae
commit 8c32e9f6ba
13 files changed
+370 -60

No files matched your search

+7 -1
View File
@@ -189,7 +189,13 @@ Floci does not write the `redshift_failed` manifest objects that AWS creates aft
stream's account and region, through the workgroup proxy. A workgroup has one database, so a URL that names
another database fails the delivery, which then follows the usual retry path. Without a `Username` the workgroup's
admin user signs in.
- `ProcessingConfiguration` on a Redshift destination is accepted and returned but not executed.
- A Lambda processor in the `ProcessingConfiguration` of a Redshift destination runs before the batch is staged,
as it does for an S3 destination: records the function drops are not loaded, and records it fails are written to
the error output of the intermediate S3 configuration. The configuration is validated on create and update
like an S3 destination's, and a Lambda processor is described with the same default parameters (`NumberOfRetries`,
`RoleArn`, buffer hints). Those defaults are carried over from the probed S3 behavior and not probed for Redshift
specifically. With `S3BackupMode` enabled, the backup object holds the untransformed source records, even when the
Lambda processor drops every record.
- The `COPY` carries no credentials, so the proxy reads the staged object as an anonymous client. With S3
authorization enforced and a private intermediate bucket the load fails and the staged object stays in S3; use a
bucket the anonymous principal can read, or leave enforcement off.
@@ -6,6 +6,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.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Processor;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessorParameter;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
@@ -94,7 +95,7 @@ public class FirehoseLambdaTransformer {
public Outcome transform(DeliveryStreamDescription stream, String bucket, List<byte[]> records,
Instant deliveryTime) {
S3Destination s3 = stream.s3Destination();
Processor processor = lambdaProcessor(s3);
Processor processor = lambdaProcessor(stream);
if (processor == null) {
return new Outcome(records, 0, 0, null);
}
@@ -136,11 +137,15 @@ public class FirehoseLambdaTransformer {
* stream has none: the other processor types AWS models are stored and echoed but not
* applied. The validator has already made "at most one" true.
*/
private static Processor lambdaProcessor(S3Destination s3) {
if (s3 == null || !s3.isProcessingEnabled() || s3.getProcessingConfiguration().getProcessors() == null) {
private static Processor lambdaProcessor(DeliveryStreamDescription stream) {
if (stream == null || !stream.isProcessingEnabled()) {
return null;
}
for (Processor processor : s3.getProcessingConfiguration().getProcessors()) {
ProcessingConfiguration processing = stream.processingConfiguration();
if (processing.getProcessors() == null) {
return null;
}
for (Processor processor : processing.getProcessors()) {
if (processor != null && "Lambda".equals(processor.getType())
&& parameterValue(processor, "LambdaArn") != null) {
return processor;
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.KinesisStreamSource;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
@@ -417,6 +418,10 @@ public class FirehoseService implements ResourceProvider {
}
DataFormatConversionValidator.validateEffective(s3Config);
ProcessingConfigurationValidator.validateEffective(s3Config);
if (redshift != null) {
ProcessingConfigurationValidator.validateEffective(redshift.getProcessingConfiguration());
redshift.canonicalizeProcessors();
}
if (s3Config != null) {
s3Config.canonicalizeProcessors();
}
@@ -545,7 +550,10 @@ public class FirehoseService implements ResourceProvider {
if (update.getS3Backup() != null && current.getS3Backup() == null) {
RedshiftDestinationValidator.validateNewBackup(update.getS3Backup(), "redshiftDestinationUpdate");
}
// The update's ProcessingConfiguration replaces the stored one outright, so it is what gets checked.
ProcessingConfigurationValidator.validateEffective(update.getProcessingConfiguration());
mergeRedshiftDestination(current, update);
current.canonicalizeProcessors();
stream.setVersionId(String.valueOf(parseVersionId(stream.getVersionId()) + 1));
stream.setLastUpdateTimestamp(Instant.now());
streamPut(streamKey, stream);
@@ -1152,7 +1160,7 @@ public class FirehoseService implements ResourceProvider {
String bucket = resolveBucket(stream);
S3Destination s3 = stream.s3Destination();
List<byte[]> records = toFlush;
if (s3 != null && s3.isProcessingEnabled()) {
if (s3 != null && stream.isProcessingEnabled()) {
ensureBucket(bucket, stream);
FirehoseLambdaTransformer.Outcome transformed =
lambdaTransformer.transform(stream, bucket, records, clock.instant());
@@ -1160,6 +1168,10 @@ public class FirehoseService implements ResourceProvider {
records.size(), streamName, transformed.droppedRecords(), transformed.failedRecords());
records = transformed.records();
if (records.isEmpty()) {
if (isRedshiftStream(stream)) {
RedshiftDestination redshift = stream.getDestinations().get(0).getRedshiftDestinationDescription();
writeRedshiftBackup(stream, redshift, toFlush);
}
// Nothing survived the transform. The batch is accounted for, dropped
// records deliberately leaving no trace and failed ones already in the
// error output, so the source may advance past it.
@@ -1184,28 +1196,14 @@ public class FirehoseService implements ResourceProvider {
ensureBucket(bucket, stream);
// Records are arbitrary bytes, so they are concatenated as bytes: routing
// them through a String would corrupt any payload that is not valid UTF-8.
// The appended newline is a deliberate deviation kept from before this
// method compressed anything: real AWS inserts no separator at all
// (verified: three "abc" records arrive as the 9 bytes "abcabcabc").
// See the deviation noted in docs/services/firehose.md.
ByteArrayOutputStream payload = new ByteArrayOutputStream();
for (byte[] data : records) {
payload.writeBytes(data);
if (data.length > 0 && data[data.length - 1] != '\n') {
payload.write('\n');
}
}
byte[] rawPayload = payload.toByteArray();
byte[] rawPayload = concatenateRecords(records);
byte[] body = compression.compress(rawPayload);
s3Service.putObject(bucket, key, body, "application/octet-stream", Map.of(),
new PutObjectOptions().withContentEncoding(compression.contentEncoding()));
LOG.infov("Flushed {0} records from stream {1} to s3://{2}/{3} ({4})",
records.size(), streamName, bucket, key, compression.wireValue());
if (isRedshiftStream(stream)) {
deliverRedshiftBatch(streamName, stream, bucket, key, rawPayload, checkpoint);
deliverRedshiftBatch(streamName, stream, bucket, key, toFlush, checkpoint);
return;
}
// Only now: the records these iterators were read past are durable.
@@ -1223,15 +1221,12 @@ public class FirehoseService implements ResourceProvider {
* backup write or checkpoint write is logged instead, and the load itself retries from the queue.
*/
private void deliverRedshiftBatch(String streamName, DeliveryStreamDescription stream,
String bucket, String key, byte[] rawPayload,
String bucket, String key, List<byte[]> toFlush,
Map<String, String> checkpoint) {
RedshiftDestination redshift = stream.getDestinations().get(0).getRedshiftDestinationDescription();
try {
writeRedshiftBackup(stream, redshift, rawPayload);
} catch (IOException | RuntimeException e) {
LOG.errorv(e, "Backup write for stream {0} failed; the batch is staged in S3 and loads normally but "
+ "has no backup copy: {1}", streamName, describe(e));
}
writeRedshiftBackupSafely(streamName, stream, redshift, toFlush,
"Backup write for stream {0} failed; the batch is staged in S3 and loads normally but "
+ "has no backup copy: {1}");
try {
commitSourceIterators(streamName, checkpoint);
} catch (RuntimeException e) {
@@ -1393,13 +1388,24 @@ public class FirehoseService implements ResourceProvider {
return e.getMessage() != null ? e.getMessage() : e.toString();
}
/** Writes the raw batch to the backup location under that location's own prefix, compression and bucket. */
private void writeRedshiftBackupSafely(String streamName, DeliveryStreamDescription stream,
RedshiftDestination redshift, List<byte[]> sourceRecords,
String failureMessage) {
try {
writeRedshiftBackup(stream, redshift, sourceRecords);
} catch (IOException | RuntimeException e) {
LOG.errorv(e, failureMessage, streamName, describe(e));
}
}
/** Writes the untransformed source records to the backup location under that location's own prefix, compression and bucket. */
private void writeRedshiftBackup(DeliveryStreamDescription stream, RedshiftDestination redshift,
byte[] rawPayload) throws IOException {
List<byte[]> sourceRecords) throws IOException {
S3Destination backup = redshift.getS3Backup();
if (!"Enabled".equals(redshift.getS3BackupMode()) || backup == null || backup.bucketName() == null) {
return;
}
byte[] rawPayload = concatenateRecords(sourceRecords);
FirehoseCompression compression = FirehoseCompression.forDelivery(backup.getCompressionFormat());
String backupKey = S3ObjectKeyResolver.resolveKey(backup, stream.getDeliveryStreamName(),
stream.getVersionId(), clock.instant(), compression);
@@ -1409,6 +1415,24 @@ public class FirehoseService implements ResourceProvider {
new PutObjectOptions().withContentEncoding(compression.contentEncoding()));
}
/**
* Records are arbitrary bytes, so they are concatenated as bytes: routing them through a String
* would corrupt any payload that is not valid UTF-8. The appended newline is a deliberate deviation
* kept from before this method compressed anything: real AWS inserts no separator at all
* (verified: three "abc" records arrive as the 9 bytes "abcabcabc"). See the deviation noted in
* docs/services/firehose.md.
*/
private static byte[] concatenateRecords(List<byte[]> records) {
ByteArrayOutputStream payload = new ByteArrayOutputStream();
for (byte[] data : records) {
payload.writeBytes(data);
if (data.length > 0 && data[data.length - 1] != '\n') {
payload.write('\n');
}
}
return payload.toByteArray();
}
private static boolean isRedshiftStream(DeliveryStreamDescription stream) {
return stream.getDestinations() != null && !stream.getDestinations().isEmpty()
&& stream.getDestinations().get(0).getRedshiftDestinationDescription() != null;
@@ -36,11 +36,11 @@ final class ProcessingConfigurationValidator {
private ProcessingConfigurationValidator() {}
static void validateEffective(S3Destination config) {
if (config == null || config.getProcessingConfiguration() == null) {
return;
}
ProcessingConfiguration processing = config.getProcessingConfiguration();
if (processing.getProcessors() == null) {
validateEffective(config == null ? null : config.getProcessingConfiguration());
}
static void validateEffective(ProcessingConfiguration processing) {
if (processing == null || processing.getProcessors() == null) {
return;
}
// Before anything a processor's own parameters say: a repeated name is rejected
@@ -161,6 +161,7 @@ final class RedshiftDestinationValidator {
"secretsManagerConfiguration.secretARN", violations);
}
}
S3DestinationValidator.collectProcessingViolations(dest.getProcessingConfiguration(), shape, violations);
S3Destination s3 = dest.getS3();
if (s3 != null && s3.getPrefix() != null && UNREADABLE_KEY_CHARS.matcher(s3.getPrefix()).find()) {
violations.add(violation(shape, "s3Configuration.prefix",
@@ -118,7 +118,7 @@ public final class S3DestinationValidator {
collectOpenXMappingViolations(config, shapeName, violations);
collectSchemaViolations(config, shapeName, violations);
collectLoggingViolations(config, shapeName, violations);
collectProcessingViolations(config, shapeName, violations);
collectProcessingViolations(config.getProcessingConfiguration(), shapeName, violations);
if (!violations.isEmpty()) {
throw constraintViolations(violations);
}
@@ -418,9 +418,8 @@ public final class S3DestinationValidator {
}
/** Members are numbered from 1 in these paths, as the probed messages show. */
private static void collectProcessingViolations(S3Destination config, String shapeName,
List<String> violations) {
ProcessingConfiguration processing = config.getProcessingConfiguration();
static void collectProcessingViolations(ProcessingConfiguration processing, String shapeName,
List<String> violations) {
if (processing == null || processing.getProcessors() == null) {
return;
}
@@ -165,6 +165,36 @@ public class DeliveryStreamDescription {
return first.getExtendedS3DestinationDescription();
}
/**
* The ProcessingConfiguration that transforms this stream's records, or null when it has none. A Redshift
* destination carries its own, next to its intermediate S3 configuration; any other destination keeps it
* on the S3 destination.
*/
public ProcessingConfiguration processingConfiguration() {
if (destinations == null || destinations.isEmpty()) {
return null;
}
Destination first = destinations.get(0);
if (first.getRedshiftDestinationDescription() != null) {
return first.getRedshiftDestinationDescription().getProcessingConfiguration();
}
S3Destination s3 = first.getExtendedS3DestinationDescription();
return s3 == null ? null : s3.getProcessingConfiguration();
}
/**
* True when a transformation applies to deliveries: the configuration is present
* and Enabled is explicitly true. An omitted Enabled leaves it disabled, the
* opposite of the conversion block below. Probed rather than carried over from
* there (2026-09-11): DescribeDeliveryStream echoes an omitted Enabled as false
* here and as true on the conversion block.
*/
@JsonIgnore
public boolean isProcessingEnabled() {
ProcessingConfiguration processing = processingConfiguration();
return processing != null && Boolean.TRUE.equals(processing.getEnabled());
}
/**
* Fills the AWS defaults on every S3 configuration the stream describes: its S3 destination, or
* a Redshift destination's intermediate and backup configurations.
@@ -300,21 +330,6 @@ public class DeliveryStreamDescription {
public CloudWatchLoggingOptions getCloudWatchLoggingOptions() { return cloudWatchLoggingOptions; }
public void setCloudWatchLoggingOptions(CloudWatchLoggingOptions options) { this.cloudWatchLoggingOptions = options; }
/**
* True when a transformation applies to deliveries: the configuration is present
* and Enabled is explicitly true. An omitted Enabled leaves it disabled, the
* opposite of the conversion block below. Probed rather than carried over from
* there (2026-09-11): DescribeDeliveryStream echoes an omitted Enabled as false
* here and as true on the conversion block.
*
* Ignored for serialization for the same reason as the accessor below.
*/
@JsonIgnore
public boolean isProcessingEnabled() {
return processingConfiguration != null
&& Boolean.TRUE.equals(processingConfiguration.getEnabled());
}
/**
* True when data format conversion applies to deliveries: the configuration is
* present and not explicitly disabled. AWS treats an omitted Enabled as enabled
@@ -399,6 +414,14 @@ public class DeliveryStreamDescription {
* role was current at the time of the read.
*/
public void canonicalizeProcessors() {
canonicalizeProcessors(processingConfiguration, roleArn);
}
/**
* The same defaults for a ProcessingConfiguration that is not an S3 destination's own, as a Redshift
* destination's is; {@code roleArn} is the role of the destination that carries it.
*/
public static void canonicalizeProcessors(ProcessingConfiguration processingConfiguration, String roleArn) {
if (processingConfiguration == null) {
return;
}
@@ -80,6 +80,15 @@ public class RedshiftDestination {
this.cloudWatchLoggingOptions = cloudWatchLoggingOptions;
}
/**
* Fills the defaults AWS describes a Lambda processor with, as the destination is written: the role comes from
* this destination's own {@code RoleARN}. Applied as an S3 destination's ProcessingConfiguration is, since both
* carry the same shape; AWS has not been probed for a Redshift destination specifically.
*/
public void canonicalizeProcessors() {
S3Destination.canonicalizeProcessors(processingConfiguration, roleArn);
}
/** Shallow copy without the password, for responses. Nested objects are shared and must not be mutated. */
public RedshiftDestination copyWithoutPassword() {
RedshiftDestination copy = new RedshiftDestination();
@@ -391,7 +391,7 @@ class LeafCfnProvisionerTest {
assertEquals(Boolean.TRUE, destination.getCloudWatchLoggingOptions().getEnabled());
assertEquals("g", destination.getCloudWatchLoggingOptions().getLogGroupName());
assertEquals("st", destination.getCloudWatchLoggingOptions().getLogStreamName());
assertTrue(destination.isProcessingEnabled());
assertEquals(Boolean.TRUE, destination.getProcessingConfiguration().getEnabled());
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:f", destination.getProcessingConfiguration()
.getProcessors().get(0).getParameters().get(0).getParameterValue());
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Processor;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessorParameter;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
@@ -80,6 +81,22 @@ class FirehoseLambdaTransformerTest {
return new DeliveryStreamDescription("stream", "arn:aws:firehose:us-west-2:000000000000:deliverystream/stream", s3);
}
/** A stream whose Lambda is configured on its Redshift destination, as AWS models it, not on its S3 location. */
private DeliveryStreamDescription redshiftStream() throws Exception {
RedshiftDestination redshift = mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"CopyCommand": {"DataTableName": "events"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"BucketARN": "arn:aws:s3:::results",
"ErrorOutputPrefix": "errors/!{firehose:error-output-type}/"},
"ProcessingConfiguration": {"Enabled": true, "Processors": [{"Type": "Lambda",
"Parameters": [{"ParameterName": "LambdaArn", "ParameterValue": "%s"}]}]}}
""".formatted(FUNCTION_ARN), RedshiftDestination.class);
return new DeliveryStreamDescription("stream",
"arn:aws:firehose:us-west-2:000000000000:deliverystream/stream", null, redshift, null);
}
private static Processor lambdaProcessor(String... parameters) {
List<ProcessorParameter> list = new ArrayList<>();
list.add(parameter("LambdaArn", FUNCTION_ARN));
@@ -202,6 +219,38 @@ class FirehoseLambdaTransformerTest {
verifyNoInteractions(lambdaService);
}
@Test
void aRedshiftStreamIsTransformedByTheLambdaOfItsDestination() throws Exception {
replyWith(ids -> records(ok(ids.get(0), "one"), outcome(ids.get(1), "Dropped")));
FirehoseLambdaTransformer.Outcome outcome = transform(redshiftStream(), record("a"), record("b"));
assertEquals(List.of("one"), delivered(outcome));
assertEquals(1, outcome.droppedRecords());
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), any(), eq(InvocationType.RequestResponse));
}
@Test
void aRedshiftStreamsFailedRecordsGoToTheErrorOutputOfItsIntermediateS3Location() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed")));
FirehoseLambdaTransformer.Outcome outcome = transform(redshiftStream(), record("a"));
assertEquals(1, outcome.failedRecords());
assertEquals(1, errorLines().size());
}
@Test
void aRedshiftStreamWithADisabledProcessingConfigurationIsNotTransformed() throws Exception {
DeliveryStreamDescription stream = redshiftStream();
stream.processingConfiguration().setEnabled(false);
FirehoseLambdaTransformer.Outcome outcome = transform(stream, record("a"));
assertEquals(List.of("a"), delivered(outcome));
verifyNoInteractions(lambdaService);
}
@Test
void aProcessorTypeFlociDoesNotApplyLeavesTheRecordsAlone() {
Processor appendDelimiter = new Processor();
@@ -27,7 +27,6 @@ import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -363,7 +362,6 @@ class FirehoseProcessingConfigurationTest {
S3Destination stored = service.describeDeliveryStream("stream").s3Destination();
assertEquals(false, stored.getProcessingConfiguration().getEnabled());
assertFalse(stored.isProcessingEnabled());
}
/**
@@ -399,7 +397,6 @@ class FirehoseProcessingConfigurationTest {
stored.applyDefaults();
assertEquals(false, processing.getEnabled());
assertFalse(stored.isProcessingEnabled());
}
private static String parameterValue(List<ProcessorParameter> parameters, String name) {
@@ -2,9 +2,11 @@ package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.databind.ObjectMapper;
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.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
@@ -30,6 +32,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.anyLong;
@@ -39,6 +42,7 @@ 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.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -53,6 +57,7 @@ class FirehoseRedshiftServiceTest {
private FirehoseService service;
private S3Service s3Service;
private FirehoseRedshiftDelivery delivery;
private FirehoseLambdaTransformer transformer;
private MutableClock clock;
private StorageFactory storageFactory;
private RegionResolver regionResolver;
@@ -68,6 +73,7 @@ class FirehoseRedshiftServiceTest {
k -> AccountAwareStorageBackend.inMemory("000000000000")));
s3Service = Mockito.mock(S3Service.class);
delivery = Mockito.mock(FirehoseRedshiftDelivery.class);
transformer = Mockito.mock(FirehoseLambdaTransformer.class);
clock = new MutableClock();
EmulatorConfig.FirehoseServiceConfig firehoseCfg = mock(EmulatorConfig.FirehoseServiceConfig.class);
@@ -82,7 +88,167 @@ class FirehoseRedshiftServiceTest {
service = new FirehoseService(storageFactory, s3Service, new KinesisService(storageFactory, regionResolver),
regionResolver, clock, config, mock(FirehoseParquetConverter.class),
mock(FirehoseLambdaTransformer.class), delivery, Runnable::run);
transformer, delivery, Runnable::run);
}
private static final String LAMBDA_PROCESSING = ", \"ProcessingConfiguration\": {\"Enabled\": true, "
+ "\"Processors\": [{\"Type\": \"Lambda\", \"Parameters\": [{\"ParameterName\": \"LambdaArn\", "
+ "\"ParameterValue\": \"arn:aws:lambda:us-east-1:000000000000:function:xform\"}]}]}";
@Test
void recordsAreTransformedByTheRedshiftDestinationsLambdaBeforeStaging() throws Exception {
createStream(LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"id\":2}".getBytes(StandardCharsets.UTF_8)), 0, 0, null));
service.flush(STREAM);
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("stage"), anyString(), body.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":2}\n", new String(body.getValue(), StandardCharsets.UTF_8));
verify(delivery, times(1)).copy(eq("000000000000"), eq("us-east-1"), any(), eq("stage"), anyString());
}
@Test
void aRedshiftLambdaProcessorIsDescribedWithItsDefaultParameters() throws Exception {
createStream(LAMBDA_PROCESSING);
List<DeliveryStreamDescription.ProcessorParameter> parameters = service.describeDeliveryStream(STREAM)
.getDestinations().get(0).getRedshiftDestinationDescription().getProcessingConfiguration()
.getProcessors().get(0).getParameters();
Map<String, String> byName = new HashMap<>();
parameters.forEach(parameter -> byName.put(parameter.getParameterName(), parameter.getParameterValue()));
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:xform", byName.get("LambdaArn"));
assertEquals("3", byName.get("NumberOfRetries"));
assertEquals("arn:aws:iam::000000000000:role/firehose", byName.get("RoleArn"));
assertEquals("1", byName.get("BufferSizeInMBs"));
assertEquals("60", byName.get("BufferIntervalInSeconds"));
}
@Test
void aDisabledProcessingConfigurationDoesNotTransform() throws Exception {
createStream(LAMBDA_PROCESSING.replace("\"Enabled\": true", "\"Enabled\": false"));
service.flush(STREAM);
verify(transformer, never()).transform(any(), anyString(), any(), any());
verifyStagedTimes(1);
}
@Test
void whenTheLambdaDropsEveryRecordNothingIsStagedOrLoaded() throws Exception {
createStream(LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(
new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
service.flush(STREAM);
verifyStagedTimes(0);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
}
@Test
void backupEnabledWithLambdaTransformKeepsTheUntransformedSourceRecords() throws Exception {
createStream(BACKUP_ENABLED + LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"id\":2}".getBytes(StandardCharsets.UTF_8)), 0, 0, null));
service.flush(STREAM);
verifyStagedTimes(1);
ArgumentCaptor<byte[]> staged = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("stage"), anyString(), staged.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":2}\n", new String(staged.getValue(), StandardCharsets.UTF_8));
ArgumentCaptor<byte[]> backup = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("bk"), anyString(), backup.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":1}\n", new String(backup.getValue(), StandardCharsets.UTF_8));
}
@Test
void backupEnabledWhenLambdaDropsEveryRecordStillWritesTheSourceRecordsToBackup() throws Exception {
createStream(BACKUP_ENABLED + LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(
new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
service.flush(STREAM);
verifyStagedTimes(0);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
ArgumentCaptor<byte[]> backup = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("bk"), anyString(), backup.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":1}\n", new String(backup.getValue(), StandardCharsets.UTF_8));
}
@Test
void backupWriteFailureWhenLambdaDropsEveryRecordLeavesTheBatchBufferedForRetry() throws Exception {
createStream(BACKUP_ENABLED + LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(
new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
doThrow(new IllegalStateException("s3 unavailable")).when(s3Service)
.putObject(eq("bk"), anyString(), any(byte[].class), anyString(), anyMap(), any());
service.flush(STREAM);
verifyStagedTimes(0);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
// The failed backup kept the batch buffered: a second flush retries the backup write
reset(s3Service);
service.flush(STREAM);
ArgumentCaptor<byte[]> backup = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("bk"), anyString(), backup.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":1}\n", new String(backup.getValue(), StandardCharsets.UTF_8));
}
@Test
void aRedshiftProcessingConfigurationWithTwoLambdaProcessorsIsRejected() throws Exception {
String lambda = "{\"Type\": \"Lambda\", \"Parameters\": [{\"ParameterName\": \"LambdaArn\", "
+ "\"ParameterValue\": \"arn:aws:lambda:us-east-1:000000000000:function:xform\"}]}";
String twoProcessors = ", \"ProcessingConfiguration\": {\"Enabled\": true, \"Processors\": ["
+ lambda + "," + lambda + "]}";
AwsException error = assertThrows(AwsException.class, () -> createStream(twoProcessors));
assertEquals("InvalidArgumentException", error.getErrorCode());
}
@Test
void aRedshiftLambdaProcessorWithoutALambdaArnIsRejected() throws Exception {
String withoutArn = ", \"ProcessingConfiguration\": {\"Enabled\": true, \"Processors\": ["
+ "{\"Type\": \"Lambda\", \"Parameters\": []}]}";
AwsException error = assertThrows(AwsException.class, () -> createStream(withoutArn));
assertEquals("InvalidArgumentException", error.getErrorCode());
}
@Test
void updatingARedshiftDestinationValidatesAndAppliesItsProcessingConfiguration() throws Exception {
createStream("");
String destinationId = service.describeDeliveryStream(STREAM).getDestinations().get(0).getDestinationId();
RedshiftDestination invalid = mapper.readValue("{" + LAMBDA_PROCESSING.substring(2)
.replace("\"Parameters\": [{\"ParameterName\": \"LambdaArn\", \"ParameterValue\": "
+ "\"arn:aws:lambda:us-east-1:000000000000:function:xform\"}]", "\"Parameters\": []") + "}",
RedshiftDestination.class);
assertThrows(AwsException.class,
() -> service.updateRedshiftDestination(STREAM, "1", destinationId, invalid));
RedshiftDestination valid = mapper.readValue("{" + LAMBDA_PROCESSING.substring(2) + "}",
RedshiftDestination.class);
service.updateRedshiftDestination(STREAM, "1", destinationId, valid);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"id\":3}".getBytes(StandardCharsets.UTF_8)), 0, 0, null));
service.flush(STREAM);
verify(transformer, times(1)).transform(any(), eq("stage"), any(), any());
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("stage"), anyString(), body.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":3}\n", new String(body.getValue(), StandardCharsets.UTF_8));
}
private RedshiftDestination destination(String extraMembers) throws Exception {
@@ -10,6 +10,7 @@ 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.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
class RedshiftDestinationModelTest {
@@ -81,6 +82,36 @@ class RedshiftDestinationModelTest {
assertEquals("stage", reloaded.s3Destination().bucketName());
}
@Test
void aRedshiftStreamsProcessingConfigurationIsTheDestinationsOwn() throws Exception {
RedshiftDestination dest = mapper.readValue("""
{"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/r", "BucketARN": "arn:aws:s3:::stage"},
"ProcessingConfiguration": {"Enabled": true, "Processors": [{"Type": "Lambda"}]}}""",
RedshiftDestination.class);
DeliveryStreamDescription stream = new DeliveryStreamDescription("s", "arn", null, dest, null);
assertSame(dest.getProcessingConfiguration(), stream.processingConfiguration());
assertNull(stream.s3Destination().getProcessingConfiguration());
}
@Test
void aRedshiftStreamWithoutProcessingHasNoProcessingConfiguration() throws Exception {
RedshiftDestination dest = mapper.readValue(CONFIG, RedshiftDestination.class);
assertNull(new DeliveryStreamDescription("s", "arn", null, dest, null).processingConfiguration());
}
@Test
void anS3StreamsProcessingConfigurationIsTheS3Destinations() {
DeliveryStreamDescription.S3Destination s3 = new DeliveryStreamDescription.S3Destination();
DeliveryStreamDescription.ProcessingConfiguration processing =
new DeliveryStreamDescription.ProcessingConfiguration();
s3.setProcessingConfiguration(processing);
assertSame(processing, new DeliveryStreamDescription("s", "arn", s3).processingConfiguration());
}
@Test
void redshiftStreamWithoutBucketHasNoBucketName() throws Exception {
RedshiftDestination dest = mapper.readValue(