feat(firehose): deliver staged Redshift batches with single-attempt COPY (#6006)

* feat(firehose): deliver staged Redshift batches with single-attempt COPY

A flush stages the batch in the intermediate S3 location, then runs COPY against the cluster proxy over JDBC simple-query mode without an IAM role. The load runs on its own thread so that slow COPY queries do not hold the shared flush executor or PutRecord callers, and failures are logged with the staged batch kept in S3.

* fix(firehose): address review comments on Redshift single-attempt COPY delivery

- Drain buffers before shutting down the Redshift delivery executor on Firehose shutdown and log dropped queued tasks.

- Catch RejectedExecutionException in deliverRedshiftBatch to prevent staged records from returning to the buffer.

- Extract DatabaseSecretCredentials helper in core.common to deduplicate Secrets Manager credentials parsing across RDS Data, Redshift Data, and Firehose.

- Extract RedshiftConnections test helper for waitForConnection and use DockerAvailability.isAvailable() in FirehoseRedshiftDeliveryIntegrationTest.

- Update docs and Javadocs to remove outdated references to retries and shared flush threads.

* fix(firehose): wait for queued Redshift COPY delivery before shutdown and log secret parse errors

* refactor(firehose): deduplicate dropAndLogQueuedTasks helper on shutdown
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-21 13:40:53 -04:00
1 parent ff813c6f34
commit fd37e109f8
16 files changed
+1373 -59

No files matched your search

@@ -0,0 +1,78 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.Optional;
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;
class DatabaseSecretCredentialsTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void parsesUsernameAndPassword() {
Optional<DatabaseSecretCredentials> creds = DatabaseSecretCredentials.parse(
"{\"username\":\"admin\",\"password\":\"secret123\"}");
assertTrue(creds.isPresent());
assertEquals("admin", creds.get().username());
assertEquals("secret123", creds.get().password());
}
@Test
void fallsBackToUserFieldWhenUsernameIsAbsent() {
Optional<DatabaseSecretCredentials> creds = DatabaseSecretCredentials.parse(
"{\"user\":\"postgres\",\"password\":\"secret456\"}");
assertTrue(creds.isPresent());
assertEquals("postgres", creds.get().username());
assertEquals("secret456", creds.get().password());
}
@Test
void parsesWithCustomMapper() {
Optional<DatabaseSecretCredentials> creds = DatabaseSecretCredentials.parse(
mapper, "{\"username\":\"admin\",\"password\":\"secret\"}");
assertTrue(creds.isPresent());
assertEquals("admin", creds.get().username());
assertEquals("secret", creds.get().password());
}
@Test
void returnsEmptyForNullOrBlank() {
assertTrue(DatabaseSecretCredentials.parse((String) null).isEmpty());
assertTrue(DatabaseSecretCredentials.parse((JsonNode) null).isEmpty());
assertTrue(DatabaseSecretCredentials.parse("").isEmpty());
assertTrue(DatabaseSecretCredentials.parse(" ").isEmpty());
}
@Test
void returnsEmptyForMalformedJson() {
assertTrue(DatabaseSecretCredentials.parse("not-a-json").isEmpty());
}
@Test
void returnsEmptyWhenMissingRequiredFields() {
assertTrue(DatabaseSecretCredentials.parse("{\"username\":\"admin\"}").isEmpty());
assertTrue(DatabaseSecretCredentials.parse("{\"password\":\"secret\"}").isEmpty());
assertTrue(DatabaseSecretCredentials.parse("{\"other\":\"value\"}").isEmpty());
}
@Test
void returnsEmptyForNonObjectNode() throws Exception {
assertTrue(DatabaseSecretCredentials.parse(mapper.readTree("[\"item\"]")).isEmpty());
}
@Test
void constructorRejectsNull() {
assertThrows(NullPointerException.class, () -> new DatabaseSecretCredentials(null, "pass"));
assertThrows(NullPointerException.class, () -> new DatabaseSecretCredentials("user", null));
}
}
@@ -0,0 +1,117 @@
package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.redshift.RedshiftConnections;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End to end: a record put into a Firehose stream with a Redshift destination is staged in S3 and
* loaded into the cluster table through COPY. Needs a Docker daemon, like every Redshift
* integration test.
*/
@QuarkusTest
class FirehoseRedshiftDeliveryIntegrationTest {
@Inject
FirehoseService firehoseService;
@Inject
RedshiftService redshiftService;
@Inject
ObjectMapper mapper;
private String clusterId;
@BeforeAll
static void requireDocker() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
"Docker daemon must be available for Firehose Redshift delivery integration tests");
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
redshiftService.deleteCluster(clusterId);
}
}
private RedshiftDestination destination(String clusterName, String table, String stageBucket) throws Exception {
return mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://%s.abc123.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "%s", "CopyOptions": "json 'auto'"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"BucketARN": "arn:aws:s3:::%s"}}
""".formatted(clusterName, table, stageBucket), RedshiftDestination.class);
}
@Test
void putRecordIsLoadedIntoTheRedshiftTable() throws Exception {
clusterId = "fh-rs-e2e";
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
try (Connection connection = RedshiftConnections.waitForConnection(cluster); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE fh_events (id int, name text)");
}
firehoseService.createDeliveryStream("us-east-1", "fh-to-redshift", null,
destination(clusterId, "fh_events", "fh-rs-stage"), List.of(), null, null);
firehoseService.putRecord("fh-to-redshift",
new Record("{\"id\":1,\"name\":\"alice\"}".getBytes(StandardCharsets.UTF_8)));
firehoseService.flush("fh-to-redshift");
Awaitility.await()
.atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(200))
.untilAsserted(() -> {
try (Connection connection = RedshiftConnections.waitForConnection(cluster);
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT id, name FROM fh_events")) {
assertTrue(rows.next(), "expected the delivered row in fh_events");
assertEquals(1, rows.getInt("id"));
assertEquals("alice", rows.getString("name"));
assertFalse(rows.next());
}
});
}
@Test
void missingTableKeepsTheStagedObjectAndTheRecord() throws Exception {
clusterId = "fh-rs-no-table";
redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
firehoseService.createDeliveryStream("us-east-1", "fh-no-table", null,
destination(clusterId, "does_not_exist", "fh-rs-no-table-stage"), List.of(), null, null);
firehoseService.putRecord("fh-no-table",
new Record("{\"id\":1,\"name\":\"alice\"}".getBytes(StandardCharsets.UTF_8)));
firehoseService.flush("fh-no-table");
String listing = given().when().get("/fh-rs-no-table-stage").then().statusCode(200).extract().asString();
assertTrue(listing.contains("<Key>"), "expected the staged object, got: " + listing);
}
}
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
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.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class FirehoseRedshiftDeliveryTest {
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
private RedshiftService redshift;
private SecretsManagerService secrets;
private final List<String[]> executed = new ArrayList<>();
private FirehoseRedshiftDelivery delivery;
@BeforeEach
void setUp() {
redshift = mock(RedshiftService.class);
secrets = mock(SecretsManagerService.class);
Cluster cluster = mock(Cluster.class);
when(cluster.getEndpoint()).thenReturn(new Endpoint("host.docker.internal", 41234));
when(cluster.getMasterUsername()).thenReturn("admin");
when(redshift.describeClustersForAccount("000000000000", "c1")).thenReturn(List.of(cluster));
delivery = new FirehoseRedshiftDelivery(redshift, secrets, mapper,
(url, user, password, sql) -> executed.add(new String[] {url, user, password, sql}));
}
private RedshiftDestination destination() throws Exception {
return mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "events", "CopyOptions": "json 'auto'"}}
""", RedshiftDestination.class);
}
@Test
void runsCopyWithoutAnIamRoleThroughTheProxyPortInSimpleMode() throws Exception {
delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1");
assertEquals(1, executed.size());
assertEquals("jdbc:postgresql://127.0.0.1:41234/dev?preferQueryMode=simple", executed.get(0)[0]);
assertEquals("admin", executed.get(0)[1]);
assertEquals("Secret123", executed.get(0)[2]);
assertEquals("COPY events FROM 's3://stage/k1' json 'auto'", executed.get(0)[3]);
}
@Test
void secretOverridesInlineCredentialsWhenEnabled() throws Exception {
RedshiftDestination dest = destination();
RedshiftDestination.SecretsManagerConfiguration cfg = new RedshiftDestination.SecretsManagerConfiguration();
cfg.setEnabled(true);
cfg.setSecretArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:rs-creds-AbCdEf");
dest.setSecretsManagerConfiguration(cfg);
SecretVersion version = mock(SecretVersion.class);
when(version.getSecretString()).thenReturn("{\"username\":\"fromsecret\",\"password\":\"pw-secret\"}");
when(secrets.getSecretValue(eq(cfg.getSecretArn()), any(), any(), eq("us-east-1"))).thenReturn(version);
delivery.copy("000000000000", "us-east-1", dest, "stage", "k1");
assertEquals("fromsecret", executed.get(0)[1]);
assertEquals("pw-secret", executed.get(0)[2]);
}
@Test
void disabledSecretsManagerKeepsTheInlineCredentials() throws Exception {
RedshiftDestination dest = destination();
RedshiftDestination.SecretsManagerConfiguration cfg = new RedshiftDestination.SecretsManagerConfiguration();
cfg.setEnabled(false);
dest.setSecretsManagerConfiguration(cfg);
delivery.copy("000000000000", "us-east-1", dest, "stage", "k1");
assertEquals("Secret123", executed.get(0)[2]);
}
@Test
void unknownClusterSurfacesAsAwsException() {
when(redshift.describeClustersForAccount("000000000000", "c1"))
.thenThrow(new AwsException("ClusterNotFound", "Cluster c1 not found", 404));
assertThrows(AwsException.class,
() -> delivery.copy("000000000000", "us-east-1", destination(), "stage", "k"));
}
@Test
void jdbcFailureIsWrappedWithTableClusterAndSqlState() {
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, secrets, mapper,
(url, user, password, sql) -> {
throw new SQLException("relation \"events\" does not exist", "42P01");
});
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> failing.copy("000000000000", "us-east-1", destination(), "stage", "k"));
assertTrue(e.getMessage().contains("events"), e.getMessage());
assertTrue(e.getMessage().contains("c1"), e.getMessage());
assertTrue(e.getMessage().contains("42P01"), e.getMessage());
}
@Test
void jdbcConnectionsCarryConnectAndSocketTimeouts() {
Properties properties = FirehoseRedshiftDelivery.connectionProperties("admin", "Secret123");
assertEquals("admin", properties.getProperty("user"));
assertEquals("Secret123", properties.getProperty("password"));
assertTrue(Integer.parseInt(properties.getProperty("connectTimeout")) > 0);
assertTrue(Integer.parseInt(properties.getProperty("socketTimeout")) > 0);
}
@Test
void closeFailureAfterACommittedCopyIsNotAFailedDelivery() throws Exception {
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
when(connection.createStatement()).thenReturn(statement);
doThrow(new SQLException("connection reset")).when(connection).close();
FirehoseRedshiftDelivery.executeAndClose(connection, "COPY t FROM 's3://b/k'");
verify(statement).execute("COPY t FROM 's3://b/k'");
}
@Test
void failedCopyIsReportedAndTheConnectionStillClosed() throws Exception {
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
when(connection.createStatement()).thenReturn(statement);
when(statement.execute(any())).thenThrow(new SQLException("relation does not exist", "42P01"));
SQLException e = assertThrows(SQLException.class,
() -> FirehoseRedshiftDelivery.executeAndClose(connection, "COPY t FROM 's3://b/k'"));
assertEquals("42P01", e.getSQLState());
verify(connection).close();
}
@Test
void destinationWithoutAnyPasswordFailsWithAClearMessage() throws Exception {
RedshiftDestination dest = destination();
dest.setPassword(null);
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.copy("000000000000", "us-east-1", dest, "stage", "k"));
assertTrue(e.getMessage().contains("Password"), e.getMessage());
}
}
@@ -233,7 +233,7 @@ class FirehoseRedshiftDestinationIntegrationTest {
}
@Test
void flushStagesTheBatchInTheIntermediateBucket() {
void flushWithAMissingClusterKeepsTheStagedObject() {
post("CreateDeliveryStream", createBody("rs-flush", "rs-flush-stage")).statusCode(200);
String data = Base64.getEncoder().encodeToString("{\"id\":1}".getBytes(StandardCharsets.UTF_8));
post("PutRecord", "{\"DeliveryStreamName\": \"rs-flush\", \"Record\": {\"Data\": \"" + data + "\"}}")
@@ -0,0 +1,279 @@
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.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.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
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.InOrder;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class FirehoseRedshiftServiceTest {
private static final String STREAM = "rs-delivery";
private static final String BACKUP_ENABLED = ", \"S3BackupMode\": \"Enabled\", \"S3BackupConfiguration\": "
+ "{\"RoleARN\": \"arn:aws:iam::000000000000:role/firehose\", \"BucketARN\": \"arn:aws:s3:::bk\"}";
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
private FirehoseService service;
private S3Service s3Service;
private FirehoseRedshiftDelivery delivery;
private MutableClock clock;
private StorageFactory storageFactory;
private RegionResolver regionResolver;
private EmulatorConfig config;
@BeforeEach
void setUp() {
storageFactory = Mockito.mock(StorageFactory.class);
Map<String, AccountAwareStorageBackend<?>> backends = new HashMap<>();
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> backends.computeIfAbsent(
invocation.getArgument(0) + "/" + invocation.getArgument(1),
k -> AccountAwareStorageBackend.inMemory("000000000000")));
s3Service = Mockito.mock(S3Service.class);
delivery = Mockito.mock(FirehoseRedshiftDelivery.class);
clock = new MutableClock();
EmulatorConfig.FirehoseServiceConfig firehoseCfg = mock(EmulatorConfig.FirehoseServiceConfig.class);
when(firehoseCfg.enabled()).thenReturn(true);
when(firehoseCfg.tickIntervalSeconds()).thenReturn(10L);
when(firehoseCfg.flushRecordCount()).thenReturn(0);
EmulatorConfig.ServicesConfig servicesCfg = mock(EmulatorConfig.ServicesConfig.class);
when(servicesCfg.firehose()).thenReturn(firehoseCfg);
config = mock(EmulatorConfig.class);
when(config.services()).thenReturn(servicesCfg);
regionResolver = new RegionResolver("us-east-1", "000000000000");
service = new FirehoseService(storageFactory, s3Service, new KinesisService(storageFactory, regionResolver),
regionResolver, clock, config, mock(FirehoseParquetConverter.class),
mock(FirehoseLambdaTransformer.class), delivery, Runnable::run);
}
private void createStream(String extraMembers) throws Exception {
RedshiftDestination destination = mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "events"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}
%s}
""".formatted(extraMembers), RedshiftDestination.class);
service.createDeliveryStream("us-east-1", STREAM, null, destination, List.of(), null, null);
service.putRecord(STREAM, new Record("{\"id\":1}".getBytes(StandardCharsets.UTF_8)));
}
private void copyFails() {
doThrow(new IllegalStateException("relation does not exist"))
.when(delivery).copy(anyString(), anyString(), any(), anyString(), anyString());
}
private void verifyStagedTimes(int times) {
verify(s3Service, times(times)).putObject(eq("stage"), anyString(), any(byte[].class), anyString(),
anyMap(), any());
}
@Test
void successfulCopyConsumesTheBatchOnce() throws Exception {
createStream("");
service.flush(STREAM);
service.flush(STREAM);
verify(delivery, times(1)).copy(eq("000000000000"), eq("us-east-1"), any(), eq("stage"), anyString());
verifyStagedTimes(1);
}
@Test
void failedCopyIsLoggedAndNotRestagedOrRebuffered() throws Exception {
createStream("");
copyFails();
service.flush(STREAM);
service.flush(STREAM);
verify(delivery, times(1)).copy(anyString(), anyString(), any(), eq("stage"), anyString());
verifyStagedTimes(1);
}
@Test
void deliveryUnavailableLeavesStagedObjectInS3() throws Exception {
FirehoseService serviceWithoutDelivery = new FirehoseService(storageFactory, s3Service,
new KinesisService(storageFactory, regionResolver), regionResolver, clock, config,
mock(FirehoseParquetConverter.class), mock(FirehoseLambdaTransformer.class), null, Runnable::run);
RedshiftDestination destination = mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "events"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}}
""", RedshiftDestination.class);
serviceWithoutDelivery.createDeliveryStream("us-east-1", "fh-no-delivery", null, destination, List.of(), null, null);
serviceWithoutDelivery.putRecord("fh-no-delivery", new Record("{\"id\":1}".getBytes(StandardCharsets.UTF_8)));
serviceWithoutDelivery.flush("fh-no-delivery");
verifyStagedTimes(1);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
}
@Test
void backupEnabledWritesTheBatchToTheBackupBucket() throws Exception {
createStream(BACKUP_ENABLED);
service.flush(STREAM);
verifyStagedTimes(1);
verify(s3Service, times(1)).putObject(eq("bk"), anyString(), any(byte[].class), anyString(), anyMap(), any());
verify(delivery, times(1)).copy(anyString(), anyString(), any(), eq("stage"), anyString());
}
@Test
void backupObjectUsesTheBackupConfigurationPrefix() throws Exception {
createStream(", \"S3BackupMode\": \"Enabled\", \"S3BackupConfiguration\": "
+ "{\"RoleARN\": \"arn:aws:iam::000000000000:role/firehose\", \"BucketARN\": \"arn:aws:s3:::bk\","
+ " \"Prefix\": \"backup/\"}");
service.flush(STREAM);
ArgumentCaptor<String> keys = ArgumentCaptor.forClass(String.class);
verify(s3Service).putObject(eq("bk"), keys.capture(), any(byte[].class), anyString(), anyMap(), any());
assertTrue(keys.getValue().startsWith("backup/"), keys.getValue());
}
@Test
void aFailingBackupWriteStillLoadsTheStagedBatchAndDoesNotRestageIt() throws Exception {
createStream(BACKUP_ENABLED);
doThrow(new IllegalStateException("backup bucket unavailable")).when(s3Service)
.putObject(eq("bk"), anyString(), any(byte[].class), anyString(), anyMap(), any());
service.flush(STREAM);
service.flush(STREAM);
verifyStagedTimes(1);
verify(delivery, times(1)).copy(anyString(), anyString(), any(), anyString(), anyString());
}
@Test
void aFailingPrimaryWriteWritesNoBackupSoNothingIsDelivered() throws Exception {
createStream(BACKUP_ENABLED);
doThrow(new IllegalStateException("s3 unavailable")).when(s3Service)
.putObject(eq("stage"), anyString(), any(byte[].class), anyString(), anyMap(), any());
service.flush(STREAM);
verify(s3Service, never()).putObject(eq("bk"), anyString(), any(byte[].class), anyString(), anyMap(), any());
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
}
@Test
void rejectedExecutionDoesNotRestoreRecordsToBuffer() throws Exception {
Executor rejectingExecutor = r -> {
throw new RejectedExecutionException("executor shut down");
};
FirehoseService rejectingService = new FirehoseService(storageFactory, s3Service,
new KinesisService(storageFactory, regionResolver), regionResolver, clock, config,
mock(FirehoseParquetConverter.class), mock(FirehoseLambdaTransformer.class), delivery, rejectingExecutor);
RedshiftDestination destination = mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "events"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}}
""", RedshiftDestination.class);
rejectingService.createDeliveryStream("us-east-1", "fh-rejected", null, destination, List.of(), null, null);
rejectingService.putRecord("fh-rejected", new Record("{\"id\":1}".getBytes(StandardCharsets.UTF_8)));
rejectingService.flush("fh-rejected");
rejectingService.flush("fh-rejected");
verify(s3Service, times(1)).putObject(eq("stage"), anyString(), any(byte[].class), anyString(),
anyMap(), any());
}
@Test
void onPreShutdownFlushesBuffersAndRunsCopyBeforeShuttingDown() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
FirehoseService shutdownService = new FirehoseService(storageFactory, s3Service,
new KinesisService(storageFactory, regionResolver), regionResolver, clock, config,
mock(FirehoseParquetConverter.class), mock(FirehoseLambdaTransformer.class), delivery, executor);
RedshiftDestination destination = mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "events"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}}
""", RedshiftDestination.class);
shutdownService.createDeliveryStream("us-east-1", "fh-shutdown", null, destination, List.of(), null, null);
shutdownService.putRecord("fh-shutdown", new Record("{\"id\":1}".getBytes(StandardCharsets.UTF_8)));
shutdownService.onPreShutdown(null);
verify(s3Service, times(1)).putObject(eq("stage"), anyString(), any(byte[].class), anyString(),
anyMap(), any());
verify(delivery, times(1)).copy(eq("000000000000"), eq("us-east-1"), any(), eq("stage"), anyString());
assertTrue(executor.isTerminated());
}
@Test
void onPreShutdownDropsQueuedTasksWhenTerminationTimesOut() throws Exception {
ExecutorService mockExecutor = mock(ExecutorService.class);
FirehoseService shutdownService = new FirehoseService(storageFactory, s3Service,
new KinesisService(storageFactory, regionResolver), regionResolver, clock, config,
mock(FirehoseParquetConverter.class), mock(FirehoseLambdaTransformer.class), delivery, mockExecutor);
RedshiftDestination destination = mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
"CopyCommand": {"DataTableName": "events"},
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}}
""", RedshiftDestination.class);
shutdownService.createDeliveryStream("us-east-1", "fh-timeout", null, destination, List.of(), null, null);
shutdownService.putRecord("fh-timeout", new Record("{\"id\":1}".getBytes(StandardCharsets.UTF_8)));
when(mockExecutor.awaitTermination(anyLong(), any())).thenReturn(false);
when(mockExecutor.shutdownNow()).thenReturn(List.of(() -> {}));
shutdownService.onPreShutdown(null);
InOrder inOrder = Mockito.inOrder(mockExecutor);
inOrder.verify(mockExecutor).execute(any());
inOrder.verify(mockExecutor).shutdown();
inOrder.verify(mockExecutor).awaitTermination(5, TimeUnit.SECONDS);
inOrder.verify(mockExecutor).shutdownNow();
}
}
@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
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;
class RedshiftCopySqlTest {
@@ -118,6 +119,50 @@ class RedshiftCopySqlTest {
assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $x"));
}
@Test
void buildsCopyWithOptionsAndNoIamRole() {
String sql = RedshiftCopySql.build("events", null, "stage", "2026/10/19/f.gz", "json 'auto' gzip");
assertEquals("COPY events FROM 's3://stage/2026/10/19/f.gz' json 'auto' gzip", sql);
}
@Test
void buildDropsTheClosingTerminatorOfTheApiReferenceExample() {
String sql = RedshiftCopySql.build("t", null, "b", "k", "delimiter '\\t' lzop;");
assertEquals("COPY t FROM 's3://b/k' delimiter '\\t' lzop", sql);
}
@Test
void buildKeepsATerminatorInsideAQuotedValue() {
String sql = RedshiftCopySql.build("t", null, "b", "k", "DELIMITER ';' CSV");
assertEquals("COPY t FROM 's3://b/k' DELIMITER ';' CSV", sql);
}
@Test
void tableAndColumnsAreKeptVerbatimSoRedshiftCaseFoldingApplies() {
String sql = RedshiftCopySql.build("Public.MyEvents", "Id, \"Full Name\"", "stage", "k", null);
assertEquals("COPY Public.MyEvents (Id, \"Full Name\") FROM 's3://stage/k'", sql);
}
@Test
void buildRejectsNamesAndOptionsThatCouldCarryAnotherStatement() {
assertThrows(IllegalArgumentException.class, () -> RedshiftCopySql.build("t; DROP TABLE x", null, "b", "k", null));
assertThrows(IllegalArgumentException.class,
() -> RedshiftCopySql.build("t", "id, name); DROP TABLE t; --", "b", "k", null));
assertThrows(IllegalArgumentException.class, () -> RedshiftCopySql.build("t", null, "b", "k", "gzip; DROP TABLE t"));
}
@Test
void objectKeyThatTheProxyCouldNotParseIsRejected() {
for (String key : new String[] {"my prefix/f.gz", "it's/f.gz", "say\"/f.gz"}) {
assertThrows(IllegalArgumentException.class,
() -> RedshiftCopySql.build("t", null, "stage", key, null), key);
}
}
@Test
void dollarQuotingAndCommentsAreRefused() {
assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $$'$$ gzip"));
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Duration;
import java.util.Objects;
public final class RedshiftConnections {
private RedshiftConnections() {}
public static String jdbcUrl(Cluster cluster) {
return "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev";
}
public static Connection waitForConnection(Cluster cluster) throws SQLException {
return waitForConnection(cluster, "admin", "Secret123");
}
public static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
return waitForConnection(jdbcUrl(cluster), username, password);
}
public static Connection waitForConnection(String host, int port, String username, String password) throws SQLException {
return waitForConnection("jdbc:postgresql://" + host + ":" + port + "/dev", username, password);
}
public static Connection waitForConnection(String jdbcUrl, String username, String password) throws SQLException {
try {
return Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollDelay(Duration.ZERO)
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.until(() -> DriverManager.getConnection(jdbcUrl, username, password), Objects::nonNull);
} catch (ConditionTimeoutException e) {
return DriverManager.getConnection(jdbcUrl, username, password);
}
}
}