fix(firehose): build S3 object keys with AWS prefix expressions and name suffix (#1858)

* fix(firehose): build S3 object keys with AWS prefix expressions and name suffix

Delivered objects now follow the AWS key format
<evaluated prefix><stream>-<version>-<yyyy-MM-dd-HH-mm-ss>-<uuid> observed on
real AWS: default prefix yyyy/MM/dd/HH/ when no Prefix is set, literal
concatenation of the time prefix for expression-free prefixes,
!{timestamp:<pattern>} and !{firehose:random-string} evaluation, no .json
extension, and CustomTimeZone support. The non-AWS {year}/{month}/{day}/{hour}
placeholders are gone.

See floci-io/floci#1857 for the behavior captured against a real AWS account.

* refactor(firehose): cache the default time-prefix DateTimeFormatter

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
This commit is contained in:
Mihai BlidaruandMihai Blidaru authored and GitHub committed 2026-08-11 21:40:24 -04:00
1 parent ea1231b8b4
commit a79e04e4ec
10 files changed
+535 -26

No files matched your search

@@ -8,9 +8,13 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -320,4 +324,142 @@ class FirehoseExtendedS3IntegrationTest {
.statusCode(400)
.body("__type", equalTo("InvalidArgumentException"));
}
// Delivery-plane coverage: flushed objects follow the AWS key format
// <evaluated prefix><stream>-<version>-<yyyy-MM-dd-HH-mm-ss>-<uuid> observed
// on real AWS (https://github.com/floci-io/floci/issues/1857).
private static final String SUFFIX_REGEX =
"-1-\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
private static final String TIME_PREFIX_REGEX = "\\d{4}/\\d{2}/\\d{2}/\\d{2}/";
@Test
@Order(11)
void deliveryWithoutPrefixUsesAwsDefaultTimePrefix() {
String stream = "delivery-default-stream";
String bucket = "extended-s3-delivery-default";
createDeliveryStream(stream, bucket, "");
putFiveRecords(stream);
String key = firstDeliveredKey(bucket, "");
assertTrue(key.matches(TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
}
@Test
@Order(12)
void deliveryAppendsTimePrefixToStaticPrefix() {
String stream = "delivery-static-stream";
String bucket = "extended-s3-delivery-static";
createDeliveryStream(stream, bucket, ", \"Prefix\": \"events/data/\"");
putFiveRecords(stream);
String key = firstDeliveredKey(bucket, "events/data/");
assertTrue(key.matches("events/data/" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
}
@Test
@Order(13)
void deliveryConcatenatesTimePrefixWithoutInsertingSlash() {
String stream = "delivery-noslash-stream";
String bucket = "extended-s3-delivery-noslash";
createDeliveryStream(stream, bucket, ", \"Prefix\": \"legacy\"");
putFiveRecords(stream);
String key = firstDeliveredKey(bucket, "legacy");
assertTrue(key.matches("legacy" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
}
@Test
@Order(14)
void deliveryEvaluatesTimestampExpressionWithoutAppendingDefault() {
String stream = "delivery-expr-stream";
String bucket = "extended-s3-delivery-expr";
createDeliveryStream(stream, bucket, ", \"Prefix\": \"data/!{timestamp:yyyy/MM/dd}/\"");
putFiveRecords(stream);
String key = firstDeliveredKey(bucket, "data/");
assertTrue(key.matches("data/\\d{4}/\\d{2}/\\d{2}/" + stream + SUFFIX_REGEX), key);
}
@Test
@Order(15)
void deliveryEvaluatesRandomStringExpressionWithoutAppendingDefault() {
String stream = "delivery-rand-stream";
String bucket = "extended-s3-delivery-rand";
createDeliveryStream(stream, bucket, ", \"Prefix\": \"rand/!{firehose:random-string}/\"");
putFiveRecords(stream);
String key = firstDeliveredKey(bucket, "rand/");
assertTrue(key.matches("rand/[A-Za-z0-9]{11}/" + stream + SUFFIX_REGEX), key);
}
@Test
@Order(16)
void customTimeZoneIsEchoedAndDeliveryKeepsAwsKeyShape() {
String stream = "delivery-tz-stream";
String bucket = "extended-s3-delivery-tz";
createDeliveryStream(stream, bucket,
", \"Prefix\": \"events/\", \"CustomTimeZone\": \"Europe/Madrid\"");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "DescribeDeliveryStream")
.body("{ \"DeliveryStreamName\": \"" + stream + "\" }")
.when()
.post("/")
.then()
.statusCode(200)
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CustomTimeZone",
equalTo("Europe/Madrid"));
putFiveRecords(stream);
String key = firstDeliveredKey(bucket, "events/");
assertTrue(key.matches("events/" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
}
private void createDeliveryStream(String streamName, String bucket, String extraDestinationJson) {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
.body("""
{
"DeliveryStreamName": "%s",
"ExtendedS3DestinationConfiguration": {
"RoleARN": "%s",
"BucketARN": "arn:aws:s3:::%s"%s
}
}
""".formatted(streamName, ROLE_ARN, bucket, extraDestinationJson))
.when()
.post("/")
.then()
.statusCode(200);
}
/** Five records reach DEFAULT_FLUSH_COUNT, so the batch triggers the automatic flush. */
private void putFiveRecords(String streamName) {
String data = Base64.getEncoder().encodeToString("{\"id\": 1}".getBytes(StandardCharsets.UTF_8));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "PutRecordBatch")
.body("""
{
"DeliveryStreamName": "%s",
"Records": [
{"Data": "%s"}, {"Data": "%s"}, {"Data": "%s"}, {"Data": "%s"}, {"Data": "%s"}
]
}
""".formatted(streamName, data, data, data, data, data))
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedPutCount", equalTo(0));
}
private String firstDeliveredKey(String bucket, String listPrefix) {
return given().when().get("/" + bucket + "?prefix=" + listPrefix)
.then().statusCode(200)
.extract().xmlPath().getString("ListBucketResult.Contents[0].Key");
}
}
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
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.s3.S3Service;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class FirehoseServiceTest {
private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
private FirehoseService firehoseService;
private S3Service s3Service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenReturn(new InMemoryStorage<>());
s3Service = Mockito.mock(S3Service.class);
firehoseService = new FirehoseService(storageFactory, s3Service,
new RegionResolver("us-east-1", "000000000000"), new MutableClock());
}
private void putRecordsUntilFlush(String streamName) {
for (int i = 0; i < 5; i++) {
Record record = new Record(("{\"n\":" + i + "}").getBytes(StandardCharsets.UTF_8));
firehoseService.putRecord(streamName, record);
}
}
private String deliveredKey(String expectedBucket) {
ArgumentCaptor<String> bucket = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
verify(s3Service).putObject(bucket.capture(), key.capture(), any(byte[].class), anyString(), anyMap());
assertEquals(expectedBucket, bucket.getValue());
return key.getValue();
}
@Test
void deliversToDefaultBucketWithAwsShapedKey() {
firehoseService.createDeliveryStream("my-stream", null);
putRecordsUntilFlush("my-stream");
String key = deliveredKey("floci-firehose-results");
assertTrue(key.matches("2026/01/01/00/my-stream-1-2026-01-01-00-00-00-" + UUID_REGEX), key);
}
@Test
void staticPrefixGetsDefaultTimePrefixAppended() {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::custom-bucket");
s3.setPrefix("events/data/");
firehoseService.createDeliveryStream("my-stream", s3);
putRecordsUntilFlush("my-stream");
String key = deliveredKey("custom-bucket");
assertTrue(key.matches("events/data/2026/01/01/00/my-stream-1-2026-01-01-00-00-00-" + UUID_REGEX), key);
}
@Test
void customTimeZoneShiftsPrefixAndSuffix() {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::custom-bucket");
s3.setCustomTimeZone("Europe/Madrid");
firehoseService.createDeliveryStream("my-stream", s3);
putRecordsUntilFlush("my-stream");
String key = deliveredKey("custom-bucket");
assertTrue(key.matches("2026/01/01/01/my-stream-1-2026-01-01-01-00-00-" + UUID_REGEX), key);
}
@Test
void updateDestinationMergesCustomTimeZoneAndBumpsKeyVersion() {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::custom-bucket");
s3.setCustomTimeZone("Europe/Madrid");
firehoseService.createDeliveryStream("my-stream", s3);
S3Destination prefixOnly = new S3Destination();
prefixOnly.setPrefix("events/");
firehoseService.updateDestination("my-stream", "1", "destinationId-000000000001", prefixOnly);
DeliveryStreamDescription described = firehoseService.describeDeliveryStream("my-stream");
assertEquals("Europe/Madrid", described.s3Destination().getCustomTimeZone());
assertEquals("events/", described.s3Destination().getPrefix());
S3Destination timeZoneOnly = new S3Destination();
timeZoneOnly.setCustomTimeZone("Asia/Tokyo");
firehoseService.updateDestination("my-stream", "2", "destinationId-000000000001", timeZoneOnly);
assertEquals("Asia/Tokyo",
firehoseService.describeDeliveryStream("my-stream").s3Destination().getCustomTimeZone());
putRecordsUntilFlush("my-stream");
String key = deliveredKey("custom-bucket");
assertTrue(key.matches("events/2026/01/01/09/my-stream-3-2026-01-01-09-00-00-" + UUID_REGEX), key);
}
}
@@ -0,0 +1,123 @@
package io.github.hectorvent.floci.services.firehose;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class S3ObjectKeyResolverTest {
private static final Instant INSTANT = Instant.parse("2026-07-13T10:42:07Z");
private static final ZonedDateTime TIME = ZonedDateTime.ofInstant(INSTANT, ZoneOffset.UTC);
private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@Test
void nullPrefixEvaluatesToDefaultTimePrefix() {
assertEquals("2026/07/13/10/", S3ObjectKeyResolver.evaluatePrefix(null, TIME));
}
@Test
void emptyPrefixEvaluatesToDefaultTimePrefix() {
assertEquals("2026/07/13/10/", S3ObjectKeyResolver.evaluatePrefix("", TIME));
}
@Test
void staticPrefixGetsDefaultTimePrefixAppended() {
assertEquals("events/data/2026/07/13/10/", S3ObjectKeyResolver.evaluatePrefix("events/data/", TIME));
}
@Test
void staticPrefixWithoutTrailingSlashIsConcatenatedLiterally() {
assertEquals("legacy2026/07/13/10/", S3ObjectKeyResolver.evaluatePrefix("legacy", TIME));
}
@Test
void timestampExpressionIsEvaluatedWithoutAppendingDefault() {
assertEquals("data/2026/07/13/", S3ObjectKeyResolver.evaluatePrefix("data/!{timestamp:yyyy/MM/dd}/", TIME));
}
@Test
void multipleTimestampExpressionsShareTheSameInstant() {
assertEquals("year=2026/hour=10/",
S3ObjectKeyResolver.evaluatePrefix("year=!{timestamp:yyyy}/hour=!{timestamp:HH}/", TIME));
}
@Test
void singleQuotedTextInTimestampPatternIsLiteral() {
assertEquals("year=2026/", S3ObjectKeyResolver.evaluatePrefix("!{timestamp:'year='yyyy}/", TIME));
}
@Test
void randomStringExpressionYieldsFreshElevenCharAlphanumerics() {
String evaluated = S3ObjectKeyResolver.evaluatePrefix(
"rand/!{firehose:random-string}/!{firehose:random-string}/", TIME);
assertTrue(evaluated.matches("rand/[A-Za-z0-9]{11}/[A-Za-z0-9]{11}/"), evaluated);
String[] parts = evaluated.split("/");
assertNotEquals(parts[1], parts[2]);
}
// Observed on real AWS but not documented: the docs' semantic rules say the
// default time prefix is appended whenever there is no *timestamp* expression,
// yet a prefix whose only expression is !{firehose:random-string} gets nothing
// appended (https://github.com/floci-io/floci/issues/1857).
@Test
void randomStringExpressionSuppressesDefaultTimePrefix() {
String evaluated = S3ObjectKeyResolver.evaluatePrefix("rand/!{firehose:random-string}/", TIME);
assertTrue(evaluated.matches("rand/[A-Za-z0-9]{11}/"), evaluated);
}
@Test
void dynamicPartitioningExpressionIsKeptLiterally() {
assertEquals("data/!{partitionKeyFromQuery:customerId}/",
S3ObjectKeyResolver.evaluatePrefix("data/!{partitionKeyFromQuery:customerId}/", TIME));
}
@Test
void unknownNamespaceIsKeptLiterally() {
assertEquals("data/!{bogus}/", S3ObjectKeyResolver.evaluatePrefix("data/!{bogus}/", TIME));
}
@Test
void invalidTimestampPatternIsKeptLiterally() {
assertEquals("data/!{timestamp:bbbb}/", S3ObjectKeyResolver.evaluatePrefix("data/!{timestamp:bbbb}/", TIME));
}
@Test
void unclosedExpressionIsLiteralAndStillGetsDefaultAppended() {
assertEquals("data/!{timestamp:yyyy2026/07/13/10/",
S3ObjectKeyResolver.evaluatePrefix("data/!{timestamp:yyyy", TIME));
}
@Test
void objectNameSuffixFollowsAwsFormat() {
String suffix = S3ObjectKeyResolver.objectNameSuffix("my-stream", "1", TIME);
assertTrue(suffix.matches("my-stream-1-2026-07-13-10-42-07-" + UUID_REGEX), suffix);
}
@Test
void resolveKeyConcatenatesEvaluatedPrefixAndSuffix() {
String key = S3ObjectKeyResolver.resolveKey("legacy", "my-stream", "3", INSTANT, ZoneOffset.UTC);
assertTrue(key.matches("legacy2026/07/13/10/my-stream-3-2026-07-13-10-42-07-" + UUID_REGEX), key);
}
@Test
void customTimeZoneShiftsPrefixAndSuffixAcrossTheDayBoundary() {
String key = S3ObjectKeyResolver.resolveKey(null, "s", "1",
Instant.parse("2026-01-01T23:30:00Z"), ZoneId.of("Europe/Madrid"));
assertTrue(key.matches("2026/01/02/00/s-1-2026-01-02-00-30-00-" + UUID_REGEX), key);
}
@Test
void resolveZoneFallsBackToUtc() {
assertEquals(ZoneOffset.UTC, S3ObjectKeyResolver.resolveZone(null));
assertEquals(ZoneOffset.UTC, S3ObjectKeyResolver.resolveZone(" "));
assertEquals(ZoneOffset.UTC, S3ObjectKeyResolver.resolveZone("Not/AZone"));
assertEquals(ZoneId.of("Europe/Madrid"), S3ObjectKeyResolver.resolveZone("Europe/Madrid"));
}
}
@@ -546,8 +546,8 @@ class SesEventPublishingV2IntegrationTest {
.header("X-Amz-Target", "Firehose_20150804.CreateDeliveryStream")
.body("""
{"DeliveryStreamName": "%s",
"S3DestinationConfiguration": {"BucketARN": "arn:aws:s3:::%s"}}
""".formatted(FIREHOSE_STREAM, FIREHOSE_BUCKET))
"S3DestinationConfiguration": {"BucketARN": "arn:aws:s3:::%s", "Prefix": "%s/"}}
""".formatted(FIREHOSE_STREAM, FIREHOSE_BUCKET, FIREHOSE_STREAM))
.when()
.post("/")
.then()
@@ -676,8 +676,8 @@ class SesEventPublishingV2IntegrationTest {
.header("X-Amz-Target", "Firehose_20150804.CreateDeliveryStream")
.body("""
{"DeliveryStreamName": "%s",
"S3DestinationConfiguration": {"BucketARN": "arn:aws:s3:::%s"}}
""".formatted(streamDisabled, FIREHOSE_BUCKET))
"S3DestinationConfiguration": {"BucketARN": "arn:aws:s3:::%s", "Prefix": "%s/"}}
""".formatted(streamDisabled, FIREHOSE_BUCKET, streamDisabled))
.when()
.post("/")
.then()