mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(redshift): support S3 COPY JSON and manifest, and DynamoDB zero-ETL backfill (#3889)
* feat(redshift): support S3 COPY FORMAT AS JSON 'auto' and MANIFEST * fix(redshift): resolve column discovery via pg_catalog and guard against empty columns * feat(redshift): track zero-ETL backfill progress and syncing status * feat(redshift): backfill existing DynamoDB items into zero-ETL landing table * test(redshift): prove zero-ETL backfill and syncing-to-active status * fix(redshift): reject JSON 'auto' COPY without columns over Extended Query clearly Catalog-based column discovery only runs over the Simple Query protocol, so a column-less COPY ... FORMAT AS JSON 'auto' sent over Extended Query failed with an obscure error. Name the cause and remedy in the error, document the limitation, and run the discovery tests over Simple Query. * docs(redshift): document zero-ETL DynamoDB backfill and syncing status * fix(redshift): address review feedback on COPY JSON, manifest and zero-ETL backfill * fix(redshift): pass user column list as written and clarify syncing status in docs * fix(redshift): wrap long condition in identifier unquoting * fix(redshift): keep user columns as written in runCopyFrom and verify backfill account scope * test(redshift): use assertNotNull for last evaluated key assertion
This commit is contained in:
1 parent
1088187cb3
commit
9379fa1179
16 files changed
+1605
-55
No files matched your search
+111
-2
@@ -1,9 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Integration;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
@@ -14,6 +23,10 @@ import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -26,8 +39,10 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
|
||||
private final Vertx vertx;
|
||||
private final DynamoDbStreamService streamService;
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final RedshiftService redshiftService;
|
||||
private final RedshiftZeroEtlWriter writer;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final long pollIntervalMs;
|
||||
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
|
||||
@@ -40,27 +55,35 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
@Inject
|
||||
public RedshiftDynamoDbZeroEtlConsumer(Vertx vertx,
|
||||
DynamoDbStreamService streamService,
|
||||
DynamoDbService dynamoDbService,
|
||||
RedshiftService redshiftService,
|
||||
RedshiftZeroEtlWriter writer,
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config) {
|
||||
this(vertx, streamService, redshiftService, writer, config.services().redshift().pollIntervalMs());
|
||||
this(vertx, streamService, dynamoDbService, redshiftService, writer, objectMapper,
|
||||
config.services().redshift().pollIntervalMs());
|
||||
}
|
||||
|
||||
RedshiftDynamoDbZeroEtlConsumer(DynamoDbStreamService streamService,
|
||||
DynamoDbService dynamoDbService,
|
||||
RedshiftService redshiftService,
|
||||
RedshiftZeroEtlWriter writer) {
|
||||
this(null, streamService, redshiftService, writer, 1000);
|
||||
this(null, streamService, dynamoDbService, redshiftService, writer, new ObjectMapper(), 1000);
|
||||
}
|
||||
|
||||
private RedshiftDynamoDbZeroEtlConsumer(Vertx vertx,
|
||||
DynamoDbStreamService streamService,
|
||||
DynamoDbService dynamoDbService,
|
||||
RedshiftService redshiftService,
|
||||
RedshiftZeroEtlWriter writer,
|
||||
ObjectMapper objectMapper,
|
||||
long pollIntervalMs) {
|
||||
this.vertx = vertx;
|
||||
this.streamService = streamService;
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.redshiftService = redshiftService;
|
||||
this.writer = writer;
|
||||
this.objectMapper = objectMapper;
|
||||
this.pollIntervalMs = pollIntervalMs;
|
||||
}
|
||||
|
||||
@@ -95,6 +118,10 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
void pollOnce(Integration integration) {
|
||||
writer.createLandingTable(integration.getAccountId(), integration.getTargetClusterIdentifier(),
|
||||
integration.getLandingTableName());
|
||||
if (!integration.isBackfillCompleted()) {
|
||||
pollBackfillPage(integration);
|
||||
return;
|
||||
}
|
||||
String iteratorType = integration.getCheckpointSequenceNumber() == null
|
||||
? "TRIM_HORIZON" : "AFTER_SEQUENCE_NUMBER";
|
||||
String iterator = streamService.getShardIterator(integration.getSourceStreamArn(),
|
||||
@@ -110,6 +137,88 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
integration.setCheckpointSequenceNumber(sequence);
|
||||
}
|
||||
|
||||
private void pollBackfillPage(Integration integration) {
|
||||
RequestScopes.runAs(integration.getAccountId(), () -> {
|
||||
String tableName = extractTableName(integration.getSourceStreamArn());
|
||||
String region = AwsArnUtils.parse(integration.getSourceStreamArn()).region();
|
||||
TableDefinition table = dynamoDbService.describeTable(tableName, region);
|
||||
JsonNode exclusiveStartKey = parseBackfillKey(integration.getBackfillLastEvaluatedKey());
|
||||
|
||||
DynamoDbService.ScanResult result = dynamoDbService.scan(tableName, null, null, null, null,
|
||||
BATCH_SIZE, exclusiveStartKey, region);
|
||||
if (!result.items().isEmpty()) {
|
||||
List<DynamoDbStreamRecord> records = result.items().stream()
|
||||
.map(item -> toBackfillRecord(integration, item, table))
|
||||
.toList();
|
||||
writer.writeBatch(integration.getAccountId(), integration.getTargetClusterIdentifier(),
|
||||
integration.getLandingTableName(), records);
|
||||
}
|
||||
|
||||
boolean completed = result.lastEvaluatedKey() == null;
|
||||
String nextKey = completed ? null : writeAsString(result.lastEvaluatedKey());
|
||||
redshiftService.updateIntegrationBackfillProgress(integration.getAccountId(), integration.getIntegrationArn(),
|
||||
nextKey, completed);
|
||||
integration.setBackfillLastEvaluatedKey(nextKey);
|
||||
integration.setBackfillCompleted(completed);
|
||||
});
|
||||
}
|
||||
|
||||
private DynamoDbStreamRecord toBackfillRecord(Integration integration, JsonNode item, TableDefinition table) {
|
||||
ObjectNode keys = objectMapper.createObjectNode();
|
||||
for (KeySchemaElement keySchemaElement : table.getKeySchema()) {
|
||||
String attributeName = keySchemaElement.getAttributeName();
|
||||
if (item.has(attributeName)) {
|
||||
keys.set(attributeName, item.get(attributeName));
|
||||
}
|
||||
}
|
||||
DynamoDbStreamRecord record = new DynamoDbStreamRecord();
|
||||
record.setEventId("backfill#" + integration.getIntegrationArn() + "#" + sha256Hex(keys.toString()));
|
||||
record.setEventName("INSERT");
|
||||
record.setSequenceNumber("backfill");
|
||||
record.setKeys(keys);
|
||||
record.setNewImage(item);
|
||||
return record;
|
||||
}
|
||||
|
||||
private static String extractTableName(String sourceStreamArn) {
|
||||
String resource = AwsArnUtils.parse(sourceStreamArn).resource();
|
||||
return resource.substring("table/".length(), resource.indexOf("/stream/"));
|
||||
}
|
||||
|
||||
private JsonNode parseBackfillKey(String backfillLastEvaluatedKey) {
|
||||
if (backfillLastEvaluatedKey == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readTree(backfillLastEvaluatedKey);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InternalFailure",
|
||||
"Could not parse a persisted zero-ETL backfill checkpoint.", 500);
|
||||
}
|
||||
}
|
||||
|
||||
private String writeAsString(JsonNode node) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(node);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InternalFailure",
|
||||
"Could not persist a zero-ETL backfill checkpoint.", 500);
|
||||
}
|
||||
}
|
||||
|
||||
private static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder sb = new StringBuilder(digest.length * 2);
|
||||
for (byte b : digest) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
for (String integrationArn : timerIds.keySet()) {
|
||||
stopPolling(integrationArn);
|
||||
|
||||
@@ -371,8 +371,8 @@ public class RedshiftService {
|
||||
integration.setRetryCount(0);
|
||||
integration.setLastError(null);
|
||||
integration.setPollingEnabled(true);
|
||||
// Real integrations pass through creating before settling; nothing here has work to do.
|
||||
integration.setStatus("active");
|
||||
// Floci approximation: report `syncing` while the backfill scan runs, then `active`.
|
||||
integration.setStatus("syncing");
|
||||
integration.setKmsKeyId(kmsKeyId);
|
||||
integration.setCreateTime(DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
|
||||
integration.setDescription(description);
|
||||
@@ -480,6 +480,26 @@ public class RedshiftService {
|
||||
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
|
||||
}
|
||||
|
||||
public synchronized void updateIntegrationBackfillProgress(String accountId, String integrationArn,
|
||||
String backfillLastEvaluatedKey,
|
||||
boolean backfillCompleted) {
|
||||
for (String key : integrations.keysForAccount(accountId)) {
|
||||
Optional<Integration> stored = integrations.getForAccount(accountId, key);
|
||||
if (stored.isEmpty() || !integrationArn.equals(stored.get().getIntegrationArn())) {
|
||||
continue;
|
||||
}
|
||||
Integration integration = stored.get();
|
||||
integration.setBackfillLastEvaluatedKey(backfillLastEvaluatedKey);
|
||||
integration.setBackfillCompleted(backfillCompleted);
|
||||
integration.setRetryCount(0);
|
||||
integration.setLastError(null);
|
||||
integration.setStatus(backfillCompleted ? "active" : "syncing");
|
||||
integrations.putForAccount(accountId, key, integration);
|
||||
return;
|
||||
}
|
||||
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
|
||||
}
|
||||
|
||||
/** One page of integrations plus the marker to continue with, or {@code null} at the end. */
|
||||
public record IntegrationPage(List<Integration> integrations, String marker) {}
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ public class Integration {
|
||||
private String targetClusterIdentifier;
|
||||
private String landingTableName;
|
||||
private String checkpointSequenceNumber;
|
||||
private String backfillLastEvaluatedKey;
|
||||
private boolean backfillCompleted;
|
||||
private int retryCount;
|
||||
private String lastError;
|
||||
private boolean pollingEnabled;
|
||||
@@ -55,6 +57,10 @@ public class Integration {
|
||||
public void setLandingTableName(String landingTableName) { this.landingTableName = landingTableName; }
|
||||
public String getCheckpointSequenceNumber() { return checkpointSequenceNumber; }
|
||||
public void setCheckpointSequenceNumber(String checkpointSequenceNumber) { this.checkpointSequenceNumber = checkpointSequenceNumber; }
|
||||
public String getBackfillLastEvaluatedKey() { return backfillLastEvaluatedKey; }
|
||||
public void setBackfillLastEvaluatedKey(String backfillLastEvaluatedKey) { this.backfillLastEvaluatedKey = backfillLastEvaluatedKey; }
|
||||
public boolean isBackfillCompleted() { return backfillCompleted; }
|
||||
public void setBackfillCompleted(boolean backfillCompleted) { this.backfillCompleted = backfillCompleted; }
|
||||
public int getRetryCount() { return retryCount; }
|
||||
public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
|
||||
public String getLastError() { return lastError; }
|
||||
|
||||
+64
-5
@@ -26,7 +26,42 @@ public final class CopyStatementParser {
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
String nullAs,
|
||||
String iamRoleArn) implements S3Statement {
|
||||
String iamRoleArn,
|
||||
boolean jsonAuto,
|
||||
boolean jsonAutoIgnoreCase,
|
||||
boolean manifest) implements S3Statement {
|
||||
|
||||
public S3CopyFrom(
|
||||
String targetTable,
|
||||
List<String> columns,
|
||||
String bucket,
|
||||
String keyOrPrefix,
|
||||
String delimiter,
|
||||
int headerLines,
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
String nullAs,
|
||||
String iamRoleArn,
|
||||
boolean jsonAuto,
|
||||
boolean manifest) {
|
||||
this(targetTable, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
|
||||
nullAs, iamRoleArn, jsonAuto, false, manifest);
|
||||
}
|
||||
|
||||
public S3CopyFrom(
|
||||
String targetTable,
|
||||
List<String> columns,
|
||||
String bucket,
|
||||
String keyOrPrefix,
|
||||
String delimiter,
|
||||
int headerLines,
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
String nullAs,
|
||||
String iamRoleArn) {
|
||||
this(targetTable, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
|
||||
nullAs, iamRoleArn, false, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
public record S3Unload(
|
||||
@@ -88,6 +123,8 @@ public final class CopyStatementParser {
|
||||
private static final Pattern HEADER_PATTERN = Pattern.compile("(?i)\\bHEADER\\b");
|
||||
private static final Pattern GZIP_PATTERN = Pattern.compile("(?i)\\bGZIP\\b");
|
||||
private static final Pattern CSV_PATTERN = Pattern.compile("(?i)\\b(?:FORMAT\\s+(?:AS\\s+)?)?CSV\\b");
|
||||
private static final Pattern JSON_AUTO_PATTERN = Pattern.compile(
|
||||
"(?i)\\b(?:FORMAT\\s+(?:AS\\s+)?)?JSON(?:\\s+AS)?\\s+['\"]auto(?:\\s+(ignorecase))?['\"]");
|
||||
|
||||
/**
|
||||
* Options this simulator does not implement. A COPY carrying any of these is not intercepted:
|
||||
@@ -95,7 +132,7 @@ public final class CopyStatementParser {
|
||||
* silently loading the data with the wrong framing.
|
||||
*/
|
||||
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
|
||||
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD|MANIFEST|MAXERROR"
|
||||
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD|MAXERROR"
|
||||
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING|REGION|CREDENTIALS"
|
||||
+ "|ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
|
||||
+ "|ACCEPTINVCHARS|ACCEPTANYDATE|BLANKSASNULL|EMPTYASNULL|FILLRECORD|TRIMBLANKS"
|
||||
@@ -329,14 +366,18 @@ public final class CopyStatementParser {
|
||||
|
||||
boolean csv = false;
|
||||
boolean gzip = false;
|
||||
boolean jsonAuto = false;
|
||||
boolean jsonAutoIgnoreCase = false;
|
||||
boolean manifest = false;
|
||||
String nullAs = null;
|
||||
String delimiter = null;
|
||||
int headerLines = 0;
|
||||
|
||||
String iamRoleArn = null;
|
||||
|
||||
boolean seenCsv = false;
|
||||
boolean seenGzip = false;
|
||||
boolean seenJson = false;
|
||||
boolean seenManifest = false;
|
||||
boolean seenNull = false;
|
||||
boolean seenDelimiter = false;
|
||||
boolean seenHeader = false;
|
||||
@@ -344,6 +385,8 @@ public final class CopyStatementParser {
|
||||
|
||||
Matcher csvMatcher = CSV_PATTERN.matcher(options);
|
||||
Matcher gzipMatcher = GZIP_PATTERN.matcher(options);
|
||||
Matcher jsonAutoMatcher = JSON_AUTO_PATTERN.matcher(options);
|
||||
Matcher manifestMatcher = MANIFEST_PATTERN.matcher(options);
|
||||
Matcher ignoreHeaderMatcher = IGNOREHEADER_PATTERN.matcher(options);
|
||||
Matcher headerMatcher = HEADER_PATTERN.matcher(options);
|
||||
Matcher delimiterMatcher = DELIMITER_PATTERN.matcher(options);
|
||||
@@ -361,12 +404,27 @@ public final class CopyStatementParser {
|
||||
}
|
||||
|
||||
if (matchClause(csvMatcher, offset, len)) {
|
||||
if (seenCsv) {
|
||||
if (seenCsv || seenJson) {
|
||||
return null;
|
||||
}
|
||||
seenCsv = true;
|
||||
csv = true;
|
||||
offset = csvMatcher.end();
|
||||
} else if (matchClause(jsonAutoMatcher, offset, len)) {
|
||||
if (seenJson || seenCsv) {
|
||||
return null;
|
||||
}
|
||||
seenJson = true;
|
||||
jsonAuto = true;
|
||||
jsonAutoIgnoreCase = jsonAutoMatcher.group(1) != null;
|
||||
offset = jsonAutoMatcher.end();
|
||||
} else if (matchClause(manifestMatcher, offset, len)) {
|
||||
if (seenManifest) {
|
||||
return null;
|
||||
}
|
||||
seenManifest = true;
|
||||
manifest = true;
|
||||
offset = manifestMatcher.end();
|
||||
} else if (matchClause(gzipMatcher, offset, len)) {
|
||||
if (seenGzip) {
|
||||
return null;
|
||||
@@ -418,7 +476,8 @@ public final class CopyStatementParser {
|
||||
delimiter = csv ? "," : "|";
|
||||
}
|
||||
|
||||
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv, nullAs, iamRoleArn);
|
||||
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
|
||||
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest);
|
||||
}
|
||||
|
||||
private static boolean matchClause(Matcher m, int start, int end) {
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
final class JsonLinesToCsvConverter {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SQLSTATE_INTERNAL = "XX000";
|
||||
|
||||
private JsonLinesToCsvConverter() {
|
||||
}
|
||||
|
||||
static void convert(InputStream in, List<String> targetColumns, OutputStream out) throws IOException {
|
||||
convert(in, targetColumns, out, false);
|
||||
}
|
||||
|
||||
static void convert(InputStream in, List<String> targetColumns, OutputStream out, boolean ignoreCase) throws IOException {
|
||||
if (targetColumns == null || targetColumns.isEmpty()) {
|
||||
// Catalog-based column discovery for FORMAT AS JSON 'auto' only runs over the Simple
|
||||
// Query protocol; over Extended Query the column list is fixed at Parse time, before
|
||||
// any backend round trip is possible. This is the only way targetColumns ever arrives
|
||||
// empty here, so the message names Extended Query directly instead of guessing.
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"COPY ... FORMAT AS JSON 'auto' requires an explicit column list over the "
|
||||
+ "Extended Query protocol; specify columns, or connect with "
|
||||
+ "preferQueryMode=simple to use catalog-based column discovery", null);
|
||||
}
|
||||
|
||||
List<String> lookupColumns = ignoreCase
|
||||
? targetColumns.stream().map(String::toLowerCase).toList()
|
||||
: targetColumns;
|
||||
|
||||
try (JsonParser parser = MAPPER.getFactory().createParser(in)) {
|
||||
while (parser.nextToken() != null) {
|
||||
JsonNode rootNode;
|
||||
try {
|
||||
rootNode = MAPPER.readTree(parser);
|
||||
} catch (IOException e) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"JSON parse error in S3 data: " + e.getMessage(), e);
|
||||
}
|
||||
if (rootNode == null) {
|
||||
continue;
|
||||
}
|
||||
if (!rootNode.isObject()) {
|
||||
String preview = rootNode.toString();
|
||||
if (preview.length() > 60) {
|
||||
preview = preview.substring(0, 60) + "...";
|
||||
}
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"JSON value is not an object: " + preview, null);
|
||||
}
|
||||
|
||||
Map<String, JsonNode> fieldMap = null;
|
||||
if (ignoreCase) {
|
||||
fieldMap = new HashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
fieldMap.put(entry.getKey().toLowerCase(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder csvLine = new StringBuilder();
|
||||
for (int i = 0; i < lookupColumns.size(); i++) {
|
||||
if (i > 0) {
|
||||
csvLine.append(',');
|
||||
}
|
||||
String col = lookupColumns.get(i);
|
||||
JsonNode val = ignoreCase ? fieldMap.get(col) : rootNode.get(col);
|
||||
if (val == null || val.isNull()) {
|
||||
// NULL in Postgres CSV is unquoted empty string
|
||||
continue;
|
||||
}
|
||||
if (val.isNumber() || val.isBoolean()) {
|
||||
csvLine.append(val.asText());
|
||||
} else if (val.isTextual()) {
|
||||
String text = val.asText();
|
||||
if (text.isEmpty()) {
|
||||
csvLine.append("\"\"");
|
||||
} else {
|
||||
csvLine.append(escapeCsv(text));
|
||||
}
|
||||
} else {
|
||||
// Nested Object or Array: serialize as JSON text
|
||||
csvLine.append(escapeCsv(MAPPER.writeValueAsString(val)));
|
||||
}
|
||||
}
|
||||
csvLine.append('\n');
|
||||
byte[] bytes = csvLine.toString().getBytes(StandardCharsets.UTF_8);
|
||||
out.write(bytes);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Throwable cause = e.getCause() != null ? e.getCause() : e;
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"JSON parse error in S3 data: " + cause.getMessage(), cause);
|
||||
}
|
||||
out.flush();
|
||||
}
|
||||
|
||||
static String escapeCsv(String text) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
boolean needsQuotes = text.contains(",") || text.contains("\"") || text.contains("\n") || text.contains("\r");
|
||||
String escaped = text.replace("\"", "\"\"");
|
||||
if (needsQuotes) {
|
||||
return "\"" + escaped + "\"";
|
||||
}
|
||||
return escaped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
final class ManifestReader {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SQLSTATE_INTERNAL = "XX000";
|
||||
|
||||
private ManifestReader() {
|
||||
}
|
||||
|
||||
static List<String> resolveManifestKeys(String bucket, String manifestKey, S3Service s3) {
|
||||
S3Object object = s3.getObject(bucket, manifestKey);
|
||||
if (object == null || object.getData() == null) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"S3 manifest file not found: s3://" + bucket + "/" + manifestKey, null);
|
||||
}
|
||||
JsonNode root;
|
||||
try {
|
||||
root = MAPPER.readTree(new String(object.getData(), StandardCharsets.UTF_8));
|
||||
} catch (IOException e) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"Invalid manifest file format in s3://" + bucket + "/" + manifestKey, e);
|
||||
}
|
||||
JsonNode entries = root.get("entries");
|
||||
if (entries == null || !entries.isArray()) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"Manifest file missing 'entries' array", null);
|
||||
}
|
||||
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (JsonNode entry : entries) {
|
||||
JsonNode urlNode = entry.get("url");
|
||||
if (urlNode == null || !urlNode.isTextual()) {
|
||||
continue;
|
||||
}
|
||||
String url = urlNode.asText();
|
||||
boolean mandatory = entry.has("mandatory") && entry.get("mandatory").asBoolean(false);
|
||||
if (!url.startsWith("s3://")) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"Invalid S3 URL in manifest: " + url, null);
|
||||
}
|
||||
String path = url.substring(5);
|
||||
int slash = path.indexOf('/');
|
||||
if (slash < 0) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"Malformed S3 URL in manifest: " + url, null);
|
||||
}
|
||||
String entryBucket = path.substring(0, slash);
|
||||
String entryKey = path.substring(slash + 1);
|
||||
|
||||
if (!bucket.equals(entryBucket)) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"Cross-bucket manifest entry not supported: " + url, null);
|
||||
}
|
||||
|
||||
if (s3.objectExists(entryBucket, entryKey)) {
|
||||
keys.add(entryKey);
|
||||
} else if (mandatory) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
|
||||
"The specified key does not exist: s3://" + entryBucket + "/" + entryKey, null);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
+190
-34
@@ -28,6 +28,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
@@ -231,11 +232,20 @@ public final class S3CopySimulator {
|
||||
: null;
|
||||
try {
|
||||
try {
|
||||
if (roleSession != null) {
|
||||
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.bucket()));
|
||||
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
|
||||
if (spec.manifest()) {
|
||||
if (roleSession != null) {
|
||||
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), spec.keyOrPrefix()));
|
||||
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), spec.keyOrPrefix());
|
||||
} else {
|
||||
s3.authorizeAnonymousGetObject(spec.bucket(), spec.keyOrPrefix());
|
||||
}
|
||||
} else {
|
||||
s3.authorizeAnonymousListBucket(spec.bucket());
|
||||
if (roleSession != null) {
|
||||
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.bucket()));
|
||||
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
|
||||
} else {
|
||||
s3.authorizeAnonymousListBucket(spec.bucket());
|
||||
}
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
|
||||
@@ -275,11 +285,19 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
static String copyBackendSql(CopyStatementParser.S3CopyFrom spec) {
|
||||
return fabricateCopy(spec);
|
||||
return fabricateCopy(spec, null);
|
||||
}
|
||||
|
||||
static String copyBackendSql(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns) {
|
||||
return fabricateCopy(spec, discoveredColumns);
|
||||
}
|
||||
|
||||
static void streamCopyInput(CopyInput input, OutputStream backendOut) throws IOException {
|
||||
streamObjects(input.spec(), input.s3(), input.iamService(), input.roleSession(), input.keys(), backendOut);
|
||||
streamCopyInput(input, null, backendOut);
|
||||
}
|
||||
|
||||
static void streamCopyInput(CopyInput input, List<String> discoveredColumns, OutputStream backendOut) throws IOException {
|
||||
streamObjects(input.spec(), discoveredColumns, input.s3(), input.iamService(), input.roleSession(), input.keys(), backendOut);
|
||||
}
|
||||
|
||||
static void releaseCopySession(CopyInput input) {
|
||||
@@ -398,8 +416,16 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
try {
|
||||
List<String> discoveredColumns = null;
|
||||
if (spec.jsonAuto() && (spec.columns() == null || spec.columns().isEmpty())) {
|
||||
discoveredColumns = discoverTableColumns(client, backend, spec, txStatus, onStatusChange);
|
||||
if (discoveredColumns == null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
backendOut.write(PostgresWireDecoder.encodeQuery(copyBackendSql(spec)));
|
||||
backendOut.write(PostgresWireDecoder.encodeQuery(copyBackendSql(spec, discoveredColumns)));
|
||||
backendOut.flush();
|
||||
|
||||
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(backend.getInputStream());
|
||||
@@ -432,7 +458,7 @@ public final class S3CopySimulator {
|
||||
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
|
||||
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
|
||||
try {
|
||||
streamCopyInput(input, backendOut);
|
||||
streamCopyInput(input, discoveredColumns, backendOut);
|
||||
writeCopyDone(backendOut);
|
||||
drainToReadyForQuery(backendDecoder, client, onStatusChange);
|
||||
} catch (RuntimeException | IOException e) {
|
||||
@@ -461,6 +487,9 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
private static List<String> resolveKeys(CopyStatementParser.S3CopyFrom spec, S3Service s3) {
|
||||
if (spec.manifest()) {
|
||||
return ManifestReader.resolveManifestKeys(spec.bucket(), spec.keyOrPrefix(), s3);
|
||||
}
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (s3.objectExists(spec.bucket(), spec.keyOrPrefix())) {
|
||||
keys.add(spec.keyOrPrefix());
|
||||
@@ -482,13 +511,22 @@ public final class S3CopySimulator {
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static String fabricateCopy(CopyStatementParser.S3CopyFrom spec) {
|
||||
private static String fabricateCopy(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns) {
|
||||
StringBuilder sql = new StringBuilder("COPY ").append(spec.targetTable());
|
||||
if (spec.columns() != null && !spec.columns().isEmpty()) {
|
||||
sql.append(" (").append(String.join(", ", spec.columns())).append(")");
|
||||
if (discoveredColumns != null && !discoveredColumns.isEmpty()) {
|
||||
sql.append(" (")
|
||||
.append(discoveredColumns.stream()
|
||||
.map(c -> "\"" + c.replace("\"", "\"\"") + "\"")
|
||||
.collect(Collectors.joining(", ")))
|
||||
.append(")");
|
||||
} else if (spec.columns() != null && !spec.columns().isEmpty()) {
|
||||
sql.append(" (")
|
||||
.append(String.join(", ", spec.columns()))
|
||||
.append(")");
|
||||
}
|
||||
sql.append(" FROM STDIN WITH (FORMAT ").append(spec.csv() ? "csv" : "text");
|
||||
String delimiter = spec.delimiter() != null ? spec.delimiter() : (spec.csv() ? "," : "|");
|
||||
boolean csv = spec.csv() || spec.jsonAuto();
|
||||
sql.append(" FROM STDIN WITH (FORMAT ").append(csv ? "csv" : "text");
|
||||
String delimiter = spec.jsonAuto() ? "," : (spec.delimiter() != null ? spec.delimiter() : (csv ? "," : "|"));
|
||||
sql.append(", DELIMITER '").append(quoteLiteral(delimiter)).append("'");
|
||||
if (spec.nullAs() != null) {
|
||||
sql.append(", NULL '").append(quoteLiteral(spec.nullAs())).append("'");
|
||||
@@ -497,6 +535,14 @@ public final class S3CopySimulator {
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
private static String unquoteIdentifier(String identifier) {
|
||||
if (identifier != null && identifier.length() >= 2
|
||||
&& identifier.startsWith("\"") && identifier.endsWith("\"")) {
|
||||
return identifier.substring(1, identifier.length() - 1).replace("\"\"", "\"");
|
||||
}
|
||||
return identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a value for a single-quoted SQL string literal. PostgreSQL defaults to
|
||||
* {@code standard_conforming_strings = on}, where a backslash is an ordinary character, so only
|
||||
@@ -506,42 +552,152 @@ public final class S3CopySimulator {
|
||||
return value.replace("'", "''");
|
||||
}
|
||||
|
||||
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, S3Service s3,
|
||||
IamService iamService, RoleSession roleSession,
|
||||
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns,
|
||||
S3Service s3, IamService iamService, RoleSession roleSession,
|
||||
List<String> keys, OutputStream backendOut) throws IOException {
|
||||
byte[] buffer = new byte[CHUNK];
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
if (roleSession != null) {
|
||||
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), keys.get(i)));
|
||||
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), keys.get(i));
|
||||
} else {
|
||||
s3.authorizeAnonymousGetObject(spec.bucket(), keys.get(i));
|
||||
}
|
||||
S3Object object = s3.getObject(spec.bucket(), keys.get(i));
|
||||
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
|
||||
InputStream in = new ByteArrayInputStream(data);
|
||||
if (spec.gzip()) {
|
||||
in = new GZIPInputStream(in);
|
||||
}
|
||||
if (i == 0 && spec.headerLines() > 0) {
|
||||
skipLines(in, spec.headerLines());
|
||||
}
|
||||
int read;
|
||||
boolean endsWithNewline = false;
|
||||
boolean hasData = false;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
if (read > 0) {
|
||||
hasData = true;
|
||||
endsWithNewline = (buffer[read - 1] == '\n');
|
||||
writeCopyData(backendOut, buffer, read);
|
||||
InputStream rawIn = new ByteArrayInputStream(data);
|
||||
try (InputStream in = spec.gzip() ? new GZIPInputStream(rawIn) : rawIn) {
|
||||
if (spec.jsonAuto()) {
|
||||
List<String> targetCols = (discoveredColumns != null && !discoveredColumns.isEmpty())
|
||||
? discoveredColumns
|
||||
: (spec.columns() != null
|
||||
? spec.columns().stream().map(S3CopySimulator::unquoteIdentifier).toList()
|
||||
: List.of());
|
||||
CopyDataOutputStream copyDataOut = new CopyDataOutputStream(backendOut);
|
||||
JsonLinesToCsvConverter.convert(in, targetCols, copyDataOut, spec.jsonAutoIgnoreCase());
|
||||
copyDataOut.flush();
|
||||
} else {
|
||||
if (i == 0 && spec.headerLines() > 0) {
|
||||
skipLines(in, spec.headerLines());
|
||||
}
|
||||
int read;
|
||||
boolean endsWithNewline = false;
|
||||
boolean hasData = false;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
if (read > 0) {
|
||||
hasData = true;
|
||||
endsWithNewline = (buffer[read - 1] == '\n');
|
||||
writeCopyData(backendOut, buffer, read);
|
||||
}
|
||||
}
|
||||
if (hasData && !endsWithNewline) {
|
||||
writeCopyData(backendOut, new byte[]{'\n'}, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
if (hasData && !endsWithNewline) {
|
||||
writeCopyData(backendOut, new byte[]{'\n'}, 1);
|
||||
}
|
||||
}
|
||||
backendOut.flush();
|
||||
}
|
||||
|
||||
private static List<String> discoverTableColumns(Socket client, Socket backend,
|
||||
CopyStatementParser.S3CopyFrom spec,
|
||||
char txStatus, IntConsumer onStatusChange) throws IOException {
|
||||
String query = "SELECT a.attname FROM pg_catalog.pg_attribute a "
|
||||
+ "WHERE a.attrelid = to_regclass('" + quoteLiteral(spec.targetTable()) + "') "
|
||||
+ "AND a.attnum > 0 AND NOT a.attisdropped "
|
||||
+ "ORDER BY a.attnum";
|
||||
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
backendOut.write(PostgresWireDecoder.encodeQuery(query));
|
||||
backendOut.flush();
|
||||
|
||||
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(backend.getInputStream());
|
||||
List<String> cols = new ArrayList<>();
|
||||
PostgresWireDecoder.FrontendMessage msg;
|
||||
while ((msg = backendDecoder.nextMessage()) != null) {
|
||||
char type = msg.type();
|
||||
if (type == 'D') {
|
||||
byte[] body = msg.body();
|
||||
if (body.length >= 6) {
|
||||
int colCount = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
|
||||
if (colCount >= 1) {
|
||||
int colLen = ((body[2] & 0xFF) << 24) | ((body[3] & 0xFF) << 16)
|
||||
| ((body[4] & 0xFF) << 8) | (body[5] & 0xFF);
|
||||
if (colLen > 0 && 6 + colLen <= body.length) {
|
||||
cols.add(new String(body, 6, colLen, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (type == 'E') {
|
||||
forward(client, msg);
|
||||
drainToReadyForQuery(backendDecoder, client, onStatusChange);
|
||||
return null;
|
||||
} else if (type == 'N' || type == 'A' || type == 'S') {
|
||||
forward(client, msg);
|
||||
} else if (type == 'Z') {
|
||||
if (onStatusChange != null && msg.body().length > 0) {
|
||||
onStatusChange.accept(msg.body()[0]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (cols.isEmpty()) {
|
||||
sendError(client, backend, "42P01",
|
||||
"relation \"" + spec.targetTable() + "\" does not exist or has no user columns",
|
||||
txStatus, onStatusChange);
|
||||
return null;
|
||||
}
|
||||
return cols;
|
||||
}
|
||||
|
||||
private static final class CopyDataOutputStream extends OutputStream {
|
||||
private final OutputStream backendOut;
|
||||
private final byte[] chunkBuf = new byte[CHUNK];
|
||||
private int count = 0;
|
||||
|
||||
CopyDataOutputStream(OutputStream backendOut) {
|
||||
this.backendOut = backendOut;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
chunkBuf[count++] = (byte) b;
|
||||
if (count == chunkBuf.length) {
|
||||
flushChunk();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
int remaining = len;
|
||||
int offset = off;
|
||||
while (remaining > 0) {
|
||||
int space = chunkBuf.length - count;
|
||||
int toCopy = Math.min(remaining, space);
|
||||
System.arraycopy(b, offset, chunkBuf, count, toCopy);
|
||||
count += toCopy;
|
||||
offset += toCopy;
|
||||
remaining -= toCopy;
|
||||
if (count == chunkBuf.length) {
|
||||
flushChunk();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void flushChunk() throws IOException {
|
||||
if (count > 0) {
|
||||
writeCopyData(backendOut, chunkBuf, count);
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException {
|
||||
flushChunk();
|
||||
backendOut.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private static void skipLines(InputStream in, int lines) throws IOException {
|
||||
int seen = 0;
|
||||
int b;
|
||||
|
||||
Reference in new issue
Block a user