refactor(core): gzip in-memory content through one Gzip.compress helper (#9364)

Four services gzipped a byte array held in memory with their own copy of the same lines: CloudTrail's
log file, a CloudWatch Logs subscription payload, a VPC flow log file and each line of a Redshift
audit log. core.common.Gzip.compress now does it once, and the four call it.

Writing to memory cannot fail, so the helper rethrows the compressor's IOException unchecked rather
than handing it to every caller; each caller already caught it as a runtime failure or had no way to
reach it. Its buffer starts small and grows with the compressed output, as the flow log
and Redshift writers' did, rather than being sized from the input. Writers that compress as they go, into a file or a stream they hand on (DynamoDB's export,
Firehose's per-format encoder, the EMR and Redshift UNLOAD writers), keep their own GZIPOutputStream.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-24 12:07:41 -04:00
1 parent bb579d5fe4
commit e15b64d07b
6 files changed
+90 -46

No files matched your search

@@ -0,0 +1,35 @@
package io.floci.aws.core.common;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.zip.GZIPOutputStream;
/**
* Gzips content held in memory, as a service does for a log file or a payload it delivers whole.
* A writer that compresses as it goes, into a file or a stream it hands on, keeps its own
* {@link GZIPOutputStream}.
*/
public final class Gzip {
private Gzip() {
}
/**
* {@code data} as one gzip member. Writing to memory cannot fail, so an {@link IOException}
* from the compressor is rethrown unchecked rather than handed to every caller.
*
* <p>The buffer starts small and grows with the compressed output rather than being sized from
* the input: a log compresses to a small part of its size, and a buffer reserved up front would
* hold memory the result never fills beside the input the caller already holds.
*/
public static byte[] compress(byte[] data) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(data);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return out.toByteArray();
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Gzip;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.ServicePrincipals;
@@ -18,7 +19,6 @@ import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.LocalDateTime;
@@ -31,7 +31,6 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.GZIPOutputStream;
/**
* Periodically drains queued CloudTrail records from {@link CloudTrailService}
@@ -250,12 +249,7 @@ public class CloudTrailLogWriter {
arr.add(r);
}
try {
byte[] json = mapper.writeValueAsBytes(envelope);
ByteArrayOutputStream baos = new ByteArrayOutputStream(Math.max(64, json.length / 4));
try (GZIPOutputStream gz = new GZIPOutputStream(baos)) {
gz.write(json);
}
return baos.toByteArray();
return Gzip.compress(mapper.writeValueAsBytes(envelope));
} catch (Exception e) {
throw new RuntimeException("Failed to serialize CloudTrail records", e);
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Gzip;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
@@ -24,14 +25,12 @@ 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
@@ -257,7 +256,7 @@ public class CloudWatchLogsSubscriptionDeliveryService {
List.of(filter.getFilterName()),
slice);
byte[] jsonBytes = objectMapper.writeValueAsBytes(payload);
gzippedBytes = gzip(jsonBytes);
gzippedBytes = Gzip.compress(jsonBytes);
} catch (Exception e) {
LOG.warnv(e, "Cannot serialize subscription payload: filter={0}", filter.getFilterName());
return;
@@ -318,12 +317,4 @@ public class CloudWatchLogsSubscriptionDeliveryService {
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();
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AvailabilityZoneIds;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Gzip;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.ec2.model.FlowLog;
@@ -20,7 +21,6 @@ import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -37,7 +37,6 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import static io.floci.aws.services.ec2.Ec2Ids.randomHex;
@@ -328,7 +327,7 @@ public class FlowLogService {
}
}
byte[] gz = gzip(sb.toString());
byte[] gz = Gzip.compress(sb.toString().getBytes(StandardCharsets.UTF_8));
String key = s3Key(fl, now);
try {
s3Service.putObject(fl.getBucketName(), key, gz, "application/octet-stream",
@@ -570,18 +569,6 @@ public class FlowLogService {
fl.getAccountId(), fl.getRegion(), datePath, file);
}
private static byte[] gzip(String content) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPOutputStream gz = new GZIPOutputStream(bos)) {
gz.write(content.getBytes(StandardCharsets.UTF_8));
}
return bos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("gzip failed", e);
}
}
/**
* The LogDestinationType a flow log gets: the requested one, else cloud-watch-logs when a log
* group is named directly or by a CloudWatch Logs ARN, else s3. CloudFormation compares an
@@ -3,6 +3,7 @@ package io.floci.aws.services.redshift;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.Gzip;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.ServiceCallAuthorizer;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
@@ -16,7 +17,6 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
@@ -31,7 +31,6 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
@ApplicationScoped
public class RedshiftAuditLogPublisher {
@@ -361,7 +360,7 @@ public class RedshiftAuditLogPublisher {
}
String line = formatS3Line(logType, record);
byte[] newMember = compressGzipMember(line);
byte[] newMember = Gzip.compress((line + "\n").getBytes(StandardCharsets.UTF_8));
int stripeIndex = Math.floorMod((bucket + "/" + key).hashCode(), STRIPE_COUNT);
Object lock = deliveryStripes[stripeIndex];
synchronized (lock) {
@@ -397,15 +396,6 @@ public class RedshiftAuditLogPublisher {
}
}
private static byte[] compressGzipMember(String newLine) throws IOException {
ByteArrayOutputStream lineGz = new ByteArrayOutputStream();
try (GZIPOutputStream gos = new GZIPOutputStream(lineGz)) {
gos.write(newLine.getBytes(StandardCharsets.UTF_8));
gos.write('\n');
}
return lineGz.toByteArray();
}
private byte[] appendGzipMember(String bucket, String key, byte[] newMember) throws IOException {
byte[] existingBytes = null;
try {