feat(redshift): execute S3 auto-copy and COPY JOB RUN (#7898)

A job failure (SQLState 42xx or 0A000) cannot clear on its own, so re-marking the bucket made every sweep reconnect and log a WARN. The job now waits for the next upload. The predicate is shared with CopyJobRunner via S3TransferException.isJobFailure.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-11 12:49:20 -04:00
1 parent b954b4fb87
commit 4d4f20b812
25 files changed
+1572 -60

No files matched your search

@@ -0,0 +1,128 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.redshift.model.Integration;
import io.floci.aws.services.redshiftdata.RedshiftCopyJobExecutor;
import io.floci.aws.services.s3.model.S3ObjectUpdatedEvent;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
class RedshiftS3AutoCopyConsumerTest {
@Test
@Timeout(10)
void observingAnUploadDoesNotWaitForAnActiveCopy() throws Exception {
RedshiftService service = mock(RedshiftService.class);
RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class);
Integration integration = integration("active", "active");
when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(integration));
CountDownLatch copying = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
copying.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return null;
}).when(writer).runAutomatic(integration);
RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1);
CompletableFuture<Void> poll = CompletableFuture.runAsync(consumer::pollOnce);
try {
assertTrue(copying.await(5, TimeUnit.SECONDS));
consumer.updated(new S3ObjectUpdatedEvent("bucket", "key"));
} finally {
release.countDown();
poll.get(5, TimeUnit.SECONDS);
}
}
@Test
void processesActiveIntegrationsAndContinuesAfterAFailedTarget() {
RedshiftService service = mock(RedshiftService.class);
RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class);
Integration failed = integration("failed", "active");
Integration healthy = integration("healthy", "active");
Integration inactive = integration("inactive", "creating");
when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(failed, inactive, healthy));
doThrow(new IllegalStateException("Target unavailable")).when(writer).runAutomatic(failed);
RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1);
consumer.pollOnce();
verify(writer).runAutomatic(failed);
verify(writer).runAutomatic(healthy);
verify(writer, never()).runAutomatic(inactive);
consumer.beforeReset();
consumer.pollOnce();
verify(writer, times(1)).runAutomatic(healthy);
consumer.clear();
consumer.afterReset();
consumer.pollOnce();
verify(writer, times(2)).runAutomatic(healthy);
}
@Test
void deletionDisablesJobsWithoutDroppingTheirMetadata() {
RedshiftService service = mock(RedshiftService.class);
RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class);
RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1);
Integration integration = integration("deleted", "active");
consumer.disable(integration);
verify(writer).disable(integration);
verifyNoMoreInteractions(writer);
}
@Test
void timerSkipsIdleTicksAfterInitialReconciliationAndEventsTargetMatchingBucket() {
RedshiftService service = mock(RedshiftService.class);
RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class);
Integration first = integration("first", "active");
first.setSourceArn("arn:aws:s3:::bucket-a");
Integration second = integration("second", "active");
second.setSourceArn("arn:aws:s3:::bucket-b");
when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(first, second));
RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1);
consumer.pollOnce();
verify(writer, times(1)).runAutomatic(first);
verify(writer, times(1)).runAutomatic(second);
consumer.pollOnce();
verifyNoMoreInteractions(writer);
consumer.updated(new S3ObjectUpdatedEvent("bucket-a", "key"));
consumer.pollOnce();
verify(writer, times(2)).runAutomatic(first);
verify(writer, times(1)).runAutomatic(second);
}
@Test
void retriesMarkedBucketWithoutAnotherUploadAndStopsAfterSuccess() {
RedshiftService service = mock(RedshiftService.class);
RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class);
Integration retry = integration("retry", "active");
Integration healthy = integration("healthy", "active");
healthy.setSourceArn("arn:aws:s3:::other-bucket");
when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(retry, healthy));
when(writer.runAutomatic(retry)).thenReturn(true, false);
RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1);
consumer.pollOnce();
consumer.pollOnce();
consumer.pollOnce();
verify(writer, times(2)).runAutomatic(retry);
verify(writer).runAutomatic(healthy);
}
private static Integration integration(String name, String status) {
Integration integration = new Integration();
integration.setAccountId("123456789012");
integration.setIntegrationArn(AwsArnUtils.Arn.of("redshift", "us-east-1", "123456789012",
"integration:" + name).toString());
integration.setStatus(status);
integration.setSourceArn("arn:aws:s3:::bucket");
return integration;
}
}
@@ -0,0 +1,151 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.testing.DockerAvailability;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.s3.S3Client;
import java.net.URI;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class RedshiftS3AutoCopyIntegrationTest {
@Inject
RedshiftService service;
@Inject
IamService iam;
@Inject
RedshiftS3AutoCopyConsumer consumer;
@TestHTTPResource
URI endpoint;
@BeforeAll
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for Redshift auto-copy");
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void sdkUploadsAreLoadedOnceAndDeletionPreservesManualExecution(String mode) throws Exception {
String id = "auto-copy-" + UUID.randomUUID().toString().substring(0, 8);
String roleName = "AutoCopy" + UUID.randomUUID().toString().replace("-", "");
String role = iam.createRole(roleName, "/", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""", null, 0, null).getArn();
iam.putRolePolicy(roleName, "S3", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:GetObject","s3:ListBucket"],"Resource":"*"}]}
""");
Cluster cluster = service.createCluster(id, "dc2.large", "admin", "Secret123", null, List.of(), List.of(role));
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"));
try (S3Client s3 = S3Client.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).forcePathStyle(true).build();
RedshiftClient redshift = RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build();
Connection connection = RedshiftConnections.waitForConnection(RedshiftConnections.jdbcUrl(cluster)
+ "?preferQueryMode=" + mode, "admin", "Secret123");
Statement statement = connection.createStatement()) {
s3.createBucket(request -> request.bucket(id));
put(s3, id, "prefix/old", "99\n");
statement.execute("CREATE TABLE events (id integer)");
statement.execute("COPY events FROM 's3://" + id + "/prefix/' IAM_ROLE '" + role + "' JOB CREATE ingest");
String integration = redshift.createIntegration(request -> request.integrationName(id)
.sourceArn("arn:aws:s3:::" + id).targetArn("arn:aws:redshift:us-east-1:000000000000:cluster:" + id))
.integrationArn();
try {
put(s3, id, "elsewhere/ignored", "98\n");
put(s3, id, "prefix/first", "1\n");
consumer.pollOnce();
assertEquals(1, count(statement, "events"));
put(s3, id, "prefix/first", "2\n");
consumer.pollOnce();
consumer.clear();
consumer.pollOnce();
assertEquals(1, count(statement, "events"));
assertEquals(1, count(statement, "floci_internal.copy_job_detail"));
} finally {
redshift.deleteIntegration(request -> request.integrationArn(integration));
}
try (ResultSet job = statement.executeQuery("COPY JOB SHOW ingest")) {
assertTrue(job.next());
assertEquals(0, job.getInt("is_auto"));
}
put(s3, id, "prefix/second", "3\n");
consumer.pollOnce();
assertEquals(1, count(statement, "events"));
connection.setAutoCommit(false);
statement.execute("COPY JOB RUN ingest");
assertEquals(2, count(statement, "events"));
connection.rollback();
connection.setAutoCommit(true);
assertEquals(1, count(statement, "events"));
statement.execute("COPY JOB RUN ingest");
assertEquals(2, count(statement, "events"));
put(s3, id, "prefix/bad", "invalid\n");
put(s3, id, "prefix/good", "4\n");
statement.execute("COPY JOB RUN ingest");
assertEquals(3, count(statement, "events"));
assertEquals(4, count(statement, "floci_internal.copy_job_detail"));
assertEquals("E", fileStatus(statement, "prefix/bad"));
assertEquals("I", fileStatus(statement, "prefix/good"));
put(s3, id, "prefix/bad", "5\n");
statement.execute("COPY JOB RUN ingest");
assertEquals(4, count(statement, "events"));
assertEquals("I", fileStatus(statement, "prefix/bad"));
statement.execute("COPY JOB DROP ingest");
assertEquals(0, count(statement, "floci_internal.copy_job_detail"));
statement.execute("CREATE USER blocked_owner PASSWORD 'Secret123'");
statement.execute("SET SESSION AUTHORIZATION blocked_owner");
statement.execute("COPY public.events FROM 's3://" + id + "/protected/' IAM_ROLE '"
+ role + "' JOB CREATE blocked_job AUTO OFF");
statement.execute("RESET SESSION AUTHORIZATION");
put(s3, id, "protected/file", "6\n");
SQLException denied = assertThrows(SQLException.class, () -> statement.execute("COPY JOB RUN blocked_job"));
assertEquals("42501", denied.getSQLState());
assertEquals(4, count(statement, "events"));
assertEquals(0, count(statement, "floci_internal.copy_job_detail"));
} finally {
service.deleteCluster(id);
}
}
private static void put(S3Client client, String bucket, String key, String body) {
client.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(body));
}
private static long count(Statement statement, String table) throws SQLException {
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM " + table)) {
assertTrue(rows.next());
return rows.getLong(1);
}
}
private static String fileStatus(Statement statement, String fileName) throws SQLException {
try (ResultSet rows = statement.executeQuery(
"SELECT status FROM sys_copy_job_detail WHERE file_name = '" + fileName + "'")) {
assertTrue(rows.next());
return rows.getString(1).trim();
}
}
}
@@ -14,6 +14,9 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.CreateIntegrationResponse;
import software.amazon.awssdk.services.redshift.model.DeleteIntegrationResponse;
import software.amazon.awssdk.services.redshift.model.DescribeIntegrationsResponse;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import java.net.URI;
@@ -22,6 +25,7 @@ import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@@ -126,6 +130,22 @@ class RedshiftS3EventIntegrationTest {
assertEquals(400, error.statusCode());
assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode());
}
CreateIntegrationResponse createdIntegration = client.createIntegration(
request -> request.integrationName("s3-sdk-roundtrip")
.sourceArn("arn:aws:s3:::" + BUCKET).targetArn(namespaceArn));
assertNotNull(createdIntegration.integrationArn());
assertEquals("s3-sdk-roundtrip", createdIntegration.integrationName());
assertEquals("arn:aws:s3:::" + BUCKET, createdIntegration.sourceArn());
assertEquals(namespaceArn, createdIntegration.targetArn());
assertEquals("active", createdIntegration.statusAsString());
DescribeIntegrationsResponse described = client.describeIntegrations(
request -> request.integrationArn(createdIntegration.integrationArn()));
assertEquals(1, described.integrations().size());
assertEquals(createdIntegration.integrationArn(), described.integrations().getFirst().integrationArn());
DeleteIntegrationResponse deletedIntegration = client.deleteIntegration(
request -> request.integrationArn(createdIntegration.integrationArn()));
assertEquals(createdIntegration.integrationArn(), deletedIntegration.integrationArn());
assertEquals("s3-sdk-roundtrip", deletedIntegration.integrationName());
}
}
@@ -898,6 +898,7 @@ class RedshiftServiceTest {
private RedshiftServerlessService zeroEtlServerless;
private EmulatorConfig config;
private S3Service zeroEtlS3;
private RedshiftS3AutoCopyConsumer autoCopyConsumer;
private RedshiftService service;
@BeforeEach
@@ -971,10 +972,12 @@ class RedshiftServiceTest {
zeroEtlServerless = mock(RedshiftServerlessService.class);
zeroEtlS3 = mock(S3Service.class);
when(zeroEtlS3.ownsBucket(any())).thenReturn(true);
autoCopyConsumer = mock(RedshiftS3AutoCopyConsumer.class);
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, mapper,
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS), null, events, integrationEvents,
new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless, zeroEtlS3, regionResolver));
new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless, zeroEtlS3, regionResolver),
autoCopyConsumer);
}
private static final String ORDERS_TABLE_ARN = "arn:aws:dynamodb:us-east-1:111111111111:table/orders";
@@ -1322,6 +1325,25 @@ class RedshiftServiceTest {
verify(integrationEvents, never()).queue(any(), any(), any(), any());
}
@Test
void deletingAnS3IntegrationDisablesJobsBeforeRemovingItsMetadata() {
Integration stored = new Integration();
stored.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:s3-one");
stored.setSourceType("s3-event-notifications");
when(integrationBackend.keys()).thenReturn(Set.of("s3-one"));
when(integrationBackend.get("s3-one")).thenReturn(Optional.of(stored));
doThrow(new AwsException("InvalidClusterState", "Paused", 400)).when(autoCopyConsumer).disable(stored);
assertThrows(AwsException.class, () -> service.deleteIntegration(stored.getIntegrationArn()));
verify(integrationBackend, never()).delete(any());
clearInvocations(autoCopyConsumer, integrationBackend);
doNothing().when(autoCopyConsumer).disable(stored);
service.deleteIntegration(stored.getIntegrationArn());
InOrder order = inOrder(autoCopyConsumer, integrationBackend);
order.verify(autoCopyConsumer).disable(stored);
order.verify(integrationBackend).delete("s3-one");
}
@Test
void sourceTypesFilterMatchesTheSourceTypeOfAnS3EventIntegration() {
Integration stored = new Integration();
@@ -79,7 +79,7 @@ class CopyJobCatalogTest {
void truncateJobs() throws SQLException {
if (cluster != null) {
try (Connection connection = open(); Statement statement = connection.createStatement()) {
statement.execute("TRUNCATE floci_internal.copy_job");
statement.execute("TRUNCATE floci_internal.copy_job CASCADE");
}
}
}
@@ -145,6 +145,64 @@ class CopyJobCatalogTest {
}
}
@Test
void fileCheckpointsDeduplicateAndRetryOnlyChangedFailedFiles() throws SQLException {
try (Connection connection = open(); Statement statement = connection.createStatement()) {
statement.execute(CopyJobSql.rewrite(COPY + " JOB CREATE checkpoint_job", false));
long jobId;
try (ResultSet job = statement.executeQuery("SELECT job_id FROM floci_internal.copy_job WHERE job_name = 'checkpoint_job'")) {
assertTrue(job.next());
jobId = job.getLong(1);
}
try (PreparedStatement reserve = connection.prepareStatement(
"SELECT floci_internal.reserve_copy_job_file(?, ?, ?, NULL, 2, CURRENT_TIMESTAMP)");
PreparedStatement failure = connection.prepareStatement(
"SELECT floci_internal.record_copy_job_file_error(?, ?, ?, NULL, 2, CURRENT_TIMESTAMP)")) {
reserve.setLong(1, jobId);
reserve.setString(2, "loaded.csv");
reserve.setString(3, "v1");
assertReservation(reserve, true);
assertReservation(reserve, false);
failure.setLong(1, jobId);
failure.setString(2, "retry.csv");
failure.setString(3, "v1");
failure.execute();
failure.setString(3, "v2");
failure.execute();
assertCheckpoint(statement, "retry.csv", "E", "v2");
reserve.setString(2, "retry.csv");
reserve.setString(3, "v2");
assertReservation(reserve, false);
reserve.setString(3, "v3");
assertReservation(reserve, true);
assertReservation(reserve, false);
failure.setString(3, "v4");
failure.execute();
assertCheckpoint(statement, "retry.csv", "I", "v3");
assertCheckpoint(statement, "loaded.csv", "I", "v1");
}
}
}
private static void assertReservation(PreparedStatement statement, boolean expected) throws SQLException {
try (ResultSet result = statement.executeQuery()) {
assertTrue(result.next());
assertEquals(expected, result.getBoolean(1));
}
}
private static void assertCheckpoint(Statement statement, String key, String status, String etag) throws SQLException {
try (ResultSet checkpoint = statement.executeQuery(
"SELECT status, etag FROM floci_internal.copy_job_detail WHERE key = '" + key + "'")) {
assertTrue(checkpoint.next());
assertEquals(status, checkpoint.getString(1).trim());
assertEquals(etag, checkpoint.getString(2));
assertFalse(checkpoint.next());
}
}
@Test
void concurrentCreatesCannotExceedTheJobLimit() throws Exception {
try (Connection connection = open(); Statement statement = connection.createStatement()) {
@@ -0,0 +1,47 @@
package io.floci.aws.services.redshift.proxy;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CopyJobRunTest {
@Test
void recognizesOnlyAStandaloneRunWithAValidName() {
assertEquals("Mixed", CopyJobSql.runName("/* comment */ COPY JOB RUN \"Mixed\";"));
assertEquals("my_job", CopyJobSql.runName("copy job run MY_JOB"));
assertNull(CopyJobSql.runName("COPY JOB RUN j; SELECT 1"));
assertNull(CopyJobSql.runName("COPY JOB RUN"));
assertNull(CopyJobSql.runName("COPY JOB RUN j extra"));
assertNotNull(CopyStatementParser.parse("COPY JOB RUN j"));
}
@Test
void preservesOptionsAndUsesTheExactObjectKey() {
String copy = "COPY t FROM 's3://bucket/prefix/' IAM_ROLE 'role' CSV";
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(copy);
CopyStatementParser.S3CopyFrom object = CopyJobRunner.forObject(spec, "prefix/a'b.csv");
assertEquals("prefix/a'b.csv", object.keyOrPrefix());
assertEquals("role", object.iamRoleArn());
assertTrue(object.csv());
assertEquals("bucket", object.bucket());
}
@Test
void deletedObjectNeverFallsBackToALongerKeyWithTheSamePrefix() {
S3Service s3 = mock(S3Service.class);
S3Object longer = new S3Object("bucket", "prefix/abc", new byte[0], "text/plain");
when(s3.objectExists("bucket", "prefix/a")).thenReturn(false);
when(s3.listObjectsWithPrefixes("bucket", "prefix/a", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(longer), List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://bucket/prefix/a' CSV");
S3CopySimulator.CopyInput input = S3CopySimulator.prepareObjectCopy(spec, s3, null, null, List.of());
assertEquals(List.of("prefix/a"), input.keys());
verify(s3, never()).listObjectsWithPrefixes("bucket", "prefix/a", null, 1000, null, null);
}
}
@@ -0,0 +1,179 @@
package io.floci.aws.services.redshift.proxy;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.ByteArrayOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@Timeout(10)
class CopyJobRunnerTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/Load";
private static final String COPY = "COPY t FROM 's3://bucket/prefix/' IAM_ROLE '" + ROLE + "' CSV";
@Test
void missingOrHiddenJobFailsBeforeReadingS3() throws Exception {
S3Service s3 = mock(S3Service.class);
withBackend(new ByteArrayOutputStream(), new ArrayList<>(), sql -> List.of(), backend -> {
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> CopyJobRunner.load(backend, "missing", s3, null, ACCOUNT, List.of()));
assertEquals("42704", error.sqlState());
});
verifyNoInteractions(s3);
}
@Test
void skipsOldAndCheckpointedFilesAndLoadsOnlyTheUnseenObjectAcrossPagesAsItsOwner() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = jobIam();
S3Object old = object("prefix/old", 10);
S3Object seen = object("prefix/seen", 30);
S3Object fresh = object("prefix/a'b", 40);
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(old, seen), List.of(), true, "page2"));
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, "page2", null))
.thenReturn(new S3Service.ListObjectsResult(List.of(fresh), List.of(), false, null));
when(s3.objectExists("bucket", "prefix/a'b")).thenReturn(true);
when(s3.getObject("bucket", "prefix/a'b")).thenReturn(fresh);
ByteArrayOutputStream copied = new ByteArrayOutputStream();
List<String> statements = new ArrayList<>();
withBackend(copied, statements, sql -> jobRows(sql, List.of(List.of("prefix/seen"))),
backend -> assertEquals(1, runJob(backend, s3, iam)));
assertEquals("1\n", copied.toString(StandardCharsets.UTF_8));
assertEquals(1, statements.stream().filter(sql -> sql.contains("reserve_copy_job_file")).count());
assertTrue(statements.contains("SET LOCAL ROLE \"job_owner\""));
assertTrue(statements.contains("SET LOCAL ROLE \"admin\""));
}
@Test
void loadsMoreThanOneHundredFilesInOneRun() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = jobIam();
List<S3Object> files = IntStream.range(0, 101).mapToObj(index -> object("prefix/" + index, 30)).toList();
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(files.subList(0, 100), List.of(), true, "page2"));
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, "page2", null))
.thenReturn(new S3Service.ListObjectsResult(files.subList(100, 101), List.of(), false, null));
for (S3Object file : files) {
when(s3.getObject("bucket", file.getKey())).thenReturn(file);
}
ByteArrayOutputStream copied = new ByteArrayOutputStream();
withBackend(copied, new ArrayList<>(), sql -> jobRows(sql, List.of()),
backend -> assertEquals(101, runJob(backend, s3, iam)));
assertEquals("1\n".repeat(101), copied.toString(StandardCharsets.UTF_8));
}
@Test
void isolatesFailedOrOverwrittenObjectAndContinuesWithValidFiles() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = jobIam();
S3Object overwritten = object("prefix/a", 30);
overwritten.setETag("\"etag-listed\"");
S3Object replaced = object("prefix/a", 31);
replaced.setETag("\"etag-new\"");
S3Object versioned = object("prefix/b", 35);
versioned.setETag("\"etag-v1\"");
versioned.setVersionId("v1");
when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(overwritten, versioned), List.of(), false, null));
when(s3.getObject("bucket", "prefix/a")).thenReturn(replaced);
when(s3.getObject("bucket", "prefix/b", "v1")).thenReturn(versioned);
ByteArrayOutputStream copied = new ByteArrayOutputStream();
List<String> statements = new ArrayList<>();
withBackend(copied, statements, sql -> jobRows(sql, List.of()),
backend -> assertEquals(1, runJob(backend, s3, iam)));
assertEquals("1\n", copied.toString(StandardCharsets.UTF_8));
assertTrue(statements.stream().anyMatch(sql -> sql.startsWith("ROLLBACK TO SAVEPOINT floci_job_file_")));
assertTrue(statements.stream().anyMatch(sql -> sql.contains("record_copy_job_file_error")
&& sql.contains("'prefix/a'")));
verify(s3).getObject("bucket", "prefix/b", "v1");
}
private static long runJob(CopyBackendSession backend, S3Service s3, IamService iam) throws Exception {
backend.begin(false);
long count = CopyJobRunner.load(backend, "job", s3, iam, ACCOUNT, List.of(ROLE));
backend.finish(false);
return count;
}
private static IamService jobIam() {
IamService iam = mock(IamService.class);
IamRole role = new IamRole();
role.setArn(ROLE);
role.setAssumeRolePolicyDocument("""
{"Statement":[{"Effect":"Allow","Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""");
when(iam.findRole(ACCOUNT, "Load")).thenReturn(Optional.of(role));
return iam;
}
private static List<List<String>> jobRows(String sql, List<List<String>> checkpoints) {
if (sql.contains("copy_job_for_run")) {
return List.of(List.of("1", COPY, "bucket", "prefix/", "20", "job_owner"));
}
if (sql.equals("SELECT current_user")) {
return List.of(List.of("admin"));
}
if (sql.contains("copy_job_loaded_keys")) {
return checkpoints;
}
if (sql.contains("reserve_copy_job_file")) {
return List.of(List.of("t"));
}
if (sql.contains("record_copy_job_file_error")) {
return List.of(List.of(""));
}
return List.of();
}
@FunctionalInterface
private interface BackendAction {
void run(CopyBackendSession backend) throws Exception;
}
private static void withBackend(ByteArrayOutputStream copied, List<String> statements,
Function<String, List<List<String>>> rows, BackendAction action) throws Exception {
try (ServerSocket listener = new ServerSocket(0);
Socket socket = new Socket("localhost", listener.getLocalPort());
Socket server = listener.accept()) {
socket.setSoTimeout(3000);
socket.setTcpNoDelay(true);
server.setTcpNoDelay(true);
CompletableFuture<Void> response = CompletableFuture.runAsync(() -> {
try {
new FakeCopyBackend(server).serveUntilSync(copied, statements::add, rows);
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
CopyBackendSession backend = new CopyBackendSession(socket, frame -> { });
action.run(backend);
backend.synchronize();
response.get(5, TimeUnit.SECONDS);
}
}
private static S3Object object(String key, long modified) {
S3Object object = new S3Object("bucket", key, "1\n".getBytes(StandardCharsets.UTF_8), "text/plain");
object.setLastModified(Instant.ofEpochSecond(modified));
return object;
}
}
@@ -97,8 +97,8 @@ class CopyJobSqlTest {
}
@Test
void runIsRefusedUntilItIsSupported() {
assertThat(CopyJobSql.rewrite("COPY JOB RUN j", false), containsString("COPY JOB RUN is not supported"));
void runIsExecutedByTheS3Interceptor() {
assertThat(CopyJobSql.rewrite("COPY JOB RUN j", false), equalTo("COPY JOB RUN j"));
}
@Test
@@ -2,14 +2,19 @@ package io.floci.aws.services.redshift.proxy;
import io.floci.aws.core.common.PostgresWire;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/** Extended-query backend for COPY tests, including catalog discovery and transaction recovery. */
final class FakeCopyBackend {
private final Socket socket;
private Function<String, List<List<String>>> rows = sql -> List.of();
FakeCopyBackend(Socket socket) {
this.socket = socket;
@@ -23,6 +28,12 @@ final class FakeCopyBackend {
serve(OutputStream.nullOutputStream(), false, failCommit, observer);
}
void serveUntilSync(OutputStream copied, StatementObserver observer,
Function<String, List<List<String>>> rows) throws Exception {
this.rows = rows;
serve(copied, false, false, observer);
}
private void serve(OutputStream copied, boolean stopAfterLoad, boolean failCommit,
StatementObserver observer) throws Exception {
PostgresWireDecoder decoder = new PostgresWireDecoder(socket.getInputStream());
@@ -69,6 +80,9 @@ final class FakeCopyBackend {
} else if (sql.startsWith("COPY ")) {
PostgresWire.write(out, 'G', new byte[]{0, 0, 0});
} else {
for (List<String> row : rows.apply(sql)) {
PostgresWire.write(out, 'D', dataRow(row));
}
if (sql.startsWith("SELECT a.attname")) {
PostgresWire.write(out, 'D', new byte[]{0, 3}, PostgresWire.int32(2), new byte[]{'i', 'd'},
PostgresWire.int32(-1), PostgresWire.int32(2), new byte[]{'2', '3'});
@@ -117,4 +131,15 @@ final class FakeCopyBackend {
interface StatementObserver {
void executed(String sql) throws Exception;
}
private static byte[] dataRow(List<String> row) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()});
for (String value : row) {
byte[] field = value.getBytes(StandardCharsets.UTF_8);
bytes.write(PostgresWire.int32(field.length));
bytes.write(field);
}
return bytes.toByteArray();
}
}
@@ -1796,7 +1796,7 @@ class S3CopySimulatorTest {
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
@@ -1829,7 +1829,7 @@ class S3CopySimulatorTest {
"1| \n2||x\n".getBytes(StandardCharsets.UTF_8), "text/plain");
when(s3.getObject("wh", "p.txt")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
@@ -1845,7 +1845,7 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "p/b.txt")).thenReturn(new S3Object("wh", "p/b.txt",
"id|name\n2|b\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input =
new S3CopySimulator.CopyInput(spec, List.of("p/a.txt", "p/b.txt"), s3, null, null);
new S3CopySimulator.CopyInput(spec, List.of("p/a.txt", "p/b.txt"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
@@ -1866,7 +1866,7 @@ class S3CopySimulatorTest {
}
when(s3.getObject("wh", "p.gz")).thenReturn(new S3Object("wh", "p.gz", gz.toByteArray(), "application/gzip"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.gz"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.gz"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
@@ -1978,7 +1978,7 @@ class S3CopySimulatorTest {
false, false, false, transforms);
when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt",
"1|03/31/2003\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, null, null,
@@ -1996,7 +1996,7 @@ class S3CopySimulatorTest {
false, false, false, transforms);
when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt",
"1|\n|03/31/2003\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, null, null,
@@ -2014,7 +2014,7 @@ class S3CopySimulatorTest {
false, false, false, transforms);
when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt",
"1\n2|b|7\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, null, null, List.of(CopyRecordTransformer.ColumnKind.OTHER,
@@ -2029,7 +2029,7 @@ class S3CopySimulatorTest {
false, false, false, false, null, null, null, false, true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null);
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
@@ -2042,7 +2042,7 @@ class S3CopySimulatorTest {
false, false, false, false, null, CopyTemporalFormat.parse("MM/DD/YYYY", false), null, false);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null);
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
@@ -2055,7 +2055,7 @@ class S3CopySimulatorTest {
new CopyStatementParser.CopyTransforms(false, false, false, true, null);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null);
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
@@ -2070,7 +2070,7 @@ class S3CopySimulatorTest {
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1||x\n1||x\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null);
long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
@@ -2093,7 +2093,7 @@ class S3CopySimulatorTest {
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1\n2\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null);
long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
@@ -2124,7 +2124,7 @@ class S3CopySimulatorTest {
String inputData = "1\n".repeat(2000);
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", inputData.getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null);
List<CopyRecordTransformer.ColumnKind> kinds = new ArrayList<>();
for (int i = 0; i < 300; i++) {
@@ -2178,7 +2178,7 @@ class S3CopySimulatorTest {
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
@@ -2203,7 +2203,7 @@ class S3CopySimulatorTest {
S3Object dataObj = new S3Object("wh", "users.json.gz", gzippedOut.toByteArray(), "application/gzip");
when(s3.getObject("wh", "users.json.gz")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json.gz"), s3, null, null);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json.gz"), s3, null, null, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
@@ -0,0 +1,138 @@
package io.floci.aws.services.redshiftdata;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshift.model.Endpoint;
import io.floci.aws.services.redshift.model.Integration;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService.WorkgroupTarget;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class RedshiftCopyJobExecutorTest {
private final RedshiftService service = mock(RedshiftService.class);
private final RedshiftZeroEtlEndpoints endpoints = mock(RedshiftZeroEtlEndpoints.class);
private final RedshiftDataConnectionFactory connections = mock(RedshiftDataConnectionFactory.class);
private final RedshiftCopyJobExecutor executor = new RedshiftCopyJobExecutor(service, endpoints, connections);
@Test
void missingClusterOrNamespaceDoesNotPreventIntegrationDeletion() {
Integration cluster = integration("arn:aws:redshift:us-east-1:123456789012:cluster:target");
when(service.describeClustersForAccount("123456789012", "target"))
.thenThrow(new AwsException("ClusterNotFound", "Gone", 404));
assertFalse(executor.runAutomatic(cluster));
assertDoesNotThrow(() -> executor.disable(cluster));
Integration namespace = integration("arn:aws:redshift-serverless:us-east-1:123456789012:namespace/target");
doThrow(new AwsException("ResourceNotFoundException", "Gone", 404))
.when(endpoints).targetWorkgroup("123456789012", namespace.getTargetArn());
assertFalse(executor.runAutomatic(namespace));
assertDoesNotThrow(() -> executor.disable(namespace));
doThrow(new AwsException("ValidationException",
"Workgroup runtime is not available for Data API execution.", 400))
.when(endpoints).targetWorkgroup("123456789012", namespace.getTargetArn());
assertTrue(executor.runAutomatic(namespace));
assertDoesNotThrow(() -> executor.disable(namespace));
verifyNoInteractions(connections);
}
@Test
void pausedClusterSkipsLoadsAndRefusesDeletionWithoutLosingIntegrationState() {
Integration integration = integration("arn:aws:redshift:us-east-1:123456789012:cluster:target");
Cluster cluster = new Cluster();
cluster.setClusterStatus("paused");
when(service.describeClustersForAccount("123456789012", "target")).thenReturn(List.of(cluster));
assertTrue(executor.runAutomatic(integration));
AwsException error = assertThrows(AwsException.class, () -> executor.disable(integration));
assertEquals("InvalidClusterState", error.getErrorCode());
verifyNoInteractions(connections);
}
@Test
void serverlessCleanupUsesTheWorkgroupProxyAndMatchesOnlyTheSourceBucket() throws Exception {
Integration integration = integration("arn:aws:redshift-serverless:us-east-1:123456789012:namespace/target");
Endpoint endpoint = new Endpoint();
endpoint.setPort(15439);
WorkgroupTarget target = new WorkgroupTarget("workgroup-arn", "workgroup", "backend", 5432, "analytics",
"master", "password", "admin", List.of(), null, endpoint);
when(endpoints.targetWorkgroup("123456789012", integration.getTargetArn())).thenReturn(target);
Connection database = mock(Connection.class);
PreparedStatement update = mock(PreparedStatement.class);
openDatabase(database);
when(database.prepareStatement(anyString())).thenReturn(update);
executor.disable(integration);
verify(connections, times(2)).open(argThat(value -> value.host().equals("127.0.0.1")
&& value.port() == 15439 && value.database().equals("analytics")));
verify(update).setString(1, "source-bucket");
verify(update).executeUpdate();
verify(database).close();
}
@ParameterizedTest
@CsvSource({
"Connection lost, 08006, true",
"Target table is missing, 42P01, false"
})
void failedJobRollsBackAndRetryIsRequestedOnlyForTransientFailures(String message, String sqlState,
boolean retryExpected) throws Exception {
Integration integration = integration("arn:aws:redshift:us-east-1:123456789012:cluster:target");
Cluster cluster = new Cluster();
cluster.setClusterStatus("available");
cluster.setProxyPort(15439);
when(service.describeClustersForAccount("123456789012", "target")).thenReturn(List.of(cluster));
Connection database = mock(Connection.class);
openDatabase(database);
PreparedStatement findJobs = mock(PreparedStatement.class);
PreparedStatement lock = mock(PreparedStatement.class);
Statement run = mock(Statement.class);
ResultSet jobs = mock(ResultSet.class);
ResultSet locked = mock(ResultSet.class);
when(database.prepareStatement(startsWith("SELECT job_name"))).thenReturn(findJobs);
when(database.prepareStatement(contains("FOR UPDATE"))).thenReturn(lock);
when(database.createStatement()).thenReturn(run);
when(findJobs.executeQuery()).thenReturn(jobs);
when(jobs.next()).thenReturn(true, true, false);
when(jobs.getString(1)).thenReturn("failed", "healthy");
when(lock.executeQuery()).thenReturn(locked);
when(locked.next()).thenReturn(true);
when(run.execute("COPY JOB RUN \"failed\"")).thenThrow(new SQLException(message, sqlState));
assertEquals(retryExpected, executor.runAutomatic(integration));
verify(database).rollback();
verify(run).execute("COPY JOB RUN \"healthy\"");
verify(database).commit();
}
private void openDatabase(Connection database) throws SQLException {
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
ResultSet databases = mock(ResultSet.class);
when(connections.open(any())).thenReturn(connection, database);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery(anyString())).thenReturn(databases);
when(databases.next()).thenReturn(true, false);
when(databases.getString(1)).thenReturn("analytics");
}
private static Integration integration(String target) {
Integration integration = new Integration();
integration.setAccountId("123456789012");
integration.setTargetArn(target);
integration.setTargetClusterIdentifier("target");
integration.setSourceArn("arn:aws:s3:::source-bucket");
return integration;
}
}
@@ -48,6 +48,21 @@ class RedshiftDataResourceResolverTest {
return new RedshiftDataResourceResolver(redshift, secrets, mapper, broker, regionResolver, serverless);
}
@Test
void copyJobRunUsesTheProxyForSingleStatementsAndBatches() {
Cluster target = cluster();
target.setProxyPort(5439);
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(target));
ObjectNode request = mapper.createObjectNode().put("ClusterIdentifier", "wh")
.put("DbUser", "admin").put("Database", "dev").put("Sql", "COPY JOB RUN ingest");
RedshiftDataResourceResolver resolver = resolver(redshift, mock(SecretsManagerService.class));
assertEquals(5439, resolver.resolve(request, REGION).port());
request.remove("Sql");
request.putArray("Sqls").add("SELECT 1").add("COPY JOB RUN ingest");
assertEquals(5439, resolver.resolve(request, REGION).port());
}
@Test
void resolvesClusterIdentifierAndMasterDbUser() {
RedshiftService redshift = mock(RedshiftService.class);