mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
refactor(dynamodb): scope runtime work to the selected backend (#4401)
Add DynamoDbRuntime and a DynamoDbBackendLifecycle seam so the emulator lifecycle starts, resets and stops only the selected backend. Native start initializes the engine before persisted stream consumers and schedules the TTL sweep, which never ran because its bean was unused. Reset gains a checkReset preflight that runs before anything is stopped or cleared, and native reset now drops streams, item caches, idempotency tokens and forwarder queues. Reset also pauses the TTL sweep and waits out in-flight zero-ETL writes before Floci storage is cleared. Shutdown stops the Lambda DynamoDB poller, the Redshift zero-ETL consumer and the Kinesis forwarding drains before the final flush, and the Redshift consumer is now Resettable.
This commit is contained in:
1 parent
5cb973c561
commit
d658c75a41
29 files changed
+1174
-64
No files matched your search
@@ -7,6 +7,12 @@ package io.github.hectorvent.floci.core.common;
|
||||
* controller never holds StorageFactory's monitor while invoking them.
|
||||
*/
|
||||
public interface Resettable {
|
||||
/**
|
||||
* Throw to refuse an emulator-wide reset. Runs on every service before anything is stopped or
|
||||
* cleared, so a refusal leaves all state intact.
|
||||
*/
|
||||
default void checkReset() {}
|
||||
|
||||
/** Stop accepting work and drain active writes before any storage is cleared. */
|
||||
default void beforeReset() {}
|
||||
|
||||
|
||||
@@ -156,17 +156,21 @@ public class EmulatorInfoController {
|
||||
}
|
||||
|
||||
private synchronized void performReset() {
|
||||
// Containers first: they are tracked independently of StorageBackend, so this can run
|
||||
// in any order relative to the storage wipe below, but stopping them here means a
|
||||
// client's reset actually reflects a clean slate instead of leaving Batch, CodeBuild,
|
||||
// or SageMaker containers running with no record of them left in the store.
|
||||
ContainerTeardowns.stopAll(containerTeardowns, LOG);
|
||||
// Resolve live instances before taking any storage locks. Serialize resets so one reset
|
||||
// cannot resume a publisher while another is still wiping its storage.
|
||||
List<Resettable> services = new ArrayList<>();
|
||||
for (Resettable service : resettables) {
|
||||
services.add(service);
|
||||
}
|
||||
// Every service may refuse before the first destructive step, so a refusal changes nothing.
|
||||
for (Resettable service : services) {
|
||||
service.checkReset();
|
||||
}
|
||||
// Containers next: they are tracked independently of StorageBackend, so this can run
|
||||
// in any order relative to the storage wipe below, but stopping them here means a
|
||||
// client's reset actually reflects a clean slate instead of leaving Batch, CodeBuild,
|
||||
// or SageMaker containers running with no record of them left in the store.
|
||||
ContainerTeardowns.stopAll(containerTeardowns, LOG);
|
||||
RuntimeException failure = null;
|
||||
try {
|
||||
for (Resettable service : services) {
|
||||
|
||||
@@ -21,6 +21,7 @@ import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheCont
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbRuntime;
|
||||
import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;
|
||||
@@ -36,6 +37,7 @@ import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerM
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftDynamoDbZeroEtlConsumer;
|
||||
import io.github.hectorvent.floci.services.timestreaminfluxdb.TimestreamInfluxDbService;
|
||||
import io.quarkus.runtime.Quarkus;
|
||||
import io.quarkus.runtime.ShutdownDelayInitiatedEvent;
|
||||
@@ -106,6 +108,8 @@ public class EmulatorLifecycle {
|
||||
private final StepFunctionsService stepFunctionsService;
|
||||
private final Instance<ContainerTeardown> containerTeardowns;
|
||||
private final PersistentPathValidator persistentPathValidator;
|
||||
private final DynamoDbRuntime dynamoDbRuntime;
|
||||
private final RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer;
|
||||
|
||||
@Inject
|
||||
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
|
||||
@@ -142,7 +146,9 @@ public class EmulatorLifecycle {
|
||||
SchemaCreationWorker schemaCreationWorker,
|
||||
StepFunctionsService stepFunctionsService,
|
||||
Instance<ContainerTeardown> containerTeardowns,
|
||||
PersistentPathValidator persistentPathValidator) {
|
||||
PersistentPathValidator persistentPathValidator,
|
||||
DynamoDbRuntime dynamoDbRuntime,
|
||||
RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer) {
|
||||
this.storageFactory = storageFactory;
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
this.config = config;
|
||||
@@ -179,6 +185,8 @@ public class EmulatorLifecycle {
|
||||
this.stepFunctionsService = stepFunctionsService;
|
||||
this.containerTeardowns = containerTeardowns;
|
||||
this.persistentPathValidator = persistentPathValidator;
|
||||
this.dynamoDbRuntime = dynamoDbRuntime;
|
||||
this.redshiftZeroEtlConsumer = redshiftZeroEtlConsumer;
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent ignored) {
|
||||
@@ -224,10 +232,13 @@ public class EmulatorLifecycle {
|
||||
schemaCreationWorker.rehydrateSchemas();
|
||||
stepFunctionsService.abortAbandonedExecutions();
|
||||
|
||||
// The selected DynamoDB backend is ready before any persisted stream consumer reads it.
|
||||
dynamoDbRuntime.start();
|
||||
sqsPoller.startPersistedPollers();
|
||||
kinesisPoller.startPersistedPollers();
|
||||
dynamodbStreamsPoller.startPersistedPollers();
|
||||
pipesService.startPersistedPollers();
|
||||
redshiftZeroEtlConsumer.startPersistedIntegrations();
|
||||
rdsService.restorePersistedRuntime();
|
||||
if (config.services().timestreamInfluxdb().enabled()) {
|
||||
timestreamInfluxDbService.restorePersistedRuntime();
|
||||
@@ -343,6 +354,9 @@ public class EmulatorLifecycle {
|
||||
// SIGTERM grace window and trigger SIGKILL; if the flush ran last it would be skipped and
|
||||
// in-memory (hybrid) data would be lost on an otherwise-graceful shutdown. shutdownAll()
|
||||
// still runs at the end to stop the flush schedulers and capture any shutdown-time writes.
|
||||
// DynamoDB stream consumers stop first, so the flush holds their final checkpoints.
|
||||
runCleanup("DynamoDB Streams poller", dynamodbStreamsPoller::shutdown);
|
||||
runCleanup("Redshift zero-ETL consumer", redshiftZeroEtlConsumer::shutdown);
|
||||
runCleanup("storage flush", storageFactory::flushAll);
|
||||
runCleanup("EC2 metadata server", () -> {
|
||||
if (isMetadataServerNeeded()) {
|
||||
@@ -372,6 +386,7 @@ public class EmulatorLifecycle {
|
||||
// EC2 instances, in-flight build/job containers). Runs before shutdownAll() so any
|
||||
// state written while stopping is captured by the final flush.
|
||||
ContainerTeardowns.stopAll(containerTeardowns, LOG);
|
||||
runCleanup("DynamoDB backend", dynamoDbRuntime::stop);
|
||||
runCleanup("storage shutdown", storageFactory::shutdownAll);
|
||||
|
||||
LOG.info("=== AWS Local Emulator Stopped ===");
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbBackendLifecycle;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
/**
|
||||
* Drives the selected DynamoDB backend through the emulator lifecycle: readiness at startup,
|
||||
* reset preflight, quiescing and cleanup, and shutdown. Does nothing while DynamoDB is disabled.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DynamoDbRuntime implements Resettable {
|
||||
|
||||
private final DynamoDbBackendLifecycle backend;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public DynamoDbRuntime(DynamoDbBackendLifecycle backend, EmulatorConfig config) {
|
||||
this.backend = backend;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (enabled()) {
|
||||
backend.start();
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (enabled()) {
|
||||
backend.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkReset() {
|
||||
if (enabled()) {
|
||||
backend.checkReset();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
if (enabled()) {
|
||||
backend.beforeReset();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
if (enabled()) {
|
||||
backend.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReset() {
|
||||
if (enabled()) {
|
||||
backend.afterReset();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean enabled() {
|
||||
return config.services().dynamodb().enabled();
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,26 @@ public class DynamoDbService {
|
||||
recoverInterruptedJobs();
|
||||
}
|
||||
|
||||
/** Emulator reset: drops the in-process item cache, locks and idempotency tokens, and stream state. */
|
||||
public void clearProcessState() {
|
||||
itemsByTable.clear();
|
||||
itemLocks.clear();
|
||||
txIdempotency.clear();
|
||||
if (streamService != null) {
|
||||
streamService.clear();
|
||||
}
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Shutdown: ends Kinesis forwarding drains so none writes to Kinesis during the final storage flush. */
|
||||
public void stopKinesisForwarding() {
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void loadPersistedItems() {
|
||||
if (itemStore == null) return;
|
||||
Map<String, TableDefinition> persistedTables = persistedTablesByScopedKey();
|
||||
@@ -2687,7 +2707,8 @@ public class DynamoDbService {
|
||||
}
|
||||
|
||||
record ExpiredTableScan(String rawKey, String accountId, String storageKey, String region,
|
||||
TableDefinition table, List<String> itemKeys) {}
|
||||
TableDefinition table, List<String> itemKeys,
|
||||
ConcurrentSkipListMap<String, JsonNode> items) {}
|
||||
|
||||
void deleteExpiredItems() {
|
||||
deleteScannedItems(scanExpiredItems());
|
||||
@@ -2726,7 +2747,7 @@ public class DynamoDbService {
|
||||
String accountId = slash >= 0 ? rawKey.substring(0, slash) : null;
|
||||
String storageKey = slash >= 0 ? rawKey.substring(slash + 1) : rawKey;
|
||||
String region = storageKey.split("::", 2)[0];
|
||||
scans.add(new ExpiredTableScan(rawKey, accountId, storageKey, region, table, expiredKeys));
|
||||
scans.add(new ExpiredTableScan(rawKey, accountId, storageKey, region, table, expiredKeys, items));
|
||||
}
|
||||
return scans;
|
||||
}
|
||||
@@ -2734,13 +2755,14 @@ public class DynamoDbService {
|
||||
void deleteScannedItems(List<ExpiredTableScan> scans) {
|
||||
int totalDeleted = 0;
|
||||
for (ExpiredTableScan scan : scans) {
|
||||
ConcurrentSkipListMap<String, JsonNode> items = itemsByTable.get(scan.rawKey());
|
||||
if (items == null) {
|
||||
continue;
|
||||
}
|
||||
ConcurrentSkipListMap<String, JsonNode> items = scan.items();
|
||||
|
||||
int deletedForTable = 0;
|
||||
for (String itemKey : scan.itemKeys()) {
|
||||
// A table deleted, or deleted and recreated, since the scan or during this sweep: its items are not this scan's.
|
||||
if (itemsByTable.get(scan.rawKey()) != items) {
|
||||
break;
|
||||
}
|
||||
JsonNode removed = withScopedItemLock(scan.rawKey(), itemKey, () -> {
|
||||
JsonNode current = items.get(itemKey);
|
||||
if (current == null || !isExpired(current, scan.table())) {
|
||||
@@ -2762,7 +2784,15 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
if (deletedForTable > 0) {
|
||||
persistItemsForAccount(scan.accountId(), scan.storageKey(), items);
|
||||
// A DeleteTable during the loop detached this map; writing it back would revive its items.
|
||||
// Persisting under the entry's lock holds off DeleteTable, which removes the entry before
|
||||
// it deletes the stored items.
|
||||
itemsByTable.computeIfPresent(scan.rawKey(), (key, live) -> {
|
||||
if (live == items) {
|
||||
persistItemsForAccount(scan.accountId(), scan.storageKey(), items);
|
||||
}
|
||||
return live;
|
||||
});
|
||||
totalDeleted += deletedForTable;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +146,13 @@ public class DynamoDbStreamService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Emulator reset: drops every stream and its records. Sequence numbers stay monotonic. */
|
||||
public void clear() {
|
||||
streams.clear();
|
||||
records.clear();
|
||||
streamRecordCounts.clear();
|
||||
}
|
||||
|
||||
public void captureEvent(String eventName, JsonNode oldItem, JsonNode newItem,
|
||||
TableDefinition table, String region) {
|
||||
StreamDescription sd = streams.get(table.getTableArn());
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -17,6 +16,7 @@ public class DynamoDbTtlService {
|
||||
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private boolean paused;
|
||||
|
||||
@Inject
|
||||
public DynamoDbTtlService(DynamoDbService dynamoDbService) {
|
||||
@@ -28,14 +28,35 @@ public class DynamoDbTtlService {
|
||||
});
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void init() {
|
||||
scheduler.scheduleAtFixedRate(dynamoDbService::deleteExpiredItems, 60, 60, TimeUnit.SECONDS);
|
||||
public void start() {
|
||||
scheduler.scheduleAtFixedRate(this::sweep, 60, 60, TimeUnit.SECONDS);
|
||||
LOG.infov("DynamoDB TTL sweeper scheduled (60s interval)");
|
||||
}
|
||||
|
||||
synchronized void sweep() {
|
||||
if (paused) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
dynamoDbService.deleteExpiredItems();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "DynamoDB TTL sweep failed; retrying on the next run");
|
||||
}
|
||||
}
|
||||
|
||||
/** Skips sweeps until {@link #resume()}, first waiting for a sweep already running to finish. */
|
||||
public synchronized void pause() {
|
||||
paused = true;
|
||||
}
|
||||
|
||||
public synchronized void resume() {
|
||||
paused = false;
|
||||
}
|
||||
|
||||
/** Stops sweeping for good, first waiting for a sweep already running to finish. */
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
public void stop() {
|
||||
pause();
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
}
|
||||
+6
@@ -374,6 +374,12 @@ public class KinesisStreamingForwarder {
|
||||
}
|
||||
}
|
||||
|
||||
/** Emulator reset and shutdown: discard every destination's buffer, stop its drains, and drop its state. */
|
||||
public void clear() {
|
||||
states.values().forEach(this::invalidate);
|
||||
states.clear();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
/** The selected engine's process lifecycle, driven by {@code DynamoDbRuntime}. */
|
||||
public interface DynamoDbBackendLifecycle {
|
||||
|
||||
/** Initializes the engine and its maintenance work; throws when it cannot serve requests. */
|
||||
void start();
|
||||
|
||||
/** Throws to refuse an emulator-wide reset; runs before anything is stopped or cleared. */
|
||||
void checkReset();
|
||||
|
||||
/** Quiesces maintenance work before Floci storage is cleared. */
|
||||
void beforeReset();
|
||||
|
||||
/** Drops the engine's process state; runs after Floci storage was cleared. */
|
||||
void reset();
|
||||
|
||||
/** Resumes maintenance work at the end of a reset; may run without a preceding {@link #beforeReset()}. */
|
||||
void afterReset();
|
||||
|
||||
/** Stops maintenance work and closes clients. */
|
||||
void stop();
|
||||
}
|
||||
+6
-1
@@ -9,7 +9,7 @@ import jakarta.inject.Inject;
|
||||
* The one immutable DynamoDB backend selection. Native is the only engine today; a configurable
|
||||
* choice arrives with the alternative engine. {@link NativeDynamoDbBackend} is typed to its concrete
|
||||
* class and {@link DynamoDbApiStreamReader} is not a bean, so these producers are the only
|
||||
* unqualified beans for the four seam interfaces.
|
||||
* unqualified beans for the five seam interfaces.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DynamoDbBackendSelector {
|
||||
@@ -36,6 +36,11 @@ public class DynamoDbBackendSelector {
|
||||
return nativeBackend;
|
||||
}
|
||||
|
||||
@Produces
|
||||
DynamoDbBackendLifecycle lifecycle() {
|
||||
return nativeBackend;
|
||||
}
|
||||
|
||||
/** Native stream history lives only in memory, so committed progress ends with the process. */
|
||||
@Produces
|
||||
DynamoDbStreamReader streamReader() {
|
||||
|
||||
+48
-2
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbTtlService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbStreamsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
@@ -12,6 +14,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.quarkus.arc.ClientProxy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Typed;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -27,23 +30,66 @@ import java.util.Optional;
|
||||
*/
|
||||
@ApplicationScoped
|
||||
@Typed(NativeDynamoDbBackend.class)
|
||||
public class NativeDynamoDbBackend implements DynamoDbOperations, DynamoDbItemAccess, DynamoDbTableAccess {
|
||||
public class NativeDynamoDbBackend implements DynamoDbOperations, DynamoDbItemAccess, DynamoDbTableAccess,
|
||||
DynamoDbBackendLifecycle {
|
||||
|
||||
private final NativeDynamoDbJsonHandler jsonHandler;
|
||||
private final NativeDynamoDbStreamsJsonHandler streamsHandler;
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final DynamoDbStreamService streamService;
|
||||
private final DynamoDbTtlService ttlService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public NativeDynamoDbBackend(NativeDynamoDbJsonHandler jsonHandler,
|
||||
NativeDynamoDbStreamsJsonHandler streamsHandler,
|
||||
DynamoDbService dynamoDbService, ObjectMapper objectMapper) {
|
||||
DynamoDbService dynamoDbService, DynamoDbStreamService streamService,
|
||||
DynamoDbTtlService ttlService, ObjectMapper objectMapper) {
|
||||
this.jsonHandler = jsonHandler;
|
||||
this.streamsHandler = streamsHandler;
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.streamService = streamService;
|
||||
this.ttlService = ttlService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the engine beans so their constructors load persisted items, recover interrupted
|
||||
* jobs and rebuild stream buffers now, before any consumer reads, then schedules the TTL sweep.
|
||||
*/
|
||||
@Override
|
||||
public void start() {
|
||||
ClientProxy.unwrap(dynamoDbService);
|
||||
ClientProxy.unwrap(streamService);
|
||||
ttlService.start();
|
||||
}
|
||||
|
||||
/** A native reset is always allowed. */
|
||||
@Override
|
||||
public void checkReset() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
ttlService.pause();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
dynamoDbService.clearProcessState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReset() {
|
||||
ttlService.resume();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
ttlService.stop();
|
||||
dynamoDbService.stopKinesisForwarding();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Reply execute(Call call) throws Exception {
|
||||
String region = call.scope().region();
|
||||
|
||||
+12
-6
@@ -75,7 +75,8 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
|
||||
final Set<String> stopped = ConcurrentHashMap.newKeySet();
|
||||
/** {@code uuid:shardId} of shards a mapping read to their end; re-derived from committed progress. */
|
||||
private final Set<String> finishedShards = ConcurrentHashMap.newKeySet();
|
||||
private volatile boolean resetting;
|
||||
/** Set during a reset and after shutdown: no invocation starts and no checkpoint is saved. */
|
||||
private volatile boolean quiesced;
|
||||
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "dynamodb-streams-esm-poller");
|
||||
t.setDaemon(true);
|
||||
@@ -185,8 +186,13 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops polling for good. Taking the monitor drains an in-flight advanceCheckpoint save, and no
|
||||
* checkpoint is saved after this returns. Idempotent, so it may run again from {@code @PreDestroy}.
|
||||
*/
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
public synchronized void shutdown() {
|
||||
quiesced = true;
|
||||
pollExecutor.shutdownNow();
|
||||
timerIds.values().forEach(vertx::cancelTimer);
|
||||
timerIds.clear();
|
||||
@@ -195,12 +201,12 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
|
||||
@Override
|
||||
public synchronized void beforeReset() {
|
||||
// Taking the monitor drains an in-flight advanceCheckpoint save; it is released before the wipe.
|
||||
resetting = true;
|
||||
quiesced = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void afterReset() {
|
||||
resetting = false;
|
||||
quiesced = pollExecutor.isShutdown();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
@@ -326,7 +332,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
|
||||
boolean enabled = esmStore.getForAccount(esm.getAccountId(), esm.getUuid())
|
||||
.map(EventSourceMapping::isEnabled)
|
||||
.orElse(false);
|
||||
if (resetting || !enabled) {
|
||||
if (quiesced || !enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -755,7 +761,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
|
||||
}
|
||||
|
||||
private boolean isStopped(EventSourceMapping esm) {
|
||||
return resetting || stopped.contains(esm.getUuid()) || !exists(esm);
|
||||
return quiesced || stopped.contains(esm.getUuid()) || !exists(esm);
|
||||
}
|
||||
|
||||
private boolean exists(EventSourceMapping esm) {
|
||||
|
||||
+99
-26
@@ -8,6 +8,7 @@ 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.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess.ScanPage;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
@@ -16,11 +17,9 @@ 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;
|
||||
import io.vertx.core.Vertx;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -33,9 +32,11 @@ import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDynamoDbZeroEtlConsumer.class);
|
||||
private static final int BATCH_SIZE = 100;
|
||||
@@ -56,6 +57,11 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
/** Polls hold the read lock; a reset takes the write lock to wait them out. */
|
||||
private final ReentrantReadWriteLock quiesceLock = new ReentrantReadWriteLock();
|
||||
private volatile boolean quiesced;
|
||||
/** Completed resets: a poll writes only while none is in progress and none completed since its submission. */
|
||||
private volatile long resets;
|
||||
|
||||
@Inject
|
||||
public RedshiftDynamoDbZeroEtlConsumer(Vertx vertx,
|
||||
@@ -92,10 +98,6 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
this.pollIntervalMs = pollIntervalMs;
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent event) {
|
||||
startPersistedIntegrations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the persisted integrations, first discarding their stream progress when it lasts only
|
||||
* for the process: native stream history is volatile, so a sequence number saved by a previous
|
||||
@@ -116,8 +118,8 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
if (vertx == null || timerIds.containsKey(integration.getIntegrationArn())) {
|
||||
return;
|
||||
}
|
||||
long timerId = vertx.setPeriodic(pollIntervalMs, ignored -> pollAnd(integration));
|
||||
timerIds.put(integration.getIntegrationArn(), timerId);
|
||||
timerIds.put(integration.getIntegrationArn(),
|
||||
vertx.setPeriodic(pollIntervalMs, timerId -> pollAnd(integration, timerId)));
|
||||
}
|
||||
|
||||
public void stopPolling(String integrationArn) {
|
||||
@@ -130,6 +132,10 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
}
|
||||
|
||||
void pollOnce(Integration integration) {
|
||||
unlessQuiesced(resets, () -> poll(integration));
|
||||
}
|
||||
|
||||
private void poll(Integration integration) {
|
||||
writer.createLandingTable(integration.getAccountId(), integration.getTargetClusterIdentifier(),
|
||||
integration.getLandingTableName());
|
||||
if (!integration.isBackfillCompleted()) {
|
||||
@@ -261,7 +267,22 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
}
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
/**
|
||||
* Waits for the poll in progress, then keeps every poll from writing until {@link #afterReset()},
|
||||
* and a poll submitted before that from writing at all.
|
||||
*/
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
quiesceLock.writeLock().lock();
|
||||
try {
|
||||
quiesced = true;
|
||||
} finally {
|
||||
quiesceLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
for (String integrationArn : timerIds.keySet()) {
|
||||
stopPolling(integrationArn);
|
||||
}
|
||||
@@ -269,34 +290,86 @@ public class RedshiftDynamoDbZeroEtlConsumer {
|
||||
finishedShards.clear();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void onStop() {
|
||||
reset();
|
||||
pollExecutor.shutdownNow();
|
||||
/** Lets the polls submitted from now on write again. */
|
||||
@Override
|
||||
public void afterReset() {
|
||||
quiesceLock.writeLock().lock();
|
||||
try {
|
||||
resets++;
|
||||
quiesced = false;
|
||||
} finally {
|
||||
quiesceLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void pollAnd(Integration integration) {
|
||||
/**
|
||||
* Stops every integration for good, waiting up to five seconds for a poll in progress so the storage
|
||||
* flush that follows holds its checkpoint. Idempotent, so it may run again from {@code @PreDestroy}.
|
||||
*/
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
clear();
|
||||
pollExecutor.shutdown();
|
||||
try {
|
||||
if (!pollExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
pollExecutor.shutdownNow();
|
||||
LOG.warnv("A zero-ETL poll was still running at shutdown, so its last checkpoint may not be flushed");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
pollExecutor.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the section unless a reset is in progress or one completed since {@code submittedAt} was read. */
|
||||
private void unlessQuiesced(long submittedAt, Runnable section) {
|
||||
quiesceLock.readLock().lock();
|
||||
try {
|
||||
if (!quiesced && resets == submittedAt) {
|
||||
section.run();
|
||||
}
|
||||
} finally {
|
||||
quiesceLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits the tick's poll only while its timer is still registered, building the task first: {@code clear()}
|
||||
* removes the timer before {@code afterReset()} counts the reset, both on the reset thread, so a task that
|
||||
* read the new count sees its timer gone and one that read the old count is rejected by {@code unlessQuiesced}.
|
||||
*/
|
||||
private void pollAnd(Integration integration, long timerId) {
|
||||
Runnable task = pollTask(integration);
|
||||
String integrationArn = integration.getIntegrationArn();
|
||||
if (!Long.valueOf(timerId).equals(timerIds.get(integrationArn))) {
|
||||
return;
|
||||
}
|
||||
if (activePolls.putIfAbsent(integrationArn, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
pollExecutor.submit(() -> {
|
||||
try {
|
||||
pollSafely(integration);
|
||||
} finally {
|
||||
activePolls.remove(integrationArn);
|
||||
}
|
||||
});
|
||||
pollExecutor.submit(task);
|
||||
}
|
||||
|
||||
private void pollSafely(Integration integration) {
|
||||
/** The poll {@code pollAnd} submits, bound to the resets completed at its submission. */
|
||||
Runnable pollTask(Integration integration) {
|
||||
long submittedAt = resets;
|
||||
return () -> {
|
||||
try {
|
||||
pollSafely(integration, submittedAt);
|
||||
} finally {
|
||||
activePolls.remove(integration.getIntegrationArn());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void pollSafely(Integration integration, long submittedAt) {
|
||||
try {
|
||||
pollOnce(integration);
|
||||
unlessQuiesced(submittedAt, () -> poll(integration));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Zero-ETL polling failed for integration {0}", integration.getIntegrationArn());
|
||||
try {
|
||||
redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
|
||||
integration.getShardSequenceNumbers(), false, e.getMessage());
|
||||
unlessQuiesced(submittedAt, () -> redshiftService.updateIntegrationRuntime(integration.getAccountId(),
|
||||
integration.getIntegrationArn(), integration.getShardSequenceNumbers(), false, e.getMessage()));
|
||||
} catch (Exception updateError) {
|
||||
LOG.warnv(updateError, "Could not persist zero-ETL failure for integration {0}",
|
||||
integration.getIntegrationArn());
|
||||
|
||||
Reference in new issue
Block a user