feat(redshift): support Redshift UNLOAD to Parquet (#7548)

* feat(redshift): support UNLOAD to Parquet

* refactor(redshift): share internal S3 scratch plumbing

* fix(redshift): warn when UNLOAD staging cleanup fails
This commit is contained in:
Maxence Frenette authored and GitHub committed 2026-11-04 22:53:38 -04:00
1 parent 189521e5cc
commit f7cf6fef6e
27 files changed
+1252 -167

No files matched your search

+9 -1
View File
@@ -940,6 +940,14 @@ runs the `COPY` over a connection to the cluster proxy. See [Firehose](firehose.
backing PostgreSQL container and writes
the result to S3 as one or more objects under `<prefix>`.
- `PARQUET` (also `FORMAT [AS] PARQUET`) writes Snappy-compressed Parquet v1 files using
floci-duck. The default extension is `.parquet`; `EXTENSION` overrides it.
Cast unconstrained `numeric` expressions to `DECIMAL(p,s)` (`p <= 38`, `0 <= s <= p`).
Unsupported types return SQLSTATE `0A000`. `SUPER`, `INTERVAL`, `ROWGROUPSIZE`, and
`PARTITION BY` are not supported. `MAXFILESIZE` is approximate at row-group boundaries,
so files may be larger or smaller than the target.
Internal staging access is scoped to the transfer session; no extra staging-bucket IAM
permissions are required. Destination permissions are checked normally.
- Framing defaults to pipe-delimited text; `FORMAT CSV` (or `CSV`) switches to CSV
with a `,` default. `DELIMITER`, `HEADER`, `NULL AS`, and `ADDQUOTES` are honoured
(`ADDQUOTES` and `HEADER` force CSV framing on PostgreSQL 15).
@@ -995,7 +1003,7 @@ the result to S3 as one or more objects under `<prefix>`.
`FLOCI_SERVICES_S3_ENFORCE_AUTH` off, S3 policy checks are skipped. With it on, the role's
identity policy must allow the required S3 actions, and any bucket policy must not deny the
request. `IAM_ROLE default` uses the cluster's default role with the same permission checks.
- Any other option (`PARQUET`, `JSON`, `FIXEDWIDTH`, `MASTER_SYMMETRIC_KEY`, `MANIFEST VERBOSE`,
- Any other option (`JSON`, `FIXEDWIDTH`, `MASTER_SYMMETRIC_KEY`, `MANIFEST VERBOSE`,
`ZSTD`, `BZIP2`, `PARTITION`, and so on) is not intercepted; the
statement is forwarded and PostgreSQL reports its own error.
- Extended Query UNLOAD is supported when the complete statement is present in `Parse` and has no
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3ObjectActions;
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpServerRequest;
@@ -562,12 +563,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
callerArns.get().putPrincipalKeys(conditionContext);
}
// Floci Spectrum transfer writes internal materialization to its own scratch bucket under the minted
// role session key. Since AWS Spectrum has no S3 write, this transfer is internal and must not be
// evaluated against the role's policies, permissions boundary, or SCPs (which often enforce read-only
// on data lake buckets). Tying authorization ahead of role policies directly to the minted transfer key
// and scratch key ensures boundary/SCP checks apply only to the actual S3 source reads.
if (isSpectrumScratchTransfer(credentialScope, action, resources, akid, callerArns.orElse(null))) {
// Internal transfers bypass customer policies only for a registered session scope in a tagged bucket.
if (isScratchTransfer(ctx, credentialScope, action, resources, akid, callerArns.orElse(null))) {
return;
}
// A create that carries tags is checked with them where its own action takes them, as the tagging
@@ -722,14 +719,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
// presigned URLs add, is a DeleteObject.
private static final Set<String> NON_DELETE_OBJECT_SUBRESOURCES = Set.of("uploadId", "tagging", "annotation");
private static final Set<String> SPECTRUM_SCRATCH_ACTIONS =
Set.of("s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload");
private static final Pattern SPECTRUM_SCRATCH_OBJECT = Pattern.compile(
"arn:" + AwsArnUtils.PARTITION_REGEX + ":s3:::"
+ Pattern.quote(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)
+ "/spectrum-[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\\.csv");
private static final Set<String> GOVERNANCE_BYPASS_ACTIONS =
Set.of("s3:PutObjectRetention", "s3:DeleteObject", "s3:DeleteObjectVersion");
@@ -770,33 +759,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return "POST".equalsIgnoreCase(ctx.getMethod()) && namesUpload && !params.containsKey("uploads");
}
/**
* A write or delete of the scratch object in the Spectrum scratch bucket by the exact assumed-role
* session running that transfer. The transfer is Floci's own, so it is authorized ahead of the
* role's policies and permissions boundaries; any other action, bucket, key or session stays
* under normal policy evaluation.
*/
private boolean isSpectrumScratchTransfer(String credentialScope, String action,
List<String> resources, String akid,
CallerArns callerArns) {
private boolean isScratchTransfer(ContainerRequestContext ctx, String credentialScope, String action,
List<String> resources, String akid, CallerArns callerArns) {
if (!"s3".equals(credentialScope) || akid == null || callerArns == null
|| !CallerArns.TYPE_ASSUMED_ROLE.equals(callerArns.principalType())
|| !SPECTRUM_SCRATCH_ACTIONS.contains(action) || resources.isEmpty()) {
|| resources.isEmpty() || s3ServiceProvider == null || !s3ServiceProvider.isResolvable()) {
return false;
}
if (s3ServiceProvider != null && s3ServiceProvider.isResolvable()
&& !s3ServiceProvider.get().isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)) {
Optional<String> allowed = iamService.scratchResourceArn(akid);
if (allowed.isEmpty()) {
return false;
}
Optional<String> allowedScratchArn = iamService.spectrumScratchResourceArn(akid);
if (allowedScratchArn.isEmpty()) {
return false;
String prefix = "s3:ListBucket".equals(action) ? ctx.getUriInfo().getQueryParameters().getFirst("prefix") : null;
for (S3ScratchSpace space : S3ScratchSpace.values()) {
if (space.permits(action, allowed.get(), resources, prefix)
&& s3ServiceProvider.get().isScratchBucket(space.bucketName())) {
return true;
}
}
String expectedArn = allowedScratchArn.get();
if (!SPECTRUM_SCRATCH_OBJECT.matcher(expectedArn).matches()) {
return false;
}
return resources.stream().allMatch(expectedArn::equals);
return false;
}
/**
@@ -4835,28 +4835,21 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
session.getPresignedAction(), session.getPresignedResourceArn()));
}
/** Binds a Redshift Spectrum scratch object ARN to an active transfer role session. */
public void registerSpectrumScratchResource(String accessKeyId, String resourceArn) {
/** Binds, or clears with null, an internal S3 scratch scope for this transfer session. */
public void registerScratchResource(String accessKeyId, String resourceArn) {
currentSession(accessKeyId).ifPresent(session -> {
session.setSpectrumScratchResourceArn(resourceArn);
session.setScratchResourceArn(resourceArn);
String accountId = session.getOriginAccountId() != null ? session.getOriginAccountId() : "000000000000";
putSessionForAccount(accountId, accessKeyId, session);
});
}
/** Clears the Spectrum scratch object permission from the session when the transfer completes. */
public void clearSpectrumScratchResource(String accessKeyId) {
currentSession(accessKeyId).ifPresent(session -> {
session.setSpectrumScratchResourceArn(null);
String accountId = session.getOriginAccountId() != null ? session.getOriginAccountId() : "000000000000";
putSessionForAccount(accountId, accessKeyId, session);
});
public void clearScratchResource(String accessKeyId) {
registerScratchResource(accessKeyId, null);
}
/** The exact scratch object ARN permitted for this session, if it is a Spectrum transfer session. */
public Optional<String> spectrumScratchResourceArn(String accessKeyId) {
return currentSession(accessKeyId)
.map(SessionCredential::getSpectrumScratchResourceArn)
public Optional<String> scratchResourceArn(String accessKeyId) {
return currentSession(accessKeyId).map(SessionCredential::getScratchResourceArn)
.filter(arn -> arn != null && !arn.isBlank());
}
@@ -34,8 +34,8 @@ public class SessionCredential {
/** Exact object action and ARN for an internally generated S3 presigned URL. */
private String presignedAction;
private String presignedResourceArn;
/** Exact scratch object ARN permitted for an internal Redshift Spectrum transfer session. */
private String spectrumScratchResourceArn;
/** Exact object ARN or UUID-scoped prefix permitted for an internal S3 transfer. */
private String scratchResourceArn;
/**
* The long-term identity whose key minted this session through GetSessionToken or
* GetFederationToken: an IAM user's ARN, or the account root's. Null for every other session.
@@ -141,9 +141,9 @@ public class SessionCredential {
public String getPresignedResourceArn() { return presignedResourceArn; }
public void setPresignedResourceArn(String presignedResourceArn) { this.presignedResourceArn = presignedResourceArn; }
public String getSpectrumScratchResourceArn() { return spectrumScratchResourceArn; }
public void setSpectrumScratchResourceArn(String spectrumScratchResourceArn) {
this.spectrumScratchResourceArn = spectrumScratchResourceArn;
public String getScratchResourceArn() { return scratchResourceArn; }
public void setScratchResourceArn(String scratchResourceArn) {
this.scratchResourceArn = scratchResourceArn;
}
public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }
@@ -270,6 +270,15 @@ final class BackendResponseCoordinator {
}
}
boolean isFirstPending(Ticket ticket) {
lock.lock();
try {
return !pending.isEmpty() && pending.getFirst().ticket().equals(ticket);
} finally {
lock.unlock();
}
}
private boolean canOwnExtendedExecute(Ticket ticket) {
for (PendingOperation operation : pending) {
if (operation.ticket().equals(ticket)) {
@@ -228,7 +228,8 @@ public final class CopyStatementParser {
boolean cleanPath,
boolean encrypted,
String sseKmsKeyId,
boolean defaultIamRoleRequested) implements S3Statement {
boolean defaultIamRoleRequested,
boolean parquet) implements S3Statement {
public S3Unload(
String selectQuery,
@@ -252,7 +253,7 @@ public final class CopyStatementParser {
String sseKmsKeyId) {
this(selectQuery, bucket, prefix, delimiter, header, gzip, csv, addQuotes, nullAs, manifest,
allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension,
escape, cleanPath, encrypted, sseKmsKeyId, false);
escape, cleanPath, encrypted, sseKmsKeyId, false, false);
}
public S3Unload(
@@ -304,6 +305,9 @@ public final class CopyStatementParser {
"(?is)^\\s*UNLOAD\\s*\\(\\s*'(.*)'\\s*\\)\\s*TO\\s*"
+ "['\"]s3://([^/'\"\\s]+)(?:/([^'\"\\s]*))?['\"]\\s*(.*)$");
private static final Pattern PARQUET_PATTERN = Pattern.compile(
"(?i)(?:FORMAT\\s+(?:AS\\s+)?)?PARQUET\\b");
private static final Pattern PARALLEL_PATTERN = Pattern.compile(
"(?i)\\bPARALLEL\\b(?:\\s+(ON|OFF|TRUE|FALSE))?");
private static final Pattern MAXFILESIZE_PATTERN = Pattern.compile(
@@ -325,7 +329,7 @@ public final class CopyStatementParser {
* UNLOAD-supported here, while PARTITION is UNLOAD-only and unsupported.
*/
private static final Pattern UNLOAD_UNSUPPORTED_CLAUSE = Pattern.compile(
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD"
"(?i)\\b(FIXEDWIDTH|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD"
+ "|ENCODING|MASTER_SYMMETRIC_KEY"
+ "|PARTITION|MAXFILESIZE\\s+\\d+\\s*(?:TB|PB))\\b");
@@ -437,6 +441,7 @@ public final class CopyStatementParser {
options = options.substring(0, semi);
}
boolean parquet = false;
boolean csv = false;
boolean gzip = false;
boolean header = false;
@@ -470,6 +475,7 @@ public final class CopyStatementParser {
boolean seenDelimiter = false;
boolean seenMaxFileSize = false;
Matcher parquetM = PARQUET_PATTERN.matcher(options);
Matcher csvM = CSV_PATTERN.matcher(options);
Matcher gzipM = GZIP_PATTERN.matcher(options);
Matcher headerM = HEADER_PATTERN.matcher(options);
@@ -497,7 +503,13 @@ public final class CopyStatementParser {
if (offset >= len) {
break;
}
if (matchClause(extensionM, offset, len)) {
if (matchClause(parquetM, offset, len)) {
if (parquet) {
return null;
}
parquet = true;
offset = parquetM.end();
} else if (matchClause(extensionM, offset, len)) {
if (seenExtension) {
return null;
}
@@ -626,6 +638,9 @@ public final class CopyStatementParser {
return null;
}
String iamRoleArn = auth.iamRoleArn();
if (parquet && (csv || gzip || header || addQuotes || escape || seenDelimiter || seenNull)) {
return null;
}
if (delimiter == null) {
delimiter = csv ? "," : "|";
}
@@ -646,7 +661,7 @@ public final class CopyStatementParser {
}
return new S3Unload(select, bucket, prefix, delimiter, header, gzip, csv,
addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension,
escape, cleanPath, encrypted, kmsKeyId, auth.defaultIamRoleRequested);
escape, cleanPath, encrypted, kmsKeyId, auth.defaultIamRoleRequested, parquet);
}
private static S3CopyFrom parseCopy(String cleaned, String defaultIamRoleArn) {
@@ -20,14 +20,14 @@ final class ExtendedS3Exchange {
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket) throws IOException {
execute(client, backend, executeFrame, statement, s3Service, iamService, null, List.of(), coordinator, ticket);
execute(client, backend, executeFrame, statement, s3Service, iamService, null, List.of(), coordinator, ticket, null);
}
static void execute(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
BackendResponseCoordinator.Ticket ticket) throws IOException {
BackendResponseCoordinator.Ticket ticket, RedshiftParquetWriter parquetWriter) throws IOException {
BackendResponseCoordinator.GateResult gate;
try {
gate = coordinator.awaitExtendedExecuteTurn(ticket);
@@ -51,7 +51,7 @@ final class ExtendedS3Exchange {
}
case CopyStatementParser.S3Unload unload -> {
CopyResult result = runUnload(client, backend, executeFrame, unload, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator);
clusterAccountId, iamRoleArns, coordinator, ticket, parquetWriter);
failed = !result.succeeded();
deferredReadyForQuery = result.deferredReadyForQuery();
}
@@ -122,8 +122,35 @@ final class ExtendedS3Exchange {
private static CopyResult runUnload(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Unload spec, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator) throws IOException {
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
BackendResponseCoordinator.Ticket ticket, RedshiftParquetWriter parquetWriter) throws IOException {
OutputStream backendOut = backend.getOutputStream();
List<RedshiftParquetWriter.Column> columns = List.of();
if (spec.parquet()) {
backendOut.write(new byte[]{'H', 0, 0, 0, 4});
backendOut.flush();
PostgresWireDecoder preamble = new PostgresWireDecoder(backend.getInputStream());
while (!coordinator.isFirstPending(ticket)) {
PostgresWireDecoder.FrontendMessage message = preamble.nextMessage();
if (message == null) {
throw new IOException("Backend closed before Parquet UNLOAD description");
}
coordinator.onBackendFrame(message.type(), message.body());
forward(client, message);
if (message.type() == 'E') {
forwardClientSyncToBackend(client, backendOut, coordinator);
return new CopyResult(false, drainReadyForQuery(client, preamble, coordinator));
}
}
RedshiftParquetWriter.Description description = RedshiftParquetWriter.describe(client, backend, spec.selectQuery());
if (description.error() != null) {
forward(client, description.error());
forwardClientSyncToBackend(client, backendOut, coordinator);
return new CopyResult(false, drainReadyForQuery(client,
new PostgresWireDecoder(backend.getInputStream()), coordinator));
}
columns = description.columns();
}
backendOut.write(executeFrame.toPacketBytes());
backendOut.flush();
forwardClientSyncToBackend(client, backendOut, coordinator);
@@ -140,7 +167,8 @@ final class ExtendedS3Exchange {
S3CopySimulator.UnloadCollector collector;
try {
collector = S3CopySimulator.prepareUnload(spec, s3Service, iamService, clusterAccountId, iamRoleArns);
collector = S3CopySimulator.prepareUnload(spec, s3Service, iamService, clusterAccountId, iamRoleArns, parquetWriter);
collector.columns(columns);
} catch (S3CopySimulator.S3TransferException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
drainExecute(client, decoder, coordinator, false);
@@ -40,6 +40,7 @@ public class RedshiftAuthProxy {
private final RdsProxyTlsCertificates tlsCertificates;
private final PasswordValidator passwordValidator;
private final S3Service s3Service;
private final RedshiftParquetWriter parquetWriter;
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final RedshiftAuditLogPublisher auditLogPublisher;
@@ -97,7 +98,7 @@ public class RedshiftAuthProxy {
int maxConnections, SpectrumInterceptor spectrumInterceptor) {
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, s3Service, iamService, clusterAccountId, iamRoleArns,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, spectrumInterceptor, null);
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, spectrumInterceptor, null, null);
}
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
@@ -109,7 +110,7 @@ public class RedshiftAuthProxy {
List<String> iamRoleArns,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher) {
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter) {
this.clusterKey = clusterKey;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -120,6 +121,7 @@ public class RedshiftAuthProxy {
this.tlsCertificates = tlsCertificates;
this.passwordValidator = passwordValidator;
this.s3Service = s3Service;
this.parquetWriter = parquetWriter;
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.auditLogPublisher = auditLogPublisher;
@@ -276,7 +278,7 @@ public class RedshiftAuthProxy {
RoleConfiguration roles = roleConfiguration;
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, roles.iamRoleArns(), spectrumInterceptor, clusterKey, login.database,
roles.defaultIamRoleArn(), auditLogPublisher, login.username).run();
roles.defaultIamRoleArn(), auditLogPublisher, login.username, parquetWriter).run();
publishConnection(client, login, "disconnection");
} else {
publishConnection(client, login, login.backendUnavailable ? "connection_error" : "authentication failure");
@@ -64,6 +64,7 @@ public class RedshiftInterceptingBridge {
private final Socket client;
private final Socket backend;
private final S3Service s3Service;
private final RedshiftParquetWriter parquetWriter;
private final IamService iamService;
private final String clusterAccountId;
private final List<String> iamRoleArns;
@@ -118,7 +119,7 @@ public class RedshiftInterceptingBridge {
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
clusterKey, databaseName, defaultIamRoleArn, null, null);
clusterKey, databaseName, defaultIamRoleArn, null, null, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
@@ -126,17 +127,17 @@ public class RedshiftInterceptingBridge {
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, null);
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, null, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns,
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher,
String databaseUser) {
String databaseUser, RedshiftParquetWriter parquetWriter) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, databaseUser, new ReentrantLock(true),
PUMP_PARK_WAIT_MS);
PUMP_PARK_WAIT_MS, parquetWriter);
}
/**
@@ -145,7 +146,7 @@ public class RedshiftInterceptingBridge {
*/
RedshiftInterceptingBridge(Socket client, Socket backend, ReentrantLock backendLock, long ownershipWaitMillis) {
this(client, backend, null, null, null, List.of(), null, null, null, null, null, null, backendLock,
ownershipWaitMillis);
ownershipWaitMillis, null);
}
private RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
@@ -153,8 +154,9 @@ public class RedshiftInterceptingBridge {
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher,
String databaseUser, ReentrantLock backendLock,
long ownershipWaitMillis) {
long ownershipWaitMillis, RedshiftParquetWriter parquetWriter) {
this.client = client;
this.parquetWriter = parquetWriter;
this.backend = backend;
this.s3Service = s3Service;
this.iamService = iamService;
@@ -306,7 +308,7 @@ public class RedshiftInterceptingBridge {
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
case CopyStatementParser.S3Unload unload -> S3CopySimulator.runUnload(
client, backend, unload, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), parquetWriter);
});
if (intercepted) {
return;
@@ -686,7 +688,7 @@ public class RedshiftInterceptingBridge {
try {
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
ExtendedS3Exchange.execute(client, backend, executeFrame, statement, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator, ticket);
clusterAccountId, iamRoleArns, coordinator, ticket, parquetWriter);
} finally {
try {
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
@@ -0,0 +1,255 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
import io.github.hectorvent.floci.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** Converts PostgreSQL CSV slices using the query's declared types, never data inference. */
@ApplicationScoped
public class RedshiftParquetWriter {
private static final Logger LOG = Logger.getLogger(RedshiftParquetWriter.class);
static final String STAGING_BUCKET = S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET;
private final FlociDuckClient duck;
private final S3Service s3;
private final IamService iam;
private final String region;
public RedshiftParquetWriter(FlociDuckClient duck, S3Service s3, IamService iam, EmulatorConfig config) {
this.duck = duck;
this.s3 = s3;
this.iam = iam;
region = config.defaultRegion();
}
record Column(String name, String type) { }
record Description(List<Column> columns, PostgresWireDecoder.FrontendMessage error) { }
/** Named Parse/Describe/Close leaves the client's portals and transaction intact. */
static Description describe(Socket client, Socket backend, String query) throws IOException {
String name = "floci_unload_" + UUID.randomUUID().toString().replace("-", "");
backend.getOutputStream().write(PostgresWireDecoder.encodeParse(
new PostgresWireDecoder.ParseMessage(name, query, List.of()), query));
backend.getOutputStream().write(PostgresWire.frame('D', PostgresWire.cStringBytes("S" + name)));
backend.getOutputStream().write(PostgresWire.frame('C', PostgresWire.cStringBytes("S" + name)));
backend.getOutputStream().write(PostgresWire.frame('H', new byte[0]));
backend.getOutputStream().flush();
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
byte[] rowDescription = null;
S3CopySimulator.S3TransferException rejectedType = null;
PostgresWireDecoder.FrontendMessage message;
while ((message = decoder.nextMessage()) != null) {
if (message.type() == 'N' || message.type() == 'A' || message.type() == 'S') {
client.getOutputStream().write(message.toPacketBytes());
client.getOutputStream().flush();
} else if (message.type() == 'T') {
rowDescription = message.body();
} else if (message.type() == 'E') {
return new Description(List.of(), rejectedType == null ? message
: new PostgresWireDecoder.FrontendMessage('E',
S3CopySimulator.errorBody(rejectedType.sqlState(), rejectedType.getMessage())));
} else if (message.type() == '3') {
try {
return new Description(rowDescription == null ? List.of() : columns(rowDescription), null);
} catch (S3CopySimulator.S3TransferException exception) {
rejectedType = exception;
// Fail the backend cycle so normal Sync recovery also handles local type errors.
String abortSql = "(FLOCI_ABORT_TX)";
backend.getOutputStream().write(PostgresWireDecoder.encodeParse(
new PostgresWireDecoder.ParseMessage(name, abortSql, List.of()), abortSql));
backend.getOutputStream().write(PostgresWire.frame('H', new byte[0]));
backend.getOutputStream().flush();
}
}
}
throw new IOException("Backend closed while describing UNLOAD query");
}
static List<Column> columns(byte[] description) throws IOException {
DataInputStream input = new DataInputStream(new ByteArrayInputStream(description));
int count = input.readUnsignedShort();
List<Column> columns = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
ByteArrayOutputStream name = new ByteArrayOutputStream();
int character;
while ((character = input.readUnsignedByte()) != 0) {
name.write(character);
}
input.readInt(); // table OID
input.readShort(); // attribute number
int oid = input.readInt();
input.readShort(); // type size
int modifier = input.readInt();
input.readShort(); // format code
String columnName = name.toString(StandardCharsets.UTF_8);
columns.add(new Column(columnName, type(columnName, oid, modifier)));
}
return columns;
}
static String type(String column, int oid, int modifier) {
return switch (oid) {
case 16 -> "BOOLEAN";
case 21 -> "SMALLINT";
case 23 -> "INTEGER";
case 20 -> "BIGINT";
case 700 -> "FLOAT";
case 701 -> "DOUBLE";
case 1082 -> "DATE";
case 1114 -> "TIMESTAMP";
case 1184 -> "TIMESTAMPTZ";
case 1700 -> {
if (modifier < 4) {
throw unsupported(column, "NUMERIC without declared precision and scale",
"Cast it to DECIMAL(p,s), with 1 <= p <= 38 and 0 <= s <= p.");
}
int precision = (modifier - 4) >> 16;
int scale = ((modifier - 4) & 0x7ff) ^ 0x400;
scale -= 0x400;
if (precision < 1 || precision > 38 || scale < 0 || scale > precision) {
throw unsupported(column, "NUMERIC(" + precision + "," + scale + ")",
"Cast it to DECIMAL(p,s), with 1 <= p <= 38 and 0 <= s <= p.");
}
yield "DECIMAL(" + precision + "," + scale + ")";
}
case 25, 1042, 1043 -> "VARCHAR";
default -> {
String typeName = switch (oid) {
case 17 -> "BYTEA";
case 114 -> "JSON";
case 1083 -> "TIME";
case 1186 -> "INTERVAL";
case 1266 -> "TIMETZ";
case 2950 -> "UUID";
case 3802 -> "JSONB";
default -> "PostgreSQL type";
};
throw unsupported(column, typeName + " (OID " + oid + ")",
"Cast it explicitly to a supported scalar type, such as VARCHAR.");
}
};
}
private static S3CopySimulator.S3TransferException unsupported(String column, String type, String hint) {
return new S3CopySimulator.S3TransferException("0A000",
"UNLOAD PARQUET does not support column \"" + column.replace("\"", "\"\"")
+ "\" of type " + type + ". " + hint, null);
}
List<byte[]> convert(byte[] csv, List<Column> columns, String accountId,
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
try {
return RequestScopes.callAsChecked(accountId,
() -> convertScoped(csv, columns, accountId, session, maxFileSizeBytes));
} catch (RuntimeException | IOException exception) {
throw exception;
} catch (Exception exception) {
throw new IOException("Unable to convert UNLOAD slice", exception);
}
}
private List<byte[]> convertScoped(byte[] csv, List<Column> columns, String accountId,
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
if (columns.isEmpty()) {
throw new IOException("UNLOAD query has no Parquet columns");
}
S3ScratchSpace.UNLOAD.ensureBucket(s3, region);
String root = "unload/" + UUID.randomUUID() + "/";
String inputKey = root + "input.csv";
String outputKey = root + "output.parquet";
try {
if (session != null) {
iam.registerScratchResource(session.accessKeyId(), AwsArnUtils.Arn.global(
AwsRegions.partitionFor(region), "s3", "", STAGING_BUCKET + "/" + root).toString());
}
s3.putObject(STAGING_BUCKET, inputKey, csv, "text/csv", null);
StringBuilder schema = new StringBuilder();
StringBuilder projection = new StringBuilder();
for (int i = 0; i < columns.size(); i++) {
if (i > 0) {
schema.append(", ");
projection.append(", ");
}
Column column = columns.get(i);
schema.append("'c").append(i).append("': '").append(column.type()).append("'");
String expression = "c" + i;
if ("TIMESTAMPTZ".equals(column.type())) {
expression = "CAST(" + expression + " AS TIMESTAMP)";
}
projection.append(expression).append(" AS \"")
.append(column.name().replace("\"", "\"\"")).append("\"");
}
String source = csv.length == 0
? emptyQuery(columns)
: "SELECT " + projection + " FROM read_csv('" + literal("s3://" + STAGING_BUCKET + "/" + inputKey)
+ "', header = false, delim = ',', quote = '\"', escape = '\"', nullstr = '', "
+ "allow_quoted_nulls = false, auto_detect = false, columns = {"
+ schema + "})";
String sql = "COPY (" + source + ") TO '"
+ literal("s3://" + STAGING_BUCKET + "/" + outputKey)
+ "' (FORMAT PARQUET, COMPRESSION SNAPPY, PARQUET_VERSION V1, FILE_SIZE_BYTES "
+ maxFileSizeBytes + ", RETURN_STATS true)";
String setup = "SET TimeZone = 'UTC'; SET threads = 1;";
List<Map<String, Object>> files = session == null
? duck.query(sql, setup, accountId)
: duck.query(sql, setup, session.accessKeyId(), session.secretAccessKey(), session.sessionToken());
if (files.isEmpty()) {
throw new IOException("DuckDB returned no Parquet output files");
}
List<byte[]> result = new ArrayList<>();
for (Map<String, Object> file : files) {
String key = file.get("filename").toString().substring(("s3://" + STAGING_BUCKET + "/").length());
try (InputStream input = s3.openObjectStream(STAGING_BUCKET, key, null)) {
result.add(input.readAllBytes());
}
}
return result;
} finally {
if (session != null) {
iam.clearScratchResource(session.accessKeyId());
}
try {
s3.deleteObjectsWithPrefix(STAGING_BUCKET, root, ignored -> {
// Internal staging cleanup does not use the external role.
});
} catch (RuntimeException exception) {
LOG.warnv(exception, "Could not remove UNLOAD staging prefix {0}", root);
}
}
}
private static String emptyQuery(List<Column> columns) {
List<String> expressions = new ArrayList<>();
for (Column column : columns) {
String type = "TIMESTAMPTZ".equals(column.type()) ? "TIMESTAMP" : column.type();
expressions.add("CAST(NULL AS " + type + ") AS \""
+ column.name().replace("\"", "\"\"") + "\"");
}
return "SELECT " + String.join(", ", expressions) + " WHERE false";
}
private static String literal(String value) {
return value.replace("'", "''");
}
}
@@ -35,6 +35,7 @@ public class RedshiftProxyManager {
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final EmulatorConfig config;
private final RedshiftParquetWriter parquetWriter;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
/**
@@ -53,20 +54,21 @@ public class RedshiftProxyManager {
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor) {
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor, null);
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor, null, null);
}
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher) {
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter) {
this.sigV4Validator = sigV4Validator;
this.tlsCertificates = tlsCertificates;
this.s3Service = s3Service;
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.config = config;
this.parquetWriter = parquetWriter;
this.auditLogPublisher = auditLogPublisher;
}
@@ -105,7 +107,7 @@ public class RedshiftProxyManager {
clusterAccountId,
iamRoleArns,
redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(),
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher);
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher, parquetWriter);
proxy.updateIamRoles(iamRoleArns, defaultIamRoleArn);
try {
proxy.start(proxyPort);
@@ -86,6 +86,8 @@ public final class S3CopySimulator {
interface UnloadCollector extends AutoCloseable {
void accept(byte[] body) throws IOException;
void columns(List<RedshiftParquetWriter.Column> columns);
void complete() throws IOException;
void abort();
@@ -284,11 +286,12 @@ public final class S3CopySimulator {
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
String clusterAccountId) {
return prepareUnload(spec, s3, iamService, clusterAccountId, null);
return prepareUnload(spec, s3, iamService, clusterAccountId, null, null);
}
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
String clusterAccountId, List<String> associatedRoleArns,
RedshiftParquetWriter parquetWriter) {
requireDefaultIamRole(spec);
RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null
? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
@@ -348,7 +351,7 @@ public final class S3CopySimulator {
"UNLOAD memory budget exhausted; retry shortly", null);
}
try {
return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath);
return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath, parquetWriter, clusterAccountId);
} catch (IOException e) {
UNLOAD_HEAP_MIB.release(UNLOAD_INITIAL_MIB);
RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
@@ -1037,15 +1040,16 @@ public final class S3CopySimulator {
public static boolean runUnload(Socket client, Socket backend,
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId,
char txStatus, IntConsumer onStatusChange) throws IOException {
return runUnload(client, backend, spec, s3, iamService, clusterAccountId, null, txStatus, onStatusChange);
return runUnload(client, backend, spec, s3, iamService, clusterAccountId, null, txStatus, onStatusChange, null);
}
public static boolean runUnload(Socket client, Socket backend,
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId,
List<String> associatedRoleArns, char txStatus, IntConsumer onStatusChange) throws IOException {
List<String> associatedRoleArns, char txStatus, IntConsumer onStatusChange,
RedshiftParquetWriter parquetWriter) throws IOException {
UnloadCollector collector;
try {
collector = prepareUnload(spec, s3, iamService, clusterAccountId, associatedRoleArns);
collector = prepareUnload(spec, s3, iamService, clusterAccountId, associatedRoleArns, parquetWriter);
} catch (S3TransferException e) {
LOG.debugv(e, "UNLOAD preparation failed for s3://{0}/{1}", spec.bucket(), spec.prefix());
sendError(client, backend, e.sqlState(), e.getMessage(), txStatus, onStatusChange);
@@ -1053,6 +1057,17 @@ public final class S3CopySimulator {
}
try (collector) {
if (spec.parquet()) {
RedshiftParquetWriter.Description description = RedshiftParquetWriter.describe(client, backend, spec.selectQuery());
if (description.error() != null) {
forward(client, description.error());
backend.getOutputStream().write(new byte[]{'S', 0, 0, 0, 4});
backend.getOutputStream().flush();
drainToReadyForQuery(new PostgresWireDecoder(backend.getInputStream()), client, onStatusChange);
return true;
}
collector.columns(description.columns());
}
return runUnloadStreaming(client, backend, spec, collector, txStatus, onStatusChange);
}
}
@@ -1242,6 +1257,9 @@ public final class S3CopySimulator {
}
private static String fabricateUnloadCopy(CopyStatementParser.S3Unload spec) {
if (spec.parquet()) {
return "COPY (" + spec.selectQuery() + ") TO STDOUT WITH (FORMAT csv, DELIMITER ',')";
}
boolean csvFraming = spec.csv() || spec.addQuotes() || spec.header();
StringBuilder sql = new StringBuilder("COPY (").append(spec.selectQuery())
.append(") TO STDOUT WITH (FORMAT ").append(csvFraming ? "csv" : "text");
@@ -1262,6 +1280,10 @@ public final class S3CopySimulator {
private static final class S3UnloadCollector implements UnloadCollector {
private final CopyStatementParser.S3Unload spec;
private final RedshiftParquetWriter parquetWriter;
private final String accountId;
private List<RedshiftParquetWriter.Column> columns = List.of();
private boolean quotedCsv;
private final S3Service s3;
private final IamService iamService;
private final RedshiftRoleAccess.RoleSession roleSession;
@@ -1290,22 +1312,38 @@ public final class S3CopySimulator {
private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3,
IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
boolean cleanPath) throws IOException {
boolean cleanPath, RedshiftParquetWriter parquetWriter,
String accountId) throws IOException {
this.spec = spec;
this.parquetWriter = parquetWriter;
this.accountId = accountId;
this.cleanPathPending = cleanPath;
this.s3 = s3;
this.iamService = iamService;
this.roleSession = roleSession;
threshold = spec.maxFileSizeBytes() > 0 ? spec.maxFileSizeBytes() : UNLOAD_TARGET_FILE_BYTES;
contentType = spec.gzip() ? "application/gzip" : "text/plain";
contentType = spec.parquet() ? "application/octet-stream"
: spec.gzip() ? "application/gzip" : "text/plain";
acc = newAccumulator();
headerBuf = spec.header() ? new ByteArrayOutputStream() : null;
capturingHeader = spec.header();
}
@Override
public void columns(List<RedshiftParquetWriter.Column> columns) {
this.columns = columns;
}
@Override
public void accept(byte[] body) throws IOException {
ensureOpen();
if (spec.parquet()) {
for (byte value : body) {
if (value == '"') {
quotedCsv = !quotedCsv;
}
}
}
runCleanPath();
int dataStart = 0;
if (capturingHeader) {
@@ -1346,7 +1384,8 @@ public final class S3CopySimulator {
fail(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
"UNLOAD result exceeds the " + UNLOAD_MAX_TOTAL_BYTES + "-byte limit", null);
}
if (slicePayload >= threshold && lastByteNewline) {
long bufferThreshold = spec.parquet() ? UNLOAD_TARGET_FILE_BYTES : threshold;
if (slicePayload >= bufferThreshold && lastByteNewline && !quotedCsv) {
writeCurrentSlice();
resetSlice();
}
@@ -1358,7 +1397,7 @@ public final class S3CopySimulator {
runCleanPath();
byte[] payload = finishSlice(acc, sink);
if (slicePayload > 0 || writtenKeys.isEmpty()) {
writePayload(payload, sliceIndex);
writeSlice(payload);
}
if (spec.manifest()) {
try {
@@ -1439,8 +1478,26 @@ public final class S3CopySimulator {
private void writeCurrentSlice() throws IOException {
byte[] payload = finishSlice(acc, sink);
writePayload(payload, sliceIndex);
sliceIndex++;
writeSlice(payload);
}
private void writeSlice(byte[] payload) throws IOException {
if (spec.parquet()) {
try {
for (byte[] file : parquetWriter.convert(payload, columns, accountId, roleSession, threshold)) {
writePayload(file, sliceIndex++);
}
} catch (IOException | RuntimeException exception) {
abort();
if (exception instanceof S3TransferException transfer) {
throw transfer;
}
throw new S3TransferException(SQLSTATE_INTERNAL,
"UNLOAD Parquet conversion failed: " + exception.getMessage(), exception);
}
} else {
writePayload(payload, sliceIndex++);
}
}
private void writePayload(byte[] payload, int index) {
@@ -1513,7 +1570,7 @@ public final class S3CopySimulator {
// EXTENSION 'txt.gz' GZIP), so the caller's extension is the whole suffix.
return spec.extension().startsWith(".") ? base + spec.extension() : base + "." + spec.extension();
}
return spec.gzip() ? base + ".gz" : base;
return spec.parquet() ? base + ".parquet" : spec.gzip() ? base + ".gz" : base;
}
private static byte[] finishSlice(OutputStream acc, ByteArrayOutputStream sink) throws IOException {
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.glue.model.Table;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess;
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator;
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import jakarta.enterprise.context.ApplicationScoped;
@@ -787,7 +788,7 @@ public class ExternalTableMaterializer {
String partition = AwsRegions.partitionFor(config.defaultRegion());
String scratchArn = AwsArnUtils.Arn.global(partition, "s3", "",
SCRATCH_BUCKET + "/" + scratchKey).toString();
iamService.registerSpectrumScratchResource(roleSession.accessKeyId(), scratchArn);
iamService.registerScratchResource(roleSession.accessKeyId(), scratchArn);
}
readWithDuckDb(session.accountId(), roleSession, table, sources,
config.services().redshift().spectrumMaxRows(), scratchKey);
@@ -831,7 +832,7 @@ public class ExternalTableMaterializer {
throw exception;
} finally {
if (roleSession != null && roleSession.accessKeyId() != null) {
iamService.clearSpectrumScratchResource(roleSession.accessKeyId());
iamService.clearScratchResource(roleSession.accessKeyId());
}
if (scratchKey != null) {
String cleanupKey = scratchKey;
@@ -963,7 +964,11 @@ public class ExternalTableMaterializer {
private void prepareScratchBucket(String accountId) {
RequestScopes.runAs(accountId, () -> {
ensureScratchBucket();
try {
S3ScratchSpace.SPECTRUM.ensureBucket(s3Service, config.defaultRegion());
} catch (IOException exception) {
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED, exception.getMessage(), exception);
}
if (sweptAccounts.add(accountId)) {
sweepStaleScratchObjects();
}
@@ -1058,30 +1063,6 @@ public class ExternalTableMaterializer {
}
}
/**
* Creates the scratch bucket and tags it as ours. A bucket of that name that carries no tag belongs to
* the user: it is neither written to nor swept, and the load fails instead of mixing with it.
*/
private void ensureScratchBucket() {
boolean created = true;
try {
s3Service.createInternalBucket(SCRATCH_BUCKET, config.defaultRegion());
} catch (AwsException exception) {
if (!"BucketAlreadyOwnedByYou".equals(exception.getErrorCode())) {
throw exception;
}
created = false;
}
if (created) {
s3Service.putBucketTagging(SCRATCH_BUCKET,
Map.of(S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
} else if (!S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE.equals(
s3Service.getBucketTagging(SCRATCH_BUCKET).get(S3Service.INTERNAL_BUCKET_TAG_KEY))) {
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED, "Bucket \"" + SCRATCH_BUCKET
+ "\" already exists and is not the Spectrum scratch bucket");
}
}
/**
* A JVM that dies mid-load leaves its scratch object behind. The first load of an account removes the
* old ones; a recent object may belong to a load still running, so only stale ones go.
@@ -0,0 +1,72 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.s3.model.Bucket;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/** Internal S3 transfers retain separate object and prefix permissions. */
public enum S3ScratchSpace {
SPECTRUM(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE,
"spectrum-%s\\.csv", Set.of("s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload")),
UNLOAD(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, S3Service.REDSHIFT_UNLOAD_STAGING_TAG_VALUE,
"unload/%s/", Set.of("s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListBucket"));
private final String bucketName;
private final String tagValue;
private final Pattern resourcePattern;
private final Set<String> actions;
S3ScratchSpace(String bucketName, String tagValue, String keyPattern, Set<String> actions) {
this.bucketName = bucketName;
this.tagValue = tagValue;
this.actions = actions;
resourcePattern = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":s3:::" + Pattern.quote(bucketName)
+ "/" + keyPattern.formatted("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}"));
}
public String bucketName() {
return bucketName;
}
boolean matchesBucket(Bucket bucket) {
return bucketName.equals(bucket.getName()) && bucket.getTags() != null
&& tagValue.equals(bucket.getTags().get(S3Service.INTERNAL_BUCKET_TAG_KEY));
}
/** Creation and tagging must finish before another transfer checks ownership. */
public synchronized void ensureBucket(S3Service s3, String region) throws IOException {
try {
s3.createInternalBucket(bucketName, region);
} catch (AwsException exception) {
if (!"BucketAlreadyOwnedByYou".equals(exception.getErrorCode())) {
throw exception;
}
if (!tagValue.equals(s3.getBucketTagging(bucketName).get(S3Service.INTERNAL_BUCKET_TAG_KEY))) {
throw new IOException("Bucket \"" + bucketName + "\" already exists and is not Floci scratch space");
}
return;
}
s3.putBucketTagging(bucketName, Map.of(S3Service.INTERNAL_BUCKET_TAG_KEY, tagValue));
}
public boolean permits(String action, String registeredArn, List<String> resources, String listPrefix) {
if (!actions.contains(action) || resources.isEmpty() || !resourcePattern.matcher(registeredArn).matches()) {
return false;
}
if ("s3:ListBucket".equals(action)) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(registeredArn);
String bucketArn = AwsArnUtils.Arn.global(arn.partition(), "s3", "", bucketName).toString();
String allowedPrefix = arn.resource().substring(bucketName.length() + 1);
return listPrefix != null && listPrefix.startsWith(allowedPrefix)
&& resources.stream().allMatch(bucketArn::equals);
}
return resources.stream().allMatch(resource -> this == UNLOAD
? resource.startsWith(registeredArn) : resource.equals(registeredArn));
}
}
@@ -117,6 +117,8 @@ public class S3Service implements Resettable, ResourceProvider {
public static final String INTERNAL_BUCKET_PREFIX = "floci-internal-";
public static final String REDSHIFT_SPECTRUM_SCRATCH_BUCKET =
INTERNAL_BUCKET_PREFIX + "redshift-spectrum-scratch";
public static final String REDSHIFT_UNLOAD_STAGING_BUCKET = INTERNAL_BUCKET_PREFIX + "redshift-unload-staging";
public static final String REDSHIFT_UNLOAD_STAGING_TAG_VALUE = "redshift-unload-staging";
public static final String INTERNAL_BUCKET_TAG_KEY = "floci:internal";
public static final String REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE = "redshift-spectrum-scratch";
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
@@ -614,26 +616,16 @@ public class S3Service implements Resettable, ResourceProvider {
public List<Bucket> listBuckets() {
return bucketStore.scan(key -> true).stream()
.filter(bucket -> !isSpectrumScratchBucket(bucket))
.filter(bucket -> !isScratchBucket(bucket))
.toList();
}
/**
* The Spectrum scratch bucket is told apart from a user bucket of the same name by the tag the
* materializer puts on it, so a user's own bucket is never hidden or treated as scratch space.
*/
private static boolean isSpectrumScratchBucket(Bucket bucket) {
return REDSHIFT_SPECTRUM_SCRATCH_BUCKET.equals(bucket.getName())
&& bucket.getTags() != null
&& REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE.equals(bucket.getTags().get(INTERNAL_BUCKET_TAG_KEY));
private static boolean isScratchBucket(Bucket bucket) {
return Arrays.stream(S3ScratchSpace.values()).anyMatch(space -> space.matchesBucket(bucket));
}
/**
* Returns true if the named bucket is Floci's internal Redshift Spectrum scratch bucket,
* verified by its name and internal tag.
*/
public boolean isSpectrumScratchBucket(String bucketName) {
return resolveBucket(bucketName).filter(S3Service::isSpectrumScratchBucket).isPresent();
public boolean isScratchBucket(String bucketName) {
return resolveBucket(bucketName).filter(S3Service::isScratchBucket).isPresent();
}
public String getBucketOwnerAccountId(String bucketName) {
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.s3.S3Controller;
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.scheduler.SchedulerController;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
@@ -1623,7 +1624,7 @@ class IamEnforcementFilterTest {
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
.thenReturn(CallerContext.of(List.of(identityPolicy)));
when(iamService.resolveCallerArns("ASIASESSION")).thenReturn(Optional.of(callerArns));
when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.of(SCRATCH_OBJECT));
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(SCRATCH_OBJECT));
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString()))
.thenReturn(List.of(resource));
UriInfo uriInfo = mock(UriInfo.class);
@@ -1645,7 +1646,7 @@ class IamEnforcementFilterTest {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
newFilterWithRealEvaluator().filter(containerRequest);
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
verify(containerRequest, never()).abortWith(any());
}
@@ -1657,7 +1658,7 @@ class IamEnforcementFilterTest {
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"s3:*\","
+ "\"Resource\":\"*\"}]}");
newFilterWithRealEvaluator().filter(containerRequest);
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
verify(containerRequest, never()).abortWith(any());
}
@@ -1669,7 +1670,7 @@ class IamEnforcementFilterTest {
S3Service s3Service = mock(S3Service.class);
when(s3ServiceProvider.isResolvable()).thenReturn(true);
when(s3ServiceProvider.get()).thenReturn(s3Service);
when(s3Service.isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)).thenReturn(false);
when(s3Service.isScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)).thenReturn(false);
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
@@ -1689,7 +1690,7 @@ class IamEnforcementFilterTest {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
stubSignedS3Request(containerRequest, attempt[0], attempt[1], assumedRoleArns(), NO_STATEMENTS);
newFilterWithRealEvaluator().filter(containerRequest);
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
verify(containerRequest).abortWith(any(Response.class));
}
@@ -1703,7 +1704,7 @@ class IamEnforcementFilterTest {
"arn:aws:iam::222233334444:user/alice", IamService.CallerArns.TYPE_USER, null, "alice",
false), NO_STATEMENTS);
newFilterWithRealEvaluator().filter(containerRequest);
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
verify(containerRequest).abortWith(any(Response.class));
}
@@ -1712,13 +1713,72 @@ class IamEnforcementFilterTest {
void anUnrelatedRoleSessionCannotWriteTheSpectrumScratchBucket() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.empty());
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.empty());
newFilterWithRealEvaluator().filter(containerRequest);
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
verify(containerRequest).abortWith(any(Response.class));
}
private static final String UNLOAD_PREFIX = "arn:aws:s3:::floci-internal-redshift-unload-staging/"
+ "unload/123e4567-e89b-12d3-a456-426614174000/";
private IamEnforcementFilter scratchFilter(S3ScratchSpace space, boolean internalBucket) {
@SuppressWarnings("unchecked")
Instance<S3Service> provider = mock(Instance.class);
S3Service s3 = mock(S3Service.class);
when(provider.isResolvable()).thenReturn(true);
when(provider.get()).thenReturn(s3);
when(s3.isScratchBucket(space.bucketName())).thenReturn(internalBucket);
return newFilterWithRealEvaluator(provider);
}
@Test
void unloadScratchAccessIsScopedAheadOfRoleDenies() {
for (String action : List.of("s3:GetObject", "s3:PutObject", "s3:AbortMultipartUpload", "s3:DeleteObject")) {
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
stubSignedS3Request(ctx, action, UNLOAD_PREFIX + "output.parquet/data_0.parquet", assumedRoleArns(),
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}");
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(UNLOAD_PREFIX));
scratchFilter(S3ScratchSpace.UNLOAD, true).filter(ctx);
verify(ctx, never()).abortWith(any());
}
}
@Test
void unloadScratchListingsCannotEscapeTheTransferPrefix() {
for (String prefix : List.of("unload/123e4567-e89b-12d3-a456-426614174000/output.parquet/", "", "unload/", "other/")) {
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
stubSignedS3Request(ctx, "s3:ListBucket", "arn:aws:s3:::floci-internal-redshift-unload-staging", assumedRoleArns(), NO_STATEMENTS);
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(UNLOAD_PREFIX));
ctx.getUriInfo().getQueryParameters().putSingle("prefix", prefix);
scratchFilter(S3ScratchSpace.UNLOAD, true).filter(ctx);
if (prefix.startsWith("unload/123e4567-e89b-12d3-a456-426614174000/")) {
verify(ctx, never()).abortWith(any());
} else {
verify(ctx).abortWith(any(Response.class));
}
}
}
@Test
void unloadScratchAllowanceRejectsOtherKeysSessionsAndBuckets() {
for (String resource : List.of("arn:aws:s3:::user-destination/file.parquet",
"arn:aws:s3:::floci-internal-redshift-unload-staging/unload/other/input.csv", UNLOAD_PREFIX + "input.csv")) {
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
stubSignedS3Request(ctx, "s3:GetObject", resource, assumedRoleArns(), NO_STATEMENTS);
when(iamService.scratchResourceArn("ASIASESSION"))
.thenReturn(resource.equals(UNLOAD_PREFIX + "input.csv") ? Optional.empty() : Optional.of(UNLOAD_PREFIX));
scratchFilter(S3ScratchSpace.UNLOAD, true).filter(ctx);
verify(ctx).abortWith(any(Response.class));
}
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
stubSignedS3Request(ctx, "s3:PutObject", UNLOAD_PREFIX + "input.csv", assumedRoleArns(), NO_STATEMENTS);
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(UNLOAD_PREFIX));
scratchFilter(S3ScratchSpace.UNLOAD, false).filter(ctx);
verify(ctx).abortWith(any(Response.class));
}
// FullAWSAccess baseline auto-attached to every OU/account when SCP enforcement is on.
private static final String FULL_AWS_ACCESS =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
@@ -2615,16 +2615,40 @@ class IamServiceTest {
accountId, accessKeyId, "secret", "token",
"arn:aws:iam::222233334444:role/R", Instant.now().plusSeconds(900), null);
assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty());
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
String scratchArn = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-1234.csv";
service.registerSpectrumScratchResource(accessKeyId, scratchArn);
service.registerScratchResource(accessKeyId, scratchArn);
assertEquals(Optional.of(scratchArn), service.spectrumScratchResourceArn(accessKeyId));
assertEquals(Optional.of(scratchArn), service.scratchResourceArn(accessKeyId));
service.clearSpectrumScratchResource(accessKeyId);
service.clearScratchResource(accessKeyId);
assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty());
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
}
@Test
void unloadScratchPrefixRegistrationAndClear() {
String accountId = "222233334444";
String accessKeyId = "ASIAUNLOAD";
AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000");
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
service.registerSessionForAccount(
accountId, accessKeyId, "secret", "token",
"arn:aws:iam::222233334444:role/R", Instant.now().plusSeconds(900), null);
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
String scratchArn = "arn:aws:s3:::floci-internal-redshift-unload-staging/unload/123e4567-e89b-12d3-a456-426614174000/";
service.registerScratchResource(accessKeyId, scratchArn);
assertEquals(Optional.of(scratchArn), service.scratchResourceArn(accessKeyId));
service.registerScratchResource(accessKeyId, null);
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
}
// =========================================================================
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
class RedshiftUnloadParquetIntegrationTest {
@Inject
RedshiftService redshift;
@Inject
S3Service s3;
@Inject
FlociDuckClient duck;
@BeforeAll
static void requireDocker() {
SidecarContainersProfile.requireDocker();
}
@ParameterizedTest
@Timeout(180)
@ValueSource(booleans = {false, true})
void typedParquetRoundTripsOverSimpleAndNamedExtendedQueries(boolean extended) throws Exception {
String id = "unload-pq-" + UUID.randomUUID().toString().substring(0, 8);
String bucket = id;
s3.createBucket(bucket, "us-east-1");
Cluster cluster = redshift.createCluster(id, "dc2.large", "admin", "Secret123");
try {
await().atMost(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(1))
.until(() -> "available".equals(redshift.describeClusters(id).getFirst().getClusterStatus()));
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
+ "/dev?socketTimeout=90&" + (extended ? "prepareThreshold=1" : "preferQueryMode=simple");
try (Connection connection = DriverManager.getConnection(url, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TEMP TABLE pq_src (id bigint, amount decimal(18,4), label text, "
+ "optional text, day date, happened timestamp, active boolean)");
statement.execute("INSERT INTO pq_src VALUES (9007199254740993, 12345678901234.5678, "
+ "'comma,quote\"line\nnext', NULL, '2026-11-04', '2026-11-04 12:34:56.123456', true), "
+ "(2, NULL, '', '', NULL, NULL, false)");
String unload = "UNLOAD ('SELECT * FROM pq_src ORDER BY id') TO 's3://" + bucket
+ "/data/' FORMAT AS PARQUET MANIFEST ALLOWOVERWRITE";
try (PreparedStatement prepared = connection.prepareStatement(unload)) {
if (extended) {
assertNull(prepared.getMetaData());
}
prepared.execute();
prepared.execute();
}
List<Map<String, Object>> rows = duck.query("SELECT id::VARCHAR AS id, amount::VARCHAR AS amount, "
+ "label, optional, day::VARCHAR AS day, happened::VARCHAR AS happened, active "
+ "FROM read_parquet('s3://" + bucket + "/data/*.parquet') ORDER BY id::BIGINT", null);
assertEquals(2, rows.size());
assertEquals("", rows.get(0).get("label"));
assertEquals("", rows.get(0).get("optional"));
assertNull(rows.get(0).get("amount"));
assertEquals("9007199254740993", rows.get(1).get("id"));
assertEquals("12345678901234.5678", rows.get(1).get("amount"));
assertEquals("comma,quote\"line\nnext", rows.get(1).get("label"));
assertNull(rows.get(1).get("optional"));
assertEquals("2026-11-04", rows.get(1).get("day"));
assertEquals("2026-11-04 12:34:56.123456", rows.get(1).get("happened"));
assertEquals(true, rows.get(1).get("active"));
S3Object data = s3.listObjects(bucket, "data/", null, 100).stream()
.filter(object -> object.getKey().endsWith(".parquet")).findFirst().orElseThrow();
byte[] bytes = s3.getObject(bucket, data.getKey()).getData();
assertEquals("PAR1", new String(bytes, 0, 4, StandardCharsets.US_ASCII));
assertEquals("PAR1", new String(bytes, bytes.length - 4, 4, StandardCharsets.US_ASCII));
String manifest = new String(s3.getObject(bucket, "data/manifest").getData(), StandardCharsets.UTF_8);
assertTrue(manifest.contains(data.getKey()));
assertTrue(manifest.contains(String.valueOf(bytes.length)));
try (PreparedStatement empty = connection.prepareStatement("UNLOAD ('SELECT * FROM pq_src WHERE false') "
+ "TO 's3://" + bucket + "/empty/' PARQUET PARALLEL OFF")) {
empty.execute();
}
List<Map<String, Object>> emptyCount = duck.query("SELECT count(*) AS n FROM read_parquet('s3://"
+ bucket + "/empty/000.parquet')", null);
assertEquals(0, ((Number) emptyCount.getFirst().get("n")).intValue());
assertEquals(7, duck.query("DESCRIBE SELECT * FROM read_parquet('s3://" + bucket
+ "/empty/000.parquet')", null).size());
statement.execute("UNLOAD ('SELECT optional FROM pq_src ORDER BY id') TO 's3://"
+ bucket + "/single-column/' PARQUET");
List<Map<String, Object>> singleColumn = duck.query("SELECT optional FROM read_parquet('s3://"
+ bucket + "/single-column/*.parquet')", null);
assertEquals(2, singleColumn.size());
assertEquals("", singleColumn.get(0).get("optional"));
assertNull(singleColumn.get(1).get("optional"));
statement.execute("UNLOAD ('SELECT id FROM generate_series(1, 250000) AS g(id) ORDER BY id') "
+ "TO 's3://" + bucket + "/split/' PARQUET PARALLEL OFF MAXFILESIZE 65536 MANIFEST");
List<S3Object> parts = s3.listObjects(bucket, "split/", null, 100).stream()
.filter(object -> object.getKey().endsWith(".parquet")).toList();
assertTrue(parts.size() > 1, "DuckDB should split at row-group boundaries");
String splitManifest = new String(s3.getObject(bucket, "split/manifest").getData(), StandardCharsets.UTF_8);
for (int i = 0; i < parts.size(); i++) {
S3Object part = parts.get(i);
assertEquals(String.format("split/%03d.parquet", i), part.getKey());
assertTrue(splitManifest.contains(part.getKey()));
assertTrue(splitManifest.contains(String.valueOf(part.getSize())));
}
List<Map<String, Object>> splitRows = duck.query("SELECT count(*) AS n, count(DISTINCT id) AS unique_ids "
+ "FROM read_parquet('s3://" + bucket + "/split/*.parquet')", null);
assertEquals(250000, ((Number) splitRows.getFirst().get("n")).intValue());
assertEquals(250000, ((Number) splitRows.getFirst().get("unique_ids")).intValue());
assertUnsupportedTypes(connection, statement, url, bucket);
SQLException rejected = assertThrows(SQLException.class, () -> statement.execute(
"UNLOAD ('SELECT missing FROM pq_src') TO 's3://" + bucket + "/bad/' PARQUET"));
assertEquals("42703", rejected.getSQLState());
try (ResultSet result = statement.executeQuery("SELECT 1")) {
assertTrue(result.next());
assertEquals(1, result.getInt(1));
}
}
} finally {
redshift.deleteCluster(id);
for (S3Object object : s3.listObjects(bucket, null, null, 1000)) {
s3.deleteObject(bucket, object.getKey());
}
s3.deleteBucket(bucket);
}
}
private void assertUnsupportedTypes(Connection connection, Statement statement, String url, String bucket) throws Exception {
int backendPid;
try (ResultSet pid = statement.executeQuery("SELECT pg_backend_pid()")) {
assertTrue(pid.next());
backendPid = pid.getInt(1);
}
String numericUnload = "UNLOAD ('SELECT amount::numeric AS total FROM pq_src') TO 's3://"
+ bucket + "/unsupported/' PARQUET";
SQLException numeric = assertThrows(SQLException.class, () -> statement.execute(numericUnload));
assertEquals("0A000", numeric.getSQLState());
assertTrue(numeric.getMessage().contains("column \"total\""));
assertTrue(numeric.getMessage().contains("NUMERIC without declared precision and scale"));
assertTrue(numeric.getMessage().contains("DECIMAL(p,s)"));
// Observe the rejected connection before sending it another command that could finish its transaction.
try (Connection observer = DriverManager.getConnection(url, "admin", "Secret123");
Statement inspection = observer.createStatement();
ResultSet state = inspection.executeQuery("SELECT xact_start IS NULL FROM pg_stat_activity WHERE pid = " + backendPid)) {
assertTrue(state.next());
assertTrue(state.getBoolean(1), "Type rejection must not leave an implicit transaction open");
}
String uuidUnload = "UNLOAD ('SELECT NULL::uuid AS payload') TO 's3://" + bucket + "/unsupported/' PARQUET";
SQLException uuid = assertThrows(SQLException.class, () -> statement.execute(uuidUnload));
assertEquals("0A000", uuid.getSQLState());
assertTrue(uuid.getMessage().contains("column \"payload\""));
assertTrue(uuid.getMessage().contains("UUID (OID 2950)"));
assertTrue(uuid.getMessage().contains("VARCHAR"));
assertTrue(s3.listObjects(bucket, "unsupported/", null, 100).isEmpty());
connection.setAutoCommit(false);
try {
statement.execute("SELECT 1");
SQLException rejected = assertThrows(SQLException.class, () -> statement.execute(numericUnload));
assertEquals("0A000", rejected.getSQLState());
SQLException failedTransaction = assertThrows(SQLException.class, () -> statement.execute("SELECT 1"));
assertEquals("25P02", failedTransaction.getSQLState());
} finally {
connection.rollback();
connection.setAutoCommit(true);
}
statement.execute("SELECT 1");
}
}
@@ -0,0 +1,92 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
import io.github.hectorvent.floci.testing.SidecarS3AuthEnforcedProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@TestProfile(SidecarS3AuthEnforcedProfile.class)
class RedshiftUnloadParquetS3AuthIntegrationTest {
@Inject
RedshiftService redshift;
@Inject
S3Service s3;
@Inject
IamService iam;
@BeforeAll
static void requireDocker() {
SidecarContainersProfile.requireDocker();
}
@Test
@Timeout(180)
void destinationOnlyRoleCanConvertButDestinationDeniesStillApply() throws Exception {
String name = "unload-auth-" + UUID.randomUUID().toString().substring(0, 8);
String role = iam.createRole(name, "/", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""", null, 0, null).getArn();
s3.createBucket(name, "us-east-1");
iam.putRolePolicy(name, "destination-only", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::%s"},
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"},
{"Effect":"Deny","Action":"s3:*","Resource":["arn:aws:s3:::floci-internal-redshift-unload-staging",
"arn:aws:s3:::floci-internal-redshift-unload-staging/*"]}]}
""".formatted(name, name));
try {
Cluster cluster = redshift.createCluster(name, "dc2.large", "admin", "Secret123", null, List.of(), List.of(role));
await().atMost(Duration.ofSeconds(120)).until(() ->
"available".equals(redshift.describeClusters(name).getFirst().getClusterStatus()));
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev?socketTimeout=60";
try (Connection connection = DriverManager.getConnection(url, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("UNLOAD ('SELECT 1 AS id') TO 's3://" + name + "/out/' IAM_ROLE '" + role
+ "' PARQUET MANIFEST PARALLEL OFF");
assertTrue(s3.getObject(name, "out/000.parquet").getSize() > 0);
assertTrue(s3.getObject(name, "out/manifest").getSize() > 0);
assertTrue(s3.listObjects(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, null, null, 100).isEmpty());
assertTrue(s3.listBuckets().stream().noneMatch(bucket ->
bucket.getName().equals(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET)));
s3.putBucketPolicy(name, """
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":{"AWS":"%s"},
"Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/denied/*"}]}
""".formatted(role, name));
SQLException denied = assertThrows(SQLException.class, () -> statement.execute(
"UNLOAD ('SELECT 2 AS id') TO 's3://" + name + "/denied/' IAM_ROLE '" + role + "' PARQUET"));
assertEquals("42501", denied.getSQLState());
assertTrue(s3.listObjects(name, "denied/", null, 100).isEmpty());
}
} finally {
redshift.deleteCluster(name);
s3.deleteBucketPolicy(name);
for (S3Object object : s3.listObjects(name, null, null, 100)) {
s3.deleteObject(name, object.getKey());
}
s3.deleteBucket(name);
iam.deleteRolePolicy(name, "destination-only");
iam.deleteRole(name);
}
}
}
@@ -364,9 +364,26 @@ class CopyStatementParserTest {
assertNull(CopyStatementParser.parse("UNLOAD ('select \\1') TO 's3://b/p/'"));
}
@Test
void unloadAcceptsParquetFormatsAndRejectsTextOptions() {
for (String format : List.of("PARQUET", "FORMAT PARQUET", "FORMAT AS PARQUET", "format as parquet")) {
CopyStatementParser.S3Unload spec = unload("UNLOAD ('select 1') TO 's3://b/p/' "
+ format + " MANIFEST ALLOWOVERWRITE PARALLEL OFF EXTENSION 'pq'");
assertNotNull(spec);
assertTrue(spec.parquet());
assertTrue(spec.manifest());
assertFalse(spec.parallel());
assertEquals("pq", spec.extension());
}
for (String option : List.of("CSV", "FORMAT CSV", "GZIP", "HEADER", "ADDQUOTES", "ESCAPE",
"DELIMITER ','", "NULL AS 'nil'", "PARQUET")) {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARQUET " + option), option);
}
assertFalse(unload("UNLOAD ('select 1') TO 's3://b/p/' EXTENSION 'parquet'").parquet());
}
@Test
void unloadRejectsUnsupportedOptions() {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARQUET"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' ENCRYPTED"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' MASTER_SYMMETRIC_KEY 'k'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' KMS_KEY_ID 'k'"));
@@ -46,7 +46,7 @@ class RedshiftAuthProxyTest {
int port = FreePorts.anyInterfacePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", 1, "admin", "password", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, password) -> PasswordValidator.AuthResult.REJECT,
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit);
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit, null);
proxy.start(port);
try (Socket client = new Socket("localhost", port)) {
client.setSoTimeout(5000);
@@ -79,7 +79,7 @@ class RedshiftAuthProxyTest {
int port = FreePorts.anyInterfacePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "password", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, password) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit);
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit, null);
proxy.start(port);
try (Socket client = new Socket("localhost", port)) {
client.setSoTimeout(5000);
@@ -78,7 +78,7 @@ class RedshiftInterceptingBridgeTest {
s3Stub = Mockito.mock(S3Service.class);
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(),
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst");
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst", null);
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
}
@@ -0,0 +1,160 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class RedshiftParquetWriterTest {
@Test
void mapsDeclaredNumericTypesAndRejectsLossyConversions() {
assertEquals("DECIMAL(18,4)", RedshiftParquetWriter.type("amount", 1700, (18 << 16) + 4 + 4));
assertEquals("BIGINT", RedshiftParquetWriter.type("amount", 20, -1));
assertEquals("DATE", RedshiftParquetWriter.type("amount", 1082, -1));
assertEquals("TIMESTAMP", RedshiftParquetWriter.type("amount", 1114, -1));
assertThrows(S3CopySimulator.S3TransferException.class, () -> RedshiftParquetWriter.type("amount", 1700, -1));
assertThrows(S3CopySimulator.S3TransferException.class, () -> RedshiftParquetWriter.type("amount", 17, -1));
}
@Test
void unsupportedErrorsIdentifyTheColumnTypeAndSuggestedCast() {
for (int oid : List.of(17, 114, 2950, 3802, 1007, 99999)) {
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftParquetWriter.type("payload", oid, -1));
assertEquals("0A000", error.sqlState());
assertTrue(error.getMessage().contains("column \"payload\""));
assertTrue(error.getMessage().contains("OID " + oid));
assertTrue(error.getMessage().contains("Cast it explicitly"));
}
for (int modifier : List.of(-1, (40 << 16) + 2 + 4, (18 << 16) + 20 + 4,
(18 << 16) + 0x7ff + 4)) {
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftParquetWriter.type("total", 1700, modifier));
assertEquals("0A000", error.sqlState());
assertTrue(error.getMessage().contains("column \"total\""));
assertTrue(error.getMessage().contains("NUMERIC"));
assertTrue(error.getMessage().contains("DECIMAL(p,s)"));
}
}
@Test
void delegatesSizingToDuckDbAndCleansStagingOnSuccessAndFailure() throws Exception {
for (boolean failure : List.of(false, true)) {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
byte[] parquet = "PAR1payloadPAR1".getBytes(StandardCharsets.UTF_8);
when(s3.openObjectStream(eq(RedshiftParquetWriter.STAGING_BUCKET), anyString(), isNull()))
.thenReturn(new ByteArrayInputStream(parquet), new ByteArrayInputStream(parquet));
when(duck.query(anyString(), anyString(), eq("123456789012")))
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet"),
Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_1.parquet")));
if (failure) {
when(duck.query(anyString(), anyString(), eq("123456789012")))
.thenThrow(new IllegalStateException("sidecar unavailable"));
}
List<RedshiftParquetWriter.Column> columns = List.of(
new RedshiftParquetWriter.Column("a\"b", "BIGINT"),
new RedshiftParquetWriter.Column("amount", "DECIMAL(18,4)"));
byte[] csv = "1,123.4500\n".getBytes(StandardCharsets.UTF_8);
RedshiftParquetWriter writer = writer(s3, duck);
if (failure) {
assertThrows(IllegalStateException.class, () -> writer.convert(csv, columns, "123456789012", null, 8192));
} else {
List<byte[]> files = writer.convert(csv, columns, "123456789012", null, 8192);
assertEquals(2, files.size());
assertArrayEquals(parquet, files.get(0));
assertArrayEquals(parquet, files.get(1));
}
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
verify(duck).query(sql.capture(), contains("SET threads = 1"), eq("123456789012"));
assertTrue(sql.getValue().contains("columns = {'c0': 'BIGINT', 'c1': 'DECIMAL(18,4)'}"));
assertTrue(sql.getValue().contains("c0 AS \"a\"\"b\""));
assertTrue(sql.getValue().contains("COMPRESSION SNAPPY"));
assertTrue(sql.getValue().contains("FILE_SIZE_BYTES 8192, RETURN_STATS true"));
verify(s3).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), any());
}
}
@Test
void emptyResultRetainsSchemaWithoutInferringFromCsv() throws Exception {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
when(duck.query(anyString(), anyString(), anyString()))
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet")));
when(s3.openObjectStream(anyString(), anyString(), isNull()))
.thenReturn(new ByteArrayInputStream(new byte[0]));
writer(s3, duck).convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
"123456789012", null, 8192);
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
verify(duck).query(sql.capture(), anyString(), eq("123456789012"));
assertTrue(sql.getValue().contains("SELECT CAST(NULL AS INTEGER) AS \"id\" WHERE false"));
assertFalse(sql.getValue().contains("read_csv"));
}
@Test
void forwardsRoleSessionCredentialsToTheSidecar() throws Exception {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
when(duck.query(anyString(), anyString(), eq("access"), eq("secret"), eq("token")))
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet")));
when(s3.openObjectStream(anyString(), anyString(), isNull()))
.thenReturn(new ByteArrayInputStream(new byte[0]));
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("access", "secret", "token");
writer(s3, duck).convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
"123456789012", session, 8192);
verify(duck).query(anyString(), anyString(), eq("access"), eq("secret"), eq("token"));
}
@Test
void registersAndRevokesStagingScopeEvenWhenConversionFails() throws Exception {
S3Service s3 = mock(S3Service.class);
IamService iam = mock(IamService.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
when(duck.query(anyString(), anyString(), eq("access"), eq("secret"), eq("token")))
.thenThrow(new IllegalStateException("sidecar failed"));
RedshiftParquetWriter writer = new RedshiftParquetWriter(duck, s3, iam, config);
assertThrows(IllegalStateException.class, () -> writer.convert(new byte[0],
List.of(new RedshiftParquetWriter.Column("id", "INTEGER")), "123456789012",
new RedshiftRoleAccess.RoleSession("access", "secret", "token"), 8192));
ArgumentCaptor<String> scopes = ArgumentCaptor.forClass(String.class);
verify(iam).registerScratchResource(eq("access"), scopes.capture());
verify(iam).clearScratchResource("access");
assertTrue(scopes.getAllValues().get(0).matches(
"arn:aws:s3:::floci-internal-redshift-unload-staging/unload/[0-9a-f-]{36}/"));
verify(s3).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), anyString(), any());
}
@Test
void refusesToUseAnExistingUntaggedStagingBucket() {
S3Service s3 = mock(S3Service.class);
FlociDuckClient duck = mock(FlociDuckClient.class);
when(s3.createInternalBucket(anyString(), anyString())).thenThrow(
new AwsException("BucketAlreadyOwnedByYou", "exists", 409));
assertThrows(IOException.class, () -> writer(s3, duck).convert(new byte[0],
List.of(new RedshiftParquetWriter.Column("id", "INTEGER")), "123456789012", null, 8192));
verifyNoInteractions(duck);
verify(s3, never()).putBucketTagging(anyString(), any());
verify(s3, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
}
private RedshiftParquetWriter writer(S3Service s3, FlociDuckClient duck) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultRegion()).thenReturn("us-east-1");
return new RedshiftParquetWriter(duck, s3, mock(IamService.class), config);
}
}
@@ -56,6 +56,65 @@ import static org.mockito.Mockito.when;
class S3CopySimulatorTest {
@Test
void parquetSlicesWaitForCompleteCsvRecordsAndManifestUsesConvertedLengths() throws Exception {
long previous = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 3;
try {
S3Service s3 = mock(S3Service.class);
RedshiftParquetWriter writer = mock(RedshiftParquetWriter.class);
List<RedshiftParquetWriter.Column> columns = List.of(new RedshiftParquetWriter.Column("v", "VARCHAR"));
byte[] parquet = "PAR1testPAR1".getBytes(StandardCharsets.UTF_8);
when(writer.convert(any(), eq(columns), eq("000000000000"), isNull(), eq(3L))).thenReturn(List.of(parquet));
CopyStatementParser.S3Unload spec = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
"UNLOAD ('select v from t') TO 's3://b/p/' PARQUET MANIFEST");
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(
spec, s3, null, "000000000000", null, writer)) {
collector.columns(columns);
collector.accept("\"first\n".getBytes(StandardCharsets.UTF_8));
verifyNoInteractions(writer);
collector.accept("second\"\n".getBytes(StandardCharsets.UTF_8));
collector.accept("last\n".getBytes(StandardCharsets.UTF_8));
collector.complete();
}
ArgumentCaptor<byte[]> slices = ArgumentCaptor.forClass(byte[].class);
verify(writer, times(2)).convert(slices.capture(), eq(columns), eq("000000000000"), isNull(), eq(3L));
assertEquals("\"first\nsecond\"\n", new String(slices.getAllValues().get(0), StandardCharsets.UTF_8));
verify(s3).putObject(eq("b"), eq("p/0000_part_00.parquet"), eq(parquet), eq("application/octet-stream"), any());
verify(s3).putObject(eq("b"), eq("p/0001_part_00.parquet"), eq(parquet), eq("application/octet-stream"), any());
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = previous;
}
}
@Test
void duckDbPartsUseExistingFlociNamesAndManifestLengths() throws Exception {
S3Service target = mock(S3Service.class);
RedshiftParquetWriter writer = mock(RedshiftParquetWriter.class);
List<RedshiftParquetWriter.Column> columns = List.of(new RedshiftParquetWriter.Column("v", "VARCHAR"));
byte[] first = new byte[30];
byte[] second = new byte[20];
when(writer.convert(any(), eq(columns), eq("000000000000"), isNull(), eq(1024L)))
.thenReturn(List.of(first, second));
CopyStatementParser.S3Unload spec = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
"UNLOAD ('select v from t') TO 's3://b/p/' PARQUET MANIFEST MAXFILESIZE 1024");
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(
spec, target, null, "000000000000", null, writer)) {
collector.columns(columns);
collector.accept("value\n".getBytes(StandardCharsets.UTF_8));
collector.complete();
}
verify(target).putObject(eq("b"), eq("p/0000_part_00.parquet"), eq(first), anyString(), any());
verify(target).putObject(eq("b"), eq("p/0001_part_00.parquet"), eq(second), anyString(), any());
ArgumentCaptor<byte[]> manifest = ArgumentCaptor.forClass(byte[].class);
verify(target).putObject(eq("b"), eq("p/manifest"), manifest.capture(), eq("application/json"), any());
String json = new String(manifest.getValue(), StandardCharsets.UTF_8);
assertTrue(json.contains("p/0000_part_00.parquet"));
assertTrue(json.contains("p/0001_part_00.parquet"));
assertTrue(json.contains("30"));
assertTrue(json.contains("20"));
}
@Test
void quotedDefaultIsValidatedAsAnArnForCopyAndUnload() {
IamService iamService = mock(IamService.class);
@@ -69,7 +128,7 @@ class S3CopySimulatorTest {
S3CopySimulator.S3TransferException copyError = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(copy, s3, iamService, "000000000000", List.of(ROLE_ARN)));
S3CopySimulator.S3TransferException unloadError = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareUnload(unload, s3, iamService, "000000000000", List.of(ROLE_ARN)));
() -> S3CopySimulator.prepareUnload(unload, s3, iamService, "000000000000", List.of(ROLE_ARN), null));
assertEquals("42501", copyError.sqlState());
assertEquals("42501", unloadError.sqlState());
assertTrue(copyError.getMessage().contains("malformed ARN"), copyError.getMessage());
@@ -88,7 +147,7 @@ class S3CopySimulatorTest {
S3CopySimulator.S3TransferException copyError = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(copy, s3, null, "000000000000", List.of()));
S3CopySimulator.S3TransferException unloadError = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareUnload(unload, s3, null, "000000000000", List.of()));
() -> S3CopySimulator.prepareUnload(unload, s3, null, "000000000000", List.of(), null));
assertEquals("42501", copyError.sqlState());
assertEquals("42501", unloadError.sqlState());
assertTrue(copyError.getMessage().contains("No default IAM role"));
@@ -245,9 +245,9 @@ class ExternalTableMaterializerTest {
verify(duck).execute(argThat(sql -> sql.contains("LIMIT 1001")), isNull(), anyString(),
startsWith("ASIA"), anyString(), notNull());
verify(duck, never()).execute(anyString(), any(), anyString(), eq(ACCOUNT));
verify(iam).registerSpectrumScratchResource(startsWith("ASIA"),
verify(iam).registerScratchResource(startsWith("ASIA"),
startsWith("arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-"));
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
verify(iam).clearScratchResource(startsWith("ASIA"));
}
@Test
@@ -265,7 +265,7 @@ class ExternalTableMaterializerTest {
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
verify(iam).clearScratchResource(startsWith("ASIA"));
}
@Test
@@ -301,7 +301,7 @@ class ExternalTableMaterializerTest {
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("58030"));
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
verify(iam).clearScratchResource(startsWith("ASIA"));
}
@Test
@@ -321,7 +321,7 @@ class ExternalTableMaterializerTest {
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("58030"));
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
verify(iam).clearScratchResource(startsWith("ASIA"));
}
@Test
@@ -340,7 +340,7 @@ class ExternalTableMaterializerTest {
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("58030"));
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
verify(iam).clearScratchResource(startsWith("ASIA"));
}
@Test
@@ -742,7 +742,7 @@ class ExternalTableMaterializerTest {
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.getMessage(), containsString("not the Spectrum scratch bucket"));
assertThat(exception.getMessage(), containsString("not Floci scratch space"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
verify(s3, never()).putBucketTagging(eq(ExternalTableMaterializer.SCRATCH_BUCKET), any());
verify(s3, never()).deleteObject(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString());
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class S3ScratchSpaceTest {
@ParameterizedTest
@EnumSource(S3ScratchSpace.class)
void createsTagsReusesAndRejectsUntaggedBuckets(S3ScratchSpace space) throws Exception {
S3Service s3 = mock(S3Service.class);
space.ensureBucket(s3, "us-east-1");
AtomicReference<Map<String, String>> tags = new AtomicReference<>();
verify(s3).putBucketTagging(eq(space.bucketName()), argThat(value -> {
tags.set(value);
return true;
}));
when(s3.createInternalBucket(anyString(), anyString())).thenThrow(
new AwsException("BucketAlreadyOwnedByYou", "exists", 409));
when(s3.getBucketTagging(space.bucketName())).thenReturn(tags.get());
space.ensureBucket(s3, "us-east-1");
verify(s3, times(1)).putBucketTagging(anyString(), any());
when(s3.getBucketTagging(space.bucketName())).thenReturn(Map.of());
assertThrows(IOException.class, () -> space.ensureBucket(s3, "us-east-1"));
verify(s3, times(1)).putBucketTagging(anyString(), any());
}
@ParameterizedTest
@EnumSource(S3ScratchSpace.class)
void concurrentInitializationWaitsForTheInternalTag(S3ScratchSpace space) throws Exception {
S3Service s3 = mock(S3Service.class);
CountDownLatch tagging = new CountDownLatch(1);
CountDownLatch releaseTag = new CountDownLatch(1);
AtomicReference<Map<String, String>> tags = new AtomicReference<>(Map.of());
when(s3.createInternalBucket(anyString(), anyString())).thenReturn(null).thenThrow(
new AwsException("BucketAlreadyOwnedByYou", "exists", 409));
doAnswer(invocation -> {
tagging.countDown();
assertTrue(releaseTag.await(10, TimeUnit.SECONDS));
tags.set(invocation.getArgument(1));
return null;
}).when(s3).putBucketTagging(anyString(), any());
when(s3.getBucketTagging(anyString())).thenAnswer(invocation -> tags.get());
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<?> first = executor.submit(() -> { space.ensureBucket(s3, "us-east-1"); return null; });
assertTrue(tagging.await(10, TimeUnit.SECONDS));
AtomicReference<Thread> secondThread = new AtomicReference<>();
Future<?> second = executor.submit(() -> {
secondThread.set(Thread.currentThread());
space.ensureBucket(s3, "us-east-1");
return null;
});
try {
await().atMost(Duration.ofSeconds(5)).until(() -> secondThread.get() != null
&& secondThread.get().getState() == Thread.State.BLOCKED);
verify(s3, times(1)).createInternalBucket(anyString(), anyString());
} finally {
releaseTag.countDown();
}
first.get(10, TimeUnit.SECONDS);
second.get(10, TimeUnit.SECONDS);
}
}
}
@@ -206,11 +206,14 @@ class S3ServiceTest {
}
@Test
void listBucketsHidesSpectrumScratchBucketButKeepsOtherInternalPrefixBuckets() {
void listBucketsHidesScratchBucketsButKeepsOtherInternalPrefixBuckets() {
s3Service.createBucket("bucket-a", "us-east-1");
s3Service.createBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, "us-east-1");
s3Service.putBucketTagging(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
s3Service.createBucket(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, "us-east-1");
s3Service.putBucketTagging(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_UNLOAD_STAGING_TAG_VALUE));
String userBucket = S3Service.INTERNAL_BUCKET_PREFIX + "customer-data";
s3Service.createBucket(userBucket, "us-east-1");
@@ -224,13 +227,19 @@ class S3ServiceTest {
}
@Test
void listBucketsKeepsAUserBucketThatOnlySharesTheScratchBucketName() {
s3Service.createBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, "us-east-1");
List<Bucket> buckets = s3Service.listBuckets();
assertEquals(1, buckets.size());
assertEquals(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, buckets.get(0).getName());
void scratchSetupRejectsUserBucketsAndReusesInternalBuckets() throws Exception {
for (S3ScratchSpace space : S3ScratchSpace.values()) {
s3Service.createBucket(space.bucketName(), "us-east-1");
assertThrows(IOException.class, () -> space.ensureBucket(s3Service, "us-east-1"));
assertFalse(s3Service.isScratchBucket(space.bucketName()));
assertTrue(s3Service.getBucketTagging(space.bucketName()).isEmpty());
assertTrue(s3Service.listBuckets().stream().anyMatch(bucket -> space.bucketName().equals(bucket.getName())));
s3Service.deleteBucket(space.bucketName());
space.ensureBucket(s3Service, "us-east-1");
space.ensureBucket(s3Service, "us-east-1");
assertTrue(s3Service.isScratchBucket(space.bucketName()));
assertTrue(s3Service.listBuckets().stream().noneMatch(bucket -> space.bucketName().equals(bucket.getName())));
}
}
@Test