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

@@ -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();