mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
ea1231b8b4
commit
a79e04e4ec
10 files changed
+535
-26
No files matched your search
@@ -15,8 +15,8 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@@ -31,13 +31,16 @@ public class FirehoseService {
|
||||
private final Map<String, List<byte[]>> buffers = new ConcurrentHashMap<>();
|
||||
private final S3Service s3Service;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, RegionResolver regionResolver) {
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, RegionResolver regionResolver,
|
||||
Clock clock) {
|
||||
this.streamStore = storageFactory.create("firehose", "streams.json",
|
||||
new TypeReference<Map<String, DeliveryStreamDescription>>() {});
|
||||
this.s3Service = s3Service;
|
||||
this.regionResolver = regionResolver;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String createDeliveryStream(String name, S3Destination s3Config) {
|
||||
@@ -142,6 +145,7 @@ public class FirehoseService {
|
||||
if (update.getPrefix() != null) current.setPrefix(update.getPrefix());
|
||||
if (update.getErrorOutputPrefix() != null) current.setErrorOutputPrefix(update.getErrorOutputPrefix());
|
||||
if (update.getCompressionFormat() != null) current.setCompressionFormat(update.getCompressionFormat());
|
||||
if (update.getCustomTimeZone() != null) current.setCustomTimeZone(update.getCustomTimeZone());
|
||||
if (update.getBufferingHints() != null) current.setBufferingHints(update.getBufferingHints());
|
||||
if (update.getEncryptionConfiguration() != null) current.setEncryptionConfiguration(update.getEncryptionConfiguration());
|
||||
}
|
||||
@@ -258,8 +262,10 @@ public class FirehoseService {
|
||||
|
||||
try {
|
||||
String bucket = resolveBucket(stream);
|
||||
String prefix = resolvePrefix(stream);
|
||||
String key = prefix + UUID.randomUUID() + ".json";
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
ZoneId zone = S3ObjectKeyResolver.resolveZone(s3 != null ? s3.getCustomTimeZone() : null);
|
||||
String key = S3ObjectKeyResolver.resolveKey(s3 != null ? s3.getPrefix() : null,
|
||||
stream.getDeliveryStreamName(), stream.getVersionId(), clock.instant(), zone);
|
||||
|
||||
ensureBucket(bucket);
|
||||
|
||||
@@ -288,21 +294,6 @@ public class FirehoseService {
|
||||
return DEFAULT_BUCKET;
|
||||
}
|
||||
|
||||
private String resolvePrefix(DeliveryStreamDescription stream) {
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
String prefix = (s3 != null && s3.getPrefix() != null) ? s3.getPrefix() : stream.getDeliveryStreamName() + "/";
|
||||
|
||||
// Substitute time-based placeholders matching real Firehose
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
prefix = prefix
|
||||
.replace("{year}", String.format("%04d", now.getYear()))
|
||||
.replace("{month}", String.format("%02d", now.getMonthValue()))
|
||||
.replace("{day}", String.format("%02d", now.getDayOfMonth()))
|
||||
.replace("{hour}", String.format("%02d", now.getHour()));
|
||||
|
||||
return prefix.endsWith("/") ? prefix : prefix + "/";
|
||||
}
|
||||
|
||||
private void ensureBucket(String bucket) {
|
||||
try {
|
||||
s3Service.createBucket(bucket, regionResolver.getDefaultRegion());
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Builds S3 object keys for Firehose deliveries the way AWS does (verified
|
||||
* against real AWS, see https://github.com/floci-io/floci/issues/1857): the key
|
||||
* is {@code <evaluated prefix><suffix>} where the prefix supports
|
||||
* {@code !{timestamp:<DateTimeFormatter pattern>}} and
|
||||
* {@code !{firehose:random-string}} expressions, {@code yyyy/MM/dd/HH/} is
|
||||
* appended by literal concatenation when the prefix holds no expression at all
|
||||
* (including the null/empty prefix), and the suffix is
|
||||
* {@code <streamName>-<versionId>-<yyyy-MM-dd-HH-mm-ss>-<uuid>} with no file
|
||||
* extension.
|
||||
*
|
||||
* Known deviations from AWS: timestamps are evaluated at delivery time instead
|
||||
* of the oldest buffered record's arrival time, and expressions AWS would
|
||||
* reject at create time (unknown namespaces, dynamic-partitioning keys,
|
||||
* invalid patterns) are kept literally in the key instead of failing.
|
||||
*/
|
||||
final class S3ObjectKeyResolver {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(S3ObjectKeyResolver.class);
|
||||
private static final Pattern EXPRESSION = Pattern.compile("!\\{(?<namespace>[^:}]*)(?::(?<argument>[^}]*))?}");
|
||||
private static final DateTimeFormatter DEFAULT_TIME_PREFIX =
|
||||
DateTimeFormatter.ofPattern("yyyy/MM/dd/HH/", Locale.ROOT);
|
||||
private static final DateTimeFormatter SUFFIX_TIMESTAMP =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss", Locale.ROOT);
|
||||
private static final String RANDOM_STRING_ALPHABET =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
private static final int RANDOM_STRING_LENGTH = 11;
|
||||
|
||||
private S3ObjectKeyResolver() {}
|
||||
|
||||
static String resolveKey(String prefix, String streamName, String versionId,
|
||||
Instant deliveryTime, ZoneId zone) {
|
||||
ZonedDateTime time = ZonedDateTime.ofInstant(deliveryTime, zone);
|
||||
return evaluatePrefix(prefix, time) + objectNameSuffix(streamName, versionId, time);
|
||||
}
|
||||
|
||||
static String evaluatePrefix(String prefix, ZonedDateTime time) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
boolean expressionSeen = false;
|
||||
Matcher matcher = EXPRESSION.matcher(prefix == null ? "" : prefix);
|
||||
while (matcher.find()) {
|
||||
expressionSeen = true;
|
||||
matcher.appendReplacement(out, Matcher.quoteReplacement(evaluateExpression(matcher, time)));
|
||||
}
|
||||
matcher.appendTail(out);
|
||||
if (!expressionSeen) {
|
||||
out.append(DEFAULT_TIME_PREFIX.format(time));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
static String objectNameSuffix(String streamName, String versionId, ZonedDateTime time) {
|
||||
return streamName + "-" + versionId + "-" + SUFFIX_TIMESTAMP.format(time) + "-" + UUID.randomUUID();
|
||||
}
|
||||
|
||||
static ZoneId resolveZone(String customTimeZone) {
|
||||
if (customTimeZone == null || customTimeZone.isBlank()) {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
try {
|
||||
return ZoneId.of(customTimeZone);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Invalid CustomTimeZone {0}, evaluating S3 prefixes in UTC", customTimeZone);
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
}
|
||||
|
||||
private static String evaluateExpression(Matcher matcher, ZonedDateTime time) {
|
||||
String namespace = matcher.group("namespace");
|
||||
String argument = matcher.group("argument");
|
||||
if ("timestamp".equals(namespace) && argument != null) {
|
||||
return formatTimestamp(argument, matcher.group(), time);
|
||||
}
|
||||
if ("firehose".equals(namespace) && "random-string".equals(argument)) {
|
||||
return randomString();
|
||||
}
|
||||
LOG.warnv("Unsupported Firehose prefix expression {0}, keeping it literally", matcher.group());
|
||||
return matcher.group();
|
||||
}
|
||||
|
||||
private static String formatTimestamp(String pattern, String expression, ZonedDateTime time) {
|
||||
try {
|
||||
return DateTimeFormatter.ofPattern(pattern, Locale.ROOT).format(time);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Invalid pattern in Firehose prefix expression {0}, keeping it literally: {1}",
|
||||
expression, e.getMessage());
|
||||
return expression;
|
||||
}
|
||||
}
|
||||
|
||||
private static String randomString() {
|
||||
StringBuilder random = new StringBuilder(RANDOM_STRING_LENGTH);
|
||||
for (int i = 0; i < RANDOM_STRING_LENGTH; i++) {
|
||||
random.append(RANDOM_STRING_ALPHABET.charAt(
|
||||
ThreadLocalRandom.current().nextInt(RANDOM_STRING_ALPHABET.length())));
|
||||
}
|
||||
return random.toString();
|
||||
}
|
||||
}
|
||||
+4
@@ -126,6 +126,8 @@ public class DeliveryStreamDescription {
|
||||
private String errorOutputPrefix;
|
||||
@JsonProperty("CompressionFormat")
|
||||
private String compressionFormat;
|
||||
@JsonProperty("CustomTimeZone")
|
||||
private String customTimeZone;
|
||||
@JsonProperty("BufferingHints")
|
||||
private BufferingHints bufferingHints;
|
||||
@JsonProperty("EncryptionConfiguration")
|
||||
@@ -142,6 +144,8 @@ public class DeliveryStreamDescription {
|
||||
public void setErrorOutputPrefix(String errorOutputPrefix) { this.errorOutputPrefix = errorOutputPrefix; }
|
||||
public String getCompressionFormat() { return compressionFormat; }
|
||||
public void setCompressionFormat(String compressionFormat) { this.compressionFormat = compressionFormat; }
|
||||
public String getCustomTimeZone() { return customTimeZone; }
|
||||
public void setCustomTimeZone(String customTimeZone) { this.customTimeZone = customTimeZone; }
|
||||
public BufferingHints getBufferingHints() { return bufferingHints; }
|
||||
public void setBufferingHints(BufferingHints bufferingHints) { this.bufferingHints = bufferingHints; }
|
||||
public EncryptionConfiguration getEncryptionConfiguration() { return encryptionConfiguration; }
|
||||
|
||||
Reference in new issue
Block a user