feat(redshift-data): support client token idempotency (#6343)

* feat: support Redshift Data API client token idempotency

* test: verify Redshift Data API retry compatibility

* fix: address Redshift Data admission and cleanup races

* refactor(redshift-data): remove implicit in-memory receipt constructor
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-23 14:36:33 -04:00
1 parent 4093694451
commit 38c641ec7e
18 files changed
+1637 -33

No files matched your search

@@ -438,6 +438,17 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
delegate.delete(accountId + "/" + key);
}
@Override
public void deleteAllAtomically(Set<String> keys) {
deleteAllAtomicallyForAccounts(Map.of(prefix(), keys));
}
public void deleteAllAtomicallyForAccounts(Map<String, Set<String>> keysByAccount) {
Set<String> rawKeys = new LinkedHashSet<>();
keysByAccount.forEach((account, keys) -> keys.forEach(key -> rawKeys.add(account + "/" + key)));
delegate.deleteAllAtomically(rawKeys);
}
// --- Entry writes, for map-valued stores whose backend persists one entry at a time ---
/** Whether the backend persists one map entry at a time; the entry methods require it. */
@@ -72,6 +72,17 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
dirty.set(true);
}
@Override
public synchronized void deleteAllAtomically(Set<K> keys) {
if (keys.isEmpty()) {
return;
}
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
candidate.keySet().removeAll(Set.copyOf(keys));
store = candidate;
dirty.set(true);
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
return store.entrySet().stream()
@@ -38,6 +38,16 @@ public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
store.remove(key);
}
@Override
public synchronized void deleteAllAtomically(Set<K> keys) {
if (keys.isEmpty()) {
return;
}
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
candidate.keySet().removeAll(Set.copyOf(keys));
store = candidate;
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
List<V> result = new ArrayList<>();
@@ -85,6 +85,21 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
persistToDisk();
}
@Override
public synchronized void deleteAllAtomically(Set<K> keys) {
if (keys.isEmpty()) {
return;
}
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
candidate.keySet().removeAll(Set.copyOf(keys));
try {
StorageFiles.writeAtomically(filePath, tempFile -> objectMapper.writeValue(tempFile.toFile(), candidate));
} catch (IOException exception) {
throw new UncheckedIOException("Failed to commit atomic deletions to " + filePath, exception);
}
store = candidate;
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
return store.entrySet().stream()
@@ -39,6 +39,11 @@ public interface StorageBackend<K, V> {
void delete(K key);
/** Remove keys as one storage commit, with the same durability guarantees as atomic puts. */
default void deleteAllAtomically(Set<K> keys) {
throw new UnsupportedOperationException("Atomic deletions are not supported by this backend");
}
/**
* Return a new mutable list of values whose keys pass the filter. Callers may sort,
* filter, or otherwise mutate the returned list without affecting the underlying store.
@@ -43,6 +43,7 @@ import java.util.stream.Collectors;
* PUT: [0x01] [4-byte key length] [key bytes] [4-byte value length] [value bytes]
* DELETE: [0x02] [4-byte key length] [key bytes]
* BATCH: [0x03] [4-byte map length] [CBOR map bytes]
* DELETE_BATCH: [0x04] [4-byte array length] [CBOR key array bytes]
*
* Key and value bytes are serialized via Jackson CBOR (compact binary format).
* Snapshot files use indented JSON for debuggability.
@@ -54,6 +55,7 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
static final byte OP_PUT = 0x01;
static final byte OP_DELETE = 0x02;
static final byte OP_BATCH = 0x03;
static final byte OP_DELETE_BATCH = 0x04;
private volatile ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
private final Path snapshotPath;
@@ -130,6 +132,25 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
} catch (IOException exception) {
throw new UncheckedIOException("Failed to encode atomic WAL batch", exception);
}
commitBatch(OP_BATCH, payload, replacements, Set.of());
}
@Override
public void deleteAllAtomically(Set<K> keys) {
Set<K> deletions = Set.copyOf(keys);
if (deletions.isEmpty()) {
return;
}
byte[] payload;
try {
payload = walMapper.writeValueAsBytes(deletions);
} catch (IOException exception) {
throw new UncheckedIOException("Failed to encode atomic WAL deletions", exception);
}
commitBatch(OP_DELETE_BATCH, payload, Map.of(), deletions);
}
private void commitBatch(byte operation, byte[] payload, Map<K, V> replacements, Set<K> deletions) {
compactionLock.writeLock().lock();
try {
if (walWriter == null) {
@@ -137,13 +158,14 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
}
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
candidate.putAll(replacements);
candidate.keySet().removeAll(deletions);
walWriter.flush();
FileChannel channel = FileChannel.open(walPath, StandardOpenOption.WRITE);
try {
long offset = channel.size();
channel.position(offset);
ByteBuffer record = ByteBuffer.allocate(1 + Integer.BYTES + payload.length);
record.put(OP_BATCH).putInt(payload.length).put(payload).flip();
record.put(operation).putInt(payload.length).put(payload).flip();
try {
while (record.hasRemaining()) {
channel.write(record);
@@ -417,6 +439,14 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
break;
}
store.putAll(batch);
} else if (op == OP_DELETE_BATCH) {
List<K> keys = walMapper.readValue(keyBytes, walMapper.getTypeFactory().constructCollectionType(
List.class, walMapper.constructType(typeReference.getType()).getKeyType()));
if (keys == null || keys.stream().anyMatch(key -> key == null)) {
LOG.warnv("Invalid WAL deletion batch at offset {0} in {1}, stopping replay", consumed, walPath);
break;
}
keys.forEach(store::remove);
} else if (op == OP_PUT) {
byte[] valueBytes = readFrame(in, fileSize - consumed - recordLength);
if (valueBytes == null) {
@@ -14,12 +14,15 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
@ApplicationScoped
class RedshiftDataExecutor implements AutoCloseable {
@@ -65,8 +68,9 @@ class RedshiftDataExecutor implements AutoCloseable {
}
/**
* Admits a statement. {@code admit} runs under the reset read lock, so a reset cannot slip
* between persisting the statement and registering its execution. {@code onFailure} runs when
* Reserves queue capacity before {@code admit} writes any state. The worker waits for admission
* to succeed. {@code admit} runs under the reset read lock, so reset cannot split admission.
* {@code onFailure} runs when
* the worker dies with an unexpected exception, so the statement can still reach a terminal state.
*/
RedshiftDataExecution submit(String account, String region, String id, Runnable admit,
@@ -79,7 +83,25 @@ class RedshiftDataExecutor implements AutoCloseable {
}
String key = account + ":" + id;
RedshiftDataExecution execution = new RedshiftDataExecution(generation);
CountDownLatch ready = new CountDownLatch(1);
AtomicBoolean admitted = new AtomicBoolean();
AtomicBoolean claimed = new AtomicBoolean();
Runnable task = () -> {
if (closed && ready.getCount() != 0) {
return;
}
try {
ready.await();
} catch (InterruptedException expected) {
// The admitting thread completes a pending reservation after shutdown interrupts its worker.
Thread.currentThread().interrupt();
if (ready.getCount() != 0) {
return;
}
}
if (!admitted.get() || !claimed.compareAndSet(false, true)) {
return;
}
try {
RequestScopes.runAs(account, region, () -> work.accept(execution));
} catch (RuntimeException failure) {
@@ -93,7 +115,6 @@ class RedshiftDataExecutor implements AutoCloseable {
}
};
execution.task(task);
admit.run();
synchronized (this) {
executions.put(key, execution);
}
@@ -105,12 +126,45 @@ class RedshiftDataExecutor implements AutoCloseable {
}
throw new AwsException("ActiveStatementsExceededException", "Too many active statements", 400);
}
try {
admit.run();
admitted.set(true);
} catch (RuntimeException | Error failure) {
workers.remove(task);
synchronized (this) {
executions.remove(key, execution);
}
execution.completed();
throw failure;
} finally {
boolean finishAfterShutdown;
synchronized (this) {
finishAfterShutdown = closed && admitted.get();
if (finishAfterShutdown) {
execution.requestCancellation();
}
ready.countDown();
}
if (finishAfterShutdown) {
Thread.startVirtualThread(task);
}
}
return execution;
} finally {
resetLock.readLock().unlock();
}
}
/** Keeps receipt lookup, admission and rejected-admission cleanup in one reset generation. */
<T> T admitting(Supplier<T> admission) {
resetLock.readLock().lock();
try {
return admission.get();
} finally {
resetLock.readLock().unlock();
}
}
private static void recover(RedshiftDataExecution execution, RuntimeException failure,
BiConsumer<RedshiftDataExecution, RuntimeException> onFailure,
String id, String account, String region) {
@@ -121,6 +175,10 @@ class RedshiftDataExecutor implements AutoCloseable {
}
}
synchronized RedshiftDataExecution execution(String account, String id) {
return executions.get(account + ":" + id);
}
boolean cancel(String account, String id) {
RedshiftDataExecution execution;
synchronized (this) {
@@ -173,12 +231,12 @@ class RedshiftDataExecutor implements AutoCloseable {
}
void clear(Runnable clearStorage) {
List<RedshiftDataExecution> active;
List<RedshiftDataExecution> active = new ArrayList<>();
resetLock.writeLock().lock();
try {
generation++;
synchronized (this) {
active = new ArrayList<>(executions.values());
active.addAll(executions.values());
executions.clear();
}
for (RedshiftDataExecution execution : active) {
@@ -187,13 +245,13 @@ class RedshiftDataExecutor implements AutoCloseable {
clearStorage.run();
} finally {
resetLock.writeLock().unlock();
}
for (RedshiftDataExecution execution : active) {
if (execution.requestCancellation()) {
Thread.startVirtualThread(execution::signalCancellation);
}
if (workers.remove(execution.task())) {
execution.completed();
for (RedshiftDataExecution execution : active) {
if (execution.requestCancellation()) {
Thread.startVirtualThread(execution::signalCancellation);
}
if (workers.remove(execution.task())) {
execution.completed();
}
}
}
}
@@ -0,0 +1,149 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@ApplicationScoped
class RedshiftDataIdempotencyStore {
private static final Duration TOKEN_TTL = Duration.ofHours(8);
private final AccountAwareStorageBackend<Receipt> receipts;
private final Clock clock;
private final ReentrantReadWriteLock mutations = new ReentrantReadWriteLock();
@Inject
RedshiftDataIdempotencyStore(StorageFactory factory) {
this(factory.create("redshift-data", "idempotency.json", new TypeReference<Map<String, Receipt>>() { }),
Clock.systemUTC());
}
RedshiftDataIdempotencyStore(AccountAwareStorageBackend<Receipt> receipts, Clock clock) {
this.receipts = receipts;
this.clock = clock;
}
static String clientToken(JsonNode request) {
JsonNode token = request.get("ClientToken");
if (token == null) {
return null;
}
if (!token.isTextual() || token.textValue().isEmpty() || token.textValue().length() > 64) {
throw new AwsException("ValidationException", "ClientToken must be a string between 1 and 64 characters", 400);
}
return token.textValue();
}
Receipt find(Scope scope) {
Receipt receipt = receipts.getForAccount(scope.accountId(), scope.key()).orElse(null);
if (receipt != null && !clock.instant().isBefore(receipt.expiresAt)) {
return null;
}
return receipt == null ? null : receipt.snapshot();
}
void put(Scope scope, ObjectNode response) {
Receipt receipt = new Receipt();
receipt.acceptedAt = clock.instant();
receipt.expiresAt = receipt.acceptedAt.plus(TOKEN_TTL);
receipt.response = response.deepCopy();
mutations.readLock().lock();
try {
receipts.putAllAtomicallyForAccount(scope.accountId(), Map.of(scope.key(), receipt));
} finally {
mutations.readLock().unlock();
}
}
void removeIfStatement(Scope scope, String statementId) {
mutations.writeLock().lock();
try {
Receipt receipt = receipts.getForAccount(scope.accountId(), scope.key()).orElse(null);
if (receipt != null && statementId.equals(receipt.response.path("Id").asText())) {
receipts.deleteAllAtomicallyForAccounts(Map.of(scope.accountId(), Set.of(scope.key())));
}
} finally {
mutations.writeLock().unlock();
}
}
void clear() {
mutations.writeLock().lock();
try {
Map<String, Set<String>> keys = new LinkedHashMap<>();
for (AccountAwareStorageBackend.AccountEntry<Receipt> entry : receipts.scanAllAccountEntries(key -> true)) {
keys.computeIfAbsent(entry.accountId(), ignored -> new LinkedHashSet<>()).add(entry.key());
}
receipts.deleteAllAtomicallyForAccounts(keys);
} finally {
mutations.writeLock().unlock();
}
}
void sweep() {
Instant now = clock.instant();
List<AccountAwareStorageBackend.AccountEntry<Receipt>> expired = receipts.scanAllAccountEntries(key -> true).stream()
.filter(entry -> !now.isBefore(entry.value().expiresAt)).toList();
if (expired.isEmpty()) {
return;
}
mutations.writeLock().lock();
try {
Map<String, Set<String>> keys = new LinkedHashMap<>();
for (AccountAwareStorageBackend.AccountEntry<Receipt> entry : expired) {
Receipt current = receipts.getForAccount(entry.accountId(), entry.key()).orElse(null);
if (current == entry.value()) {
keys.computeIfAbsent(entry.accountId(), ignored -> new LinkedHashSet<>()).add(entry.key());
}
}
receipts.deleteAllAtomicallyForAccounts(keys);
} finally {
mutations.writeLock().unlock();
}
}
record Scope(String accountId, String region, String operation, String token) {
String key() {
return encode(region) + "." + encode(operation) + "." + encode(token);
}
private static String encode(String value) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
}
}
@RegisterForReflection
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
static final class Receipt {
Instant acceptedAt;
Instant expiresAt;
ObjectNode response;
Receipt snapshot() {
Receipt copy = new Receipt();
copy.acceptedAt = acceptedAt;
copy.expiresAt = expiresAt;
copy.response = response.deepCopy();
return copy;
}
}
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
@@ -24,6 +25,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
@@ -32,6 +34,8 @@ import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.regex.Pattern;
@@ -54,18 +58,22 @@ public class RedshiftDataService implements Resettable {
private final RedshiftDataEventPublisher publisher;
private final RequestContext requestContext;
private final IamService iamService;
private final RedshiftDataIdempotencyStore idempotency;
private final ConcurrentHashMap<RedshiftDataIdempotencyStore.Scope, AdmissionLock> admissionLocks = new ConcurrentHashMap<>();
RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher) {
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher, null, null);
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher, null,
null, new RedshiftDataIdempotencyStore(AccountAwareStorageBackend.inMemory("000000000000"),
Clock.systemUTC()));
}
@Inject
public RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
RequestContext requestContext, IamService iamService) {
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency) {
this.resolver = resolver;
this.connectionFactory = connectionFactory;
this.store = store;
@@ -75,11 +83,31 @@ public class RedshiftDataService implements Resettable {
this.publisher = publisher;
this.requestContext = requestContext;
this.iamService = iamService;
this.idempotency = idempotency;
}
@Override
public void clear() {
executor.clear(store::clear);
executor.clear(() -> {
RuntimeException failure = null;
try {
store.clear();
} catch (RuntimeException storageFailure) {
failure = storageFailure;
}
try {
idempotency.clear();
} catch (RuntimeException receiptFailure) {
if (failure == null) {
failure = receiptFailure;
} else {
failure.addSuppressed(receiptFailure);
}
}
if (failure != null) {
throw failure;
}
});
}
// ── ExecuteStatement ────────────────────────────────────────────────────
@@ -89,11 +117,58 @@ public class RedshiftDataService implements Resettable {
}
public ObjectNode executeStatement(JsonNode request, String region, String principal) {
int waitSeconds = waitSeconds(request);
return submit(prepareStatement(request, region), waitSeconds, principal);
return execute(request, region, principal, false);
}
private ObjectNode submit(PendingStatement pending, int waitSeconds, String principal) {
private ObjectNode execute(JsonNode request, String region, String principal, boolean batch) {
String token = RedshiftDataIdempotencyStore.clientToken(request);
int waitSeconds = waitSeconds(request);
PendingStatement pending = batch ? prepareBatch(request, region) : prepareStatement(request, region);
RedshiftDataStatementStore.StoredStatement stored = pending.statement();
RedshiftDataIdempotencyStore.Scope scope = token == null ? null : new RedshiftDataIdempotencyStore.Scope(
stored.accountId, region, batch ? "BatchExecuteStatement" : "ExecuteStatement", token);
Admission admission = executor.admitting(() -> scope == null ? submit(pending, principal, null)
: admitScoped(pending, principal, scope));
if (waitSeconds > 0 && admission.execution() != null) {
admission.execution().await(Duration.ofSeconds(waitSeconds));
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(admission.accountId(), admission.id());
if (current != null) {
return executeResponse(current);
}
}
return admission.response();
}
private record Admission(String accountId, String id, ObjectNode response, RedshiftDataExecution execution) { }
private static final class AdmissionLock {
private final ReentrantLock lock = new ReentrantLock();
private int users;
}
private Admission admitScoped(PendingStatement pending, String principal, RedshiftDataIdempotencyStore.Scope scope) {
AdmissionLock scoped = admissionLocks.compute(scope, (key, existing) -> {
AdmissionLock selected = existing == null ? new AdmissionLock() : existing;
selected.users++;
return selected;
});
scoped.lock.lock();
try {
RedshiftDataIdempotencyStore.Receipt receipt = idempotency.find(scope);
if (receipt == null) {
return submit(pending, principal, scope);
}
String id = receipt.response.path("Id").asText();
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(scope.accountId(), id);
return new Admission(scope.accountId(), id, current == null ? receipt.response : executeResponse(current),
executor.execution(scope.accountId(), id));
} finally {
scoped.lock.unlock();
admissionLocks.compute(scope, (key, existing) -> --scoped.users == 0 ? null : scoped);
}
}
private Admission submit(PendingStatement pending, String principal, RedshiftDataIdempotencyStore.Scope scope) {
RedshiftDataStatementStore.StoredStatement stored = pending.statement();
if (principal != null) {
stored.principal = principal;
@@ -102,7 +177,14 @@ public class RedshiftDataService implements Resettable {
RedshiftDataExecution handle;
try {
handle = executor.submit(stored.accountId, stored.region, stored.id,
() -> store.putForAccount(stored.accountId, stored),
() -> {
if (scope == null) {
store.putForAccount(stored.accountId, stored);
} else {
store.admitForAccount(stored.accountId, stored);
idempotency.put(scope, response);
}
},
execution -> {
try {
execution.checkCancellation();
@@ -116,18 +198,22 @@ public class RedshiftDataService implements Resettable {
complete(stored, execution);
},
(execution, failure) -> recoverStatement(stored, execution, failure));
} catch (AwsException failure) {
store.deleteForAccount(stored.accountId, stored.id);
} catch (RuntimeException failure) {
try {
if (scope != null) {
idempotency.removeIfStatement(scope, stored.id);
}
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
try {
store.deleteForAccount(stored.accountId, stored.id);
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
throw failure;
}
if (waitSeconds > 0) {
handle.await(Duration.ofSeconds(waitSeconds));
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(stored.accountId, stored.id);
if (current != null) {
return executeResponse(current);
}
}
return response;
return new Admission(stored.accountId, stored.id, response, handle);
}
private void complete(RedshiftDataStatementStore.StoredStatement stored, RedshiftDataExecution execution) {
@@ -477,8 +563,7 @@ public class RedshiftDataService implements Resettable {
}
public ObjectNode batchExecuteStatement(JsonNode request, String region, String principal) {
int waitSeconds = waitSeconds(request);
return submit(prepareBatch(request, region), waitSeconds, principal);
return execute(request, region, principal, true);
}
private PendingStatement prepareBatch(JsonNode request, String region) {
@@ -42,22 +42,25 @@ class RedshiftDataStatementStore {
private final AccountAwareStorageBackend<StoredStatement> statements;
private final Duration ttl;
private final Clock clock;
private final RedshiftDataIdempotencyStore idempotency;
// Created by the CDI lifecycle in start(); the test constructor never starts it, so unit
// tests that build the store directly drive sweep() by hand and spawn no background thread.
private ScheduledExecutorService sweeper;
@Inject
RedshiftDataStatementStore(StorageFactory storageFactory, EmulatorConfig config) {
RedshiftDataStatementStore(StorageFactory storageFactory, EmulatorConfig config, RedshiftDataIdempotencyStore idempotency) {
this.statements = storageFactory.create("redshift-data", "statements.json",
new TypeReference<Map<String, StoredStatement>>() {});
this.ttl = Duration.ofHours(Math.max(1, config.services().redshiftData().resultTtlHours()));
this.clock = Clock.systemUTC();
this.idempotency = idempotency;
}
RedshiftDataStatementStore(int resultTtlHours, Clock clock) {
this.statements = AccountAwareStorageBackend.inMemory("000000000000");
this.ttl = Duration.ofHours(Math.max(1, resultTtlHours));
this.clock = clock;
this.idempotency = null;
}
@PostConstruct
@@ -95,10 +98,18 @@ class RedshiftDataStatementStore {
statements.putForAccount(accountId, statement.id, statement.snapshot());
}
void admitForAccount(String accountId, StoredStatement statement) {
statements.putAllAtomicallyForAccount(accountId, Map.of(statement.id, statement.snapshot()));
}
void deleteForAccount(String accountId, String id) {
statements.deleteForAccount(accountId, id);
}
void flush() {
statements.flush();
}
Instant expiresAt(Instant createdAt) {
return createdAt.plus(ttl);
}
@@ -120,6 +131,9 @@ class RedshiftDataStatementStore {
}
void sweep() {
if (idempotency != null) {
idempotency.sweep();
}
Instant cutoff = Instant.now(clock).minus(ttl);
// The sweep thread has no request context, so it iterates every account's partition
// and deletes per account rather than through the current-account view.