mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+1
-1
@@ -56,7 +56,7 @@ class IamConditionContextResolverTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
dynamoDbService = mock(DynamoDbService.class);
|
||||
NativeDynamoDbBackend dynamoDbBackend = new NativeDynamoDbBackend(null, null, dynamoDbService, mapper);
|
||||
NativeDynamoDbBackend dynamoDbBackend = new NativeDynamoDbBackend(null, null, dynamoDbService, null, null, mapper);
|
||||
dynamoDbFacadeInstance = mock(Instance.class);
|
||||
when(dynamoDbFacadeInstance.isResolvable()).thenReturn(true);
|
||||
when(dynamoDbFacadeInstance.get()).thenReturn(new DynamoDbFacade(dynamoDbBackend, dynamoDbBackend,
|
||||
|
||||
+34
-3
@@ -1,15 +1,17 @@
|
||||
package io.github.hectorvent.floci.lifecycle;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
@@ -152,6 +154,35 @@ class EmulatorInfoControllerIntegrationTest {
|
||||
.body("schemas[0]", equalTo("urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stateResetClearsDynamoDbStreams() {
|
||||
String tableName = "reset-streams-" + UUID.randomUUID();
|
||||
dynamoDb("DynamoDB_20120810.CreateTable", """
|
||||
{"TableName": "%s",
|
||||
"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
|
||||
"AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
|
||||
"BillingMode": "PAY_PER_REQUEST",
|
||||
"StreamSpecification": {"StreamEnabled": true, "StreamViewType": "KEYS_ONLY"}}
|
||||
""".formatted(tableName))
|
||||
.statusCode(200);
|
||||
String listStreams = "{\"TableName\": \"" + tableName + "\"}";
|
||||
dynamoDb("DynamoDBStreams_20120810.ListStreams", listStreams).body("Streams", hasSize(1));
|
||||
|
||||
given().when().post("/_floci/state/reset").then().statusCode(200);
|
||||
|
||||
dynamoDb("DynamoDBStreams_20120810.ListStreams", listStreams).statusCode(200).body("Streams", hasSize(0));
|
||||
}
|
||||
|
||||
private static ValidatableResponse dynamoDb(String target, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stateReset_clearsDatabaseState() {
|
||||
// 1. Put SSM parameter
|
||||
|
||||
@@ -18,12 +18,16 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -148,4 +152,21 @@ class EmulatorInfoControllerTest {
|
||||
verify(resettable, never()).clear();
|
||||
verify(later, never()).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetRefusedByPreflightChangesNothing() {
|
||||
Resettable refusing = mock(Resettable.class);
|
||||
IllegalStateException refusal = new IllegalStateException("backend refuses reset");
|
||||
doThrow(refusal).when(refusing).checkReset();
|
||||
lenient().when(containerTeardowns.iterator()).thenReturn(List.of(sageMakerTeardown).iterator());
|
||||
when(resettables.iterator()).thenReturn(List.of(resettable, refusing).iterator());
|
||||
|
||||
assertSame(refusal, assertThrows(IllegalStateException.class, controller::reset));
|
||||
|
||||
verify(resettable).checkReset();
|
||||
verify(refusing).checkReset();
|
||||
verifyNoMoreInteractions(resettable, refusing);
|
||||
verify(sageMakerTeardown, never()).stopManagedContainers();
|
||||
verifyNoInteractions(storageFactory);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
|
||||
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker;
|
||||
import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbRuntime;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentialsServer;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
@@ -28,6 +29,7 @@ import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
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.stepfunctions.StepFunctionsService;
|
||||
import io.github.hectorvent.floci.services.timestreaminfluxdb.TimestreamInfluxDbService;
|
||||
import io.quarkus.runtime.Quarkus;
|
||||
@@ -113,6 +115,8 @@ class EmulatorLifecycleTest {
|
||||
@Mock private SchemaCreationWorker schemaCreationWorker;
|
||||
@Mock private StepFunctionsService stepFunctionsService;
|
||||
@Mock private Instance<ContainerTeardown> containerTeardowns;
|
||||
@Mock private DynamoDbRuntime dynamoDbRuntime;
|
||||
@Mock private RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer;
|
||||
|
||||
private EmulatorLifecycle emulatorLifecycle;
|
||||
|
||||
@@ -151,7 +155,8 @@ class EmulatorLifecycleTest {
|
||||
elbV2Service, elbClassicService,
|
||||
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
|
||||
pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState,
|
||||
schemaCreationWorker, stepFunctionsService, containerTeardowns, persistentPathValidator);
|
||||
schemaCreationWorker, stepFunctionsService, containerTeardowns, persistentPathValidator,
|
||||
dynamoDbRuntime, redshiftZeroEtlConsumer);
|
||||
Mockito.lenient().when(containerTeardowns.iterator())
|
||||
.thenReturn(java.util.Collections.emptyIterator());
|
||||
}
|
||||
@@ -181,6 +186,46 @@ class EmulatorLifecycleTest {
|
||||
inOrder.verify(rdsService).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsTheDynamoDbBackendAfterStorageLoadAndBeforeItsStreamConsumers() {
|
||||
stubStorageConfig();
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, dynamoDbRuntime, dynamodbStreamsPoller, pipesService,
|
||||
redshiftZeroEtlConsumer);
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(dynamoDbRuntime).start();
|
||||
inOrder.verify(dynamodbStreamsPoller).startPersistedPollers();
|
||||
inOrder.verify(pipesService).startPersistedPollers();
|
||||
inOrder.verify(redshiftZeroEtlConsumer).startPersistedIntegrations();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopsDynamoDbStreamConsumersBeforeTheFlushAndTheBackendBeforeStorageShutdown() {
|
||||
emulatorLifecycle.onStop(Mockito.mock(ShutdownEvent.class));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(dynamodbStreamsPoller, redshiftZeroEtlConsumer, storageFactory,
|
||||
flociUiManager, dynamoDbRuntime);
|
||||
inOrder.verify(dynamodbStreamsPoller).shutdown();
|
||||
inOrder.verify(redshiftZeroEtlConsumer).shutdown();
|
||||
inOrder.verify(storageFactory).flushAll();
|
||||
inOrder.verify(flociUiManager).shutdown();
|
||||
inOrder.verify(dynamoDbRuntime).stop();
|
||||
inOrder.verify(storageFactory).shutdownAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopsTheZeroEtlConsumerWhenTheStreamsPollerShutdownFails() {
|
||||
doThrow(new IllegalStateException("poller shutdown failed")).when(dynamodbStreamsPoller).shutdown();
|
||||
|
||||
emulatorLifecycle.onStop(Mockito.mock(ShutdownEvent.class));
|
||||
|
||||
verify(redshiftZeroEtlConsumer).shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should restore ELBv2 persisted runtime after loading storage when elbv2 is enabled")
|
||||
void shouldRestoreElbV2PersistedRuntimeAfterStorageLoad() {
|
||||
|
||||
+1
-1
@@ -268,7 +268,7 @@ final class CfnProvisionerFixture {
|
||||
discovered.add(new SnsCfnProvisioner(snsService));
|
||||
}
|
||||
if (dynamoDbService != null) {
|
||||
NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDbService, objectMapper);
|
||||
NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDbService, null, null, objectMapper);
|
||||
discovered.add(new DynamoDbCfnProvisioner(new DynamoDbFacade(backend, backend,
|
||||
new RegionResolver("us-east-1", "000000000000"))));
|
||||
}
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ class DynamoDbCfnProvisionerTest {
|
||||
|
||||
private final DynamoDbService dynamoDb = mock(DynamoDbService.class);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDb, mapper);
|
||||
private final NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDb, null, null, mapper);
|
||||
private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(
|
||||
new DynamoDbFacade(backend, backend, new RegionResolver("us-east-1", "000000000000")));
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbBackendLifecycle;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class DynamoDbRuntimeTest {
|
||||
|
||||
private final DynamoDbBackendLifecycle backend = mock(DynamoDbBackendLifecycle.class);
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
private final DynamoDbRuntime runtime = new DynamoDbRuntime(backend, config);
|
||||
|
||||
@Test
|
||||
void drivesTheSelectedBackendLifecycle() {
|
||||
when(config.services().dynamodb().enabled()).thenReturn(true);
|
||||
|
||||
runtime.start();
|
||||
runtime.checkReset();
|
||||
runtime.beforeReset();
|
||||
runtime.clear();
|
||||
runtime.afterReset();
|
||||
runtime.stop();
|
||||
|
||||
InOrder order = inOrder(backend);
|
||||
order.verify(backend).start();
|
||||
order.verify(backend).checkReset();
|
||||
order.verify(backend).beforeReset();
|
||||
order.verify(backend).reset();
|
||||
order.verify(backend).afterReset();
|
||||
order.verify(backend).stop();
|
||||
verifyNoMoreInteractions(backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesTheBackendAloneWhenDynamoDbIsDisabled() {
|
||||
when(config.services().dynamodb().enabled()).thenReturn(false);
|
||||
|
||||
runtime.start();
|
||||
runtime.checkReset();
|
||||
runtime.beforeReset();
|
||||
runtime.clear();
|
||||
runtime.afterReset();
|
||||
runtime.stop();
|
||||
|
||||
verifyNoInteractions(backend);
|
||||
}
|
||||
}
|
||||
+127
@@ -25,11 +25,17 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -201,6 +207,127 @@ class DynamoDbTtlForwardingTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ttlSweepDoesNotPersistItemsOfATableDeletedMidSweep() {
|
||||
StorageBackend<String, TableDefinition> tableStore = new InMemoryStorage<>();
|
||||
StorageBackend<String, Map<String, JsonNode>> itemStore = new InMemoryStorage<>();
|
||||
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
|
||||
DynamoDbService svc = new DynamoDbService(
|
||||
tableStore, itemStore, new RegionResolver("us-east-1", "000000000000"), streamService, null);
|
||||
seedTtlTable(svc, 1);
|
||||
doAnswer(invocation -> {
|
||||
svc.deleteTable("TtlTable", REGION);
|
||||
return null;
|
||||
}).when(streamService).captureEvent(eq("REMOVE"), any(), any(), any(), any());
|
||||
|
||||
svc.deleteExpiredItems();
|
||||
|
||||
assertTrue(itemStore.get("us-east-1::TtlTable").isEmpty(),
|
||||
"the sweep must not write items back for a table deleted while it ran");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSweepDoesNotDeleteFromATableRecreatedAfterItsScan() {
|
||||
StorageBackend<String, TableDefinition> tableStore = new InMemoryStorage<>();
|
||||
StorageBackend<String, Map<String, JsonNode>> itemStore = new InMemoryStorage<>();
|
||||
DynamoDbService svc = new DynamoDbService(
|
||||
tableStore, itemStore, new RegionResolver("us-east-1", "000000000000"));
|
||||
long past = Instant.now().getEpochSecond() - 3600;
|
||||
svc.createTable("TtlTable",
|
||||
List.of(new KeySchemaElement("pk", "HASH")),
|
||||
List.of(new AttributeDefinition("pk", "S")),
|
||||
5L, 5L, REGION);
|
||||
svc.updateTimeToLive("TtlTable", "expireAt", true, REGION);
|
||||
ObjectNode expired = mapper.createObjectNode();
|
||||
expired.set("pk", stringAttr("row-0"));
|
||||
expired.set("expireAt", numberAttr(past));
|
||||
svc.putItem("TtlTable", expired, REGION);
|
||||
List<DynamoDbService.ExpiredTableScan> scans = svc.scanExpiredItems();
|
||||
assertEquals(1, scans.stream().mapToInt(scan -> scan.itemKeys().size()).sum(),
|
||||
"the expired row must be a scan candidate");
|
||||
|
||||
svc.deleteTable("TtlTable", REGION);
|
||||
svc.createTable("TtlTable",
|
||||
List.of(new KeySchemaElement("pk", "HASH")),
|
||||
List.of(new AttributeDefinition("pk", "S")),
|
||||
5L, 5L, REGION);
|
||||
ObjectNode recreated = mapper.createObjectNode();
|
||||
recreated.set("pk", stringAttr("row-0"));
|
||||
recreated.set("expireAt", numberAttr(past));
|
||||
svc.putItem("TtlTable", recreated, REGION);
|
||||
svc.deleteScannedItems(scans);
|
||||
|
||||
ObjectNode key = mapper.createObjectNode();
|
||||
key.set("pk", stringAttr("row-0"));
|
||||
assertNotNull(svc.getItem("TtlTable", key, REGION),
|
||||
"a scan of the deleted table must not delete the recreated table's item");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTableDeletedDuringASweepEmitsNoFurtherRemoves() {
|
||||
StorageBackend<String, TableDefinition> tableStore = new InMemoryStorage<>();
|
||||
StorageBackend<String, Map<String, JsonNode>> itemStore = new InMemoryStorage<>();
|
||||
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
|
||||
DynamoDbService svc = new DynamoDbService(
|
||||
tableStore, itemStore, new RegionResolver("us-east-1", "000000000000"), streamService, null);
|
||||
seedTtlTable(svc, 3);
|
||||
List<DynamoDbService.ExpiredTableScan> scans = svc.scanExpiredItems();
|
||||
assertEquals(3, scans.stream().mapToInt(scan -> scan.itemKeys().size()).sum(),
|
||||
"every expired row must be a scan candidate");
|
||||
doAnswer(invocation -> {
|
||||
svc.deleteTable("TtlTable", REGION);
|
||||
return null;
|
||||
}).doNothing().when(streamService).captureEvent(eq("REMOVE"), any(), any(), any(), any());
|
||||
|
||||
svc.deleteScannedItems(scans);
|
||||
|
||||
verify(streamService, times(1)).captureEvent(eq("REMOVE"), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTableWaitsForASweepPersistingTheTable() throws Exception {
|
||||
CountDownLatch persisting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
StorageBackend<String, TableDefinition> tableStore = new InMemoryStorage<>();
|
||||
StorageBackend<String, Map<String, JsonNode>> itemStore = new InMemoryStorage<>() {
|
||||
@Override
|
||||
public void put(String key, Map<String, JsonNode> value) {
|
||||
if ("ttl-sweep".equals(Thread.currentThread().getName())) {
|
||||
persisting.countDown();
|
||||
try {
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
};
|
||||
DynamoDbService svc = new DynamoDbService(
|
||||
tableStore, itemStore, new RegionResolver("us-east-1", "000000000000"));
|
||||
seedTtlTable(svc, 1);
|
||||
Thread sweep = new Thread(svc::deleteExpiredItems, "ttl-sweep");
|
||||
sweep.start();
|
||||
assertTrue(persisting.await(10, TimeUnit.SECONDS));
|
||||
|
||||
Thread delete = new Thread(() -> svc.deleteTable("TtlTable", REGION));
|
||||
delete.start();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (delete.getState() != Thread.State.BLOCKED) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
fail("DeleteTable did not wait for the sweep persisting the table");
|
||||
}
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
release.countDown();
|
||||
sweep.join(10_000);
|
||||
delete.join(10_000);
|
||||
|
||||
assertEquals(Thread.State.TERMINATED, delete.getState());
|
||||
assertTrue(itemStore.get("us-east-1::TtlTable").isEmpty(),
|
||||
"DeleteTable must delete the stored items after the sweep wrote them");
|
||||
}
|
||||
|
||||
// A write landing between scanExpiredItems() and deleteScannedItems() must not be lost.
|
||||
@Test
|
||||
void ttlSweep_preserves_item_updated_between_scan_and_delete() throws Exception {
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class DynamoDbTtlServiceTest {
|
||||
|
||||
@Test
|
||||
void aFailingSweepDoesNotEscapeTheScheduledTask() {
|
||||
DynamoDbService dynamoDbService = mock(DynamoDbService.class);
|
||||
doThrow(new IllegalStateException("sweep failed")).when(dynamoDbService).deleteExpiredItems();
|
||||
DynamoDbTtlService ttlService = new DynamoDbTtlService(dynamoDbService);
|
||||
|
||||
assertDoesNotThrow(ttlService::sweep);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPausedSweepDeletesNothingUntilResumed() {
|
||||
DynamoDbService dynamoDbService = mock(DynamoDbService.class);
|
||||
DynamoDbTtlService ttlService = new DynamoDbTtlService(dynamoDbService);
|
||||
|
||||
ttlService.pause();
|
||||
ttlService.sweep();
|
||||
verify(dynamoDbService, never()).deleteExpiredItems();
|
||||
|
||||
ttlService.resume();
|
||||
ttlService.sweep();
|
||||
verify(dynamoDbService).deleteExpiredItems();
|
||||
}
|
||||
|
||||
@Test
|
||||
void pauseWaitsForTheSweepInProgress() throws Exception {
|
||||
assertWaitsForTheSweepInProgress(DynamoDbTtlService::pause);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopWaitsForASweepInProgress() throws Exception {
|
||||
assertWaitsForTheSweepInProgress(DynamoDbTtlService::stop);
|
||||
}
|
||||
|
||||
/** Also asserts that no sweep deletes anything after {@code call} returns. */
|
||||
private static void assertWaitsForTheSweepInProgress(Consumer<DynamoDbTtlService> call) throws Exception {
|
||||
DynamoDbService dynamoDbService = mock(DynamoDbService.class);
|
||||
CountDownLatch sweeping = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
sweeping.countDown();
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
return null;
|
||||
}).when(dynamoDbService).deleteExpiredItems();
|
||||
DynamoDbTtlService ttlService = new DynamoDbTtlService(dynamoDbService);
|
||||
Thread sweep = new Thread(ttlService::sweep);
|
||||
sweep.start();
|
||||
assertTrue(sweeping.await(10, TimeUnit.SECONDS));
|
||||
|
||||
Thread caller = new Thread(() -> call.accept(ttlService));
|
||||
caller.start();
|
||||
awaitBlocked(caller);
|
||||
release.countDown();
|
||||
caller.join(10_000);
|
||||
sweep.join(10_000);
|
||||
|
||||
assertEquals(Thread.State.TERMINATED, caller.getState());
|
||||
assertEquals(Thread.State.TERMINATED, sweep.getState());
|
||||
ttlService.sweep();
|
||||
verify(dynamoDbService).deleteExpiredItems();
|
||||
}
|
||||
|
||||
/** Observes the calling thread reach the sweep's monitor instead of sleeping to hope for it. */
|
||||
private static void awaitBlocked(Thread thread) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (thread.getState() != Thread.State.BLOCKED) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
fail("the call returned or never reached the sweep's monitor while a sweep was running");
|
||||
}
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.arc.Arc;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
/** The emulator lifecycle drives only the selected DynamoDB backend, here one that refuses resets. */
|
||||
@QuarkusTest
|
||||
@TestProfile(DynamoDbBackendResetIntegrationTest.RefusingBackendProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class DynamoDbBackendResetIntegrationTest {
|
||||
|
||||
public static final class RefusingBackendProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Set<Class<?>> getEnabledAlternatives() {
|
||||
return Set.of(RefusingDynamoDbBackendLifecycle.class);
|
||||
}
|
||||
}
|
||||
|
||||
private static final String PARAMETER = "/dynamodb-backend-reset/survives-a-refused-reset";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void startupInitializesNoNativeDatabaseState() {
|
||||
assertFalse(Arc.container().getActiveContext(ApplicationScoped.class).getState().getContextualInstances()
|
||||
.keySet().stream().anyMatch(bean -> bean.getBeanClass() == DynamoDbService.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void aRefusedResetClearsNothing() {
|
||||
ssm("PutParameter", "{\"Name\": \"" + PARAMETER + "\", \"Value\": \"kept\", \"Type\": \"String\"}")
|
||||
.statusCode(200);
|
||||
|
||||
given().when().post("/_floci/state/reset").then().statusCode(409);
|
||||
|
||||
ssm("GetParameter", "{\"Name\": \"" + PARAMETER + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Parameter.Value", equalTo("kept"));
|
||||
}
|
||||
|
||||
private static ValidatableResponse ssm(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "AmazonSSM." + action)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+10
@@ -54,6 +54,9 @@ class DynamoDbBackendSelectionTest {
|
||||
@Inject
|
||||
DynamoDbStreamReader streamReader;
|
||||
|
||||
@Inject
|
||||
DynamoDbBackendLifecycle lifecycle;
|
||||
|
||||
// Collected exactly as ResourceExplorer2Service collects its providers.
|
||||
@Inject
|
||||
Instance<ResourceProvider> providers;
|
||||
@@ -68,6 +71,13 @@ class DynamoDbBackendSelectionTest {
|
||||
assertInstanceOf(NativeDynamoDbBackend.class, backend);
|
||||
assertSame(backend, ClientProxy.unwrap(items));
|
||||
assertSame(backend, ClientProxy.unwrap(tables));
|
||||
assertSame(backend, ClientProxy.unwrap(lifecycle));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupSchedulesTheTtlSweep() {
|
||||
assertTrue(Thread.getAllStackTraces().keySet().stream()
|
||||
.anyMatch(thread -> thread.isAlive() && "dynamodb-ttl-sweeper".equals(thread.getName())));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+61
-4
@@ -7,11 +7,13 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbTtlService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.KinesisStreamingForwarder;
|
||||
import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbStreamsJsonHandler;
|
||||
@@ -26,6 +28,7 @@ import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -39,7 +42,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The native engine behind the DynamoDB seam, and the thin public handlers in front of it. */
|
||||
@@ -51,20 +56,26 @@ class DynamoDbNativeBackendTest {
|
||||
private static final String TABLE = "orders";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<StorageBackend<?, ?>> stores = new ArrayList<>();
|
||||
private final KinesisStreamingForwarder forwarder = mock(KinesisStreamingForwarder.class);
|
||||
private final DynamoDbTtlService ttl = mock(DynamoDbTtlService.class);
|
||||
private NativeDynamoDbBackend backend;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation -> {
|
||||
AccountAwareStorageBackend<Object> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
stores.add(store);
|
||||
return store;
|
||||
});
|
||||
DynamoDbStreamService streams = new DynamoDbStreamService(mapper, storageFactory);
|
||||
DynamoDbService service = new DynamoDbService(storageFactory, new RegionResolver(REGION, ACCOUNT), streams,
|
||||
mock(KinesisStreamingForwarder.class), null, mapper, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
forwarder, null, mapper, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
NativeDynamoDbTableService tables = new NativeDynamoDbTableService(service, streams, mock(KinesisService.class));
|
||||
backend = new NativeDynamoDbBackend(new NativeDynamoDbJsonHandler(service, tables, mapper),
|
||||
new NativeDynamoDbStreamsJsonHandler(streams, service, new RegionResolver(REGION, ACCOUNT), mapper),
|
||||
service, mapper);
|
||||
service, streams, ttl, mapper);
|
||||
}
|
||||
|
||||
private Reply call(Api api, String action, JsonNode body) throws Exception {
|
||||
@@ -84,6 +95,52 @@ class DynamoDbNativeBackendTest {
|
||||
return mapper.readTree(text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lifecycleDrivesTheTtlSweep() {
|
||||
backend.start();
|
||||
verify(ttl).start();
|
||||
|
||||
backend.beforeReset();
|
||||
verify(ttl).pause();
|
||||
|
||||
backend.afterReset();
|
||||
verify(ttl).resume();
|
||||
|
||||
backend.stop();
|
||||
verify(ttl).stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopEndsKinesisForwardingAfterTheTtlSweep() {
|
||||
backend.stop();
|
||||
|
||||
InOrder order = inOrder(ttl, forwarder);
|
||||
order.verify(ttl).stop();
|
||||
order.verify(forwarder).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetDropsTheEngineProcessState() throws Exception {
|
||||
createTable(",\"StreamSpecification\":{\"StreamEnabled\":true,\"StreamViewType\":\"KEYS_ONLY\"}");
|
||||
JsonNode transact = json("""
|
||||
{"ClientRequestToken":"token-1",
|
||||
"TransactItems":[{"Put":{"TableName":"%s","Item":{"id":{"S":"a"}}}}]}
|
||||
""".formatted(TABLE));
|
||||
call(Api.DYNAMODB, "TransactWriteItems", transact);
|
||||
|
||||
// An emulator reset wipes Floci storage before it resets the engine.
|
||||
stores.forEach(StorageBackend::clear);
|
||||
backend.reset();
|
||||
createTable("");
|
||||
call(Api.DYNAMODB, "TransactWriteItems", transact);
|
||||
|
||||
Reply streams = call(Api.DYNAMODB_STREAMS, "ListStreams", mapper.createObjectNode());
|
||||
assertEquals(0, streams.body().path("Streams").size());
|
||||
JsonNode key = json("{\"id\":{\"S\":\"a\"}}");
|
||||
assertEquals(key, backend.getItem(SCOPE, TABLE, key), "the reused token writes again");
|
||||
verify(forwarder).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rawDeleteTableHonoursDeletionProtectionWhileTypedDeleteDoesNot() throws Exception {
|
||||
createTable(",\"DeletionProtectionEnabled\":true");
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Alternative;
|
||||
|
||||
/** A selected backend that starts nothing and refuses every emulator reset. */
|
||||
@Alternative
|
||||
@ApplicationScoped
|
||||
public class RefusingDynamoDbBackendLifecycle implements DynamoDbBackendLifecycle {
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkReset() {
|
||||
throw new AwsException("ResourceInUseException", "The DynamoDB backend refuses an emulator reset", 409);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
throw new IllegalStateException("beforeReset ran after a refused preflight");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
throw new IllegalStateException("reset ran after a refused preflight");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReset() {
|
||||
throw new IllegalStateException("afterReset ran after a refused preflight");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
}
|
||||
}
|
||||
+44
@@ -1955,6 +1955,50 @@ class DynamoDbStreamsEventSourcePollerTest {
|
||||
verify(store).saveForAccount(eq(ACCOUNT_ID), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkpointIsNotSavedAfterShutdown() throws Exception {
|
||||
stubStream("s1");
|
||||
EventSourceMapping esm = filterEsm();
|
||||
EsmStore store = mock(EsmStore.class);
|
||||
DynamoDbStreamsEventSourcePoller p = pollerWith(store);
|
||||
AtomicBoolean shutdownDuringInvoke = new AtomicBoolean(true);
|
||||
List<List<String>> invocations = recordInvocations(seqs -> {
|
||||
if (shutdownDuringInvoke.getAndSet(false)) {
|
||||
p.shutdown();
|
||||
}
|
||||
return new InvokeResult();
|
||||
});
|
||||
|
||||
pollOnce(p, esm);
|
||||
|
||||
assertEquals(List.of(List.of("s1")), invocations);
|
||||
assertNull(checkpoint(esm));
|
||||
verify(store, never()).saveForAccount(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResetEndingAfterShutdownKeepsThePollerQuiesced() throws Exception {
|
||||
stubStream("s1");
|
||||
EventSourceMapping esm = filterEsm();
|
||||
EsmStore store = mock(EsmStore.class);
|
||||
DynamoDbStreamsEventSourcePoller p = pollerWith(store);
|
||||
AtomicBoolean resetAcrossShutdownDuringInvoke = new AtomicBoolean(true);
|
||||
List<List<String>> invocations = recordInvocations(seqs -> {
|
||||
if (resetAcrossShutdownDuringInvoke.getAndSet(false)) {
|
||||
p.beforeReset();
|
||||
p.shutdown();
|
||||
p.afterReset();
|
||||
}
|
||||
return new InvokeResult();
|
||||
});
|
||||
|
||||
pollOnce(p, esm);
|
||||
|
||||
assertEquals(List.of(List.of("s1")), invocations);
|
||||
assertNull(checkpoint(esm));
|
||||
verify(store, never()).saveForAccount(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pollDuringAResetDoesNotInvokeUntilTheResetEnds() throws Exception {
|
||||
stubStream("s1");
|
||||
|
||||
+196
@@ -3,9 +3,11 @@ package io.github.hectorvent.floci.services.redshift;
|
||||
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.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
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.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader;
|
||||
@@ -17,6 +19,8 @@ import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Integration;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Vertx;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -27,19 +31,27 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
@@ -260,6 +272,190 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmulatorResetStopsEveryIntegrationTimer() {
|
||||
Vertx vertx = mock(Vertx.class);
|
||||
when(vertx.setPeriodic(anyLong(), any())).thenReturn(7L);
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(vertx,
|
||||
new FakeStreamReader(CheckpointLifetime.PROCESS), dynamoDb, mock(RedshiftService.class),
|
||||
mock(RedshiftZeroEtlWriter.class), MAPPER, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
consumer.startPolling(streamingIntegration());
|
||||
Resettable resettable = consumer;
|
||||
|
||||
resettable.clear();
|
||||
|
||||
verify(vertx).cancelTimer(7L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmulatorResetWaitsForTheWriteInProgressAndWritesNothingUntilItEnds() throws Exception {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
CountDownLatch writing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
writing.countDown();
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
return null;
|
||||
}).doNothing().when(writer).writeBatch(any(), any(), any(), any());
|
||||
Integration integration = streamingIntegration();
|
||||
List<DynamoDbStreamReader.Record> shard = streams.shard(SHARD_ID, null);
|
||||
shard.add(streamRecord("s1"));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer);
|
||||
Thread poll = new Thread(() -> consumer.pollOnce(integration));
|
||||
poll.start();
|
||||
assertTrue(writing.await(10, TimeUnit.SECONDS));
|
||||
|
||||
Thread reset = new Thread(consumer::beforeReset);
|
||||
reset.start();
|
||||
awaitWaiting(reset);
|
||||
release.countDown();
|
||||
reset.join(10_000);
|
||||
poll.join(10_000);
|
||||
assertEquals(Thread.State.TERMINATED, reset.getState());
|
||||
|
||||
DynamoDbStreamReader.Record second = streamRecord("s2");
|
||||
shard.add(second);
|
||||
consumer.pollOnce(integration);
|
||||
verify(writer, times(1)).createLandingTable(any(), any(), any());
|
||||
verify(writer, times(1)).writeBatch(any(), any(), any(), any());
|
||||
|
||||
consumer.afterReset();
|
||||
consumer.pollOnce(integration);
|
||||
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
|
||||
List.of(second.awsRecord()));
|
||||
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPollSubmittedBeforeAResetIsSkippedEvenWhenItRunsAfterTheReset() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
Integration integration = streamingIntegration();
|
||||
DynamoDbStreamReader.Record first = streamRecord("s1");
|
||||
streams.shard(SHARD_ID, null).add(first);
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
|
||||
Runnable submittedBeforeReset = consumer.pollTask(integration);
|
||||
|
||||
consumer.beforeReset();
|
||||
consumer.clear();
|
||||
consumer.afterReset();
|
||||
submittedBeforeReset.run();
|
||||
|
||||
verifyNoInteractions(writer);
|
||||
verify(redshiftService, never()).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
|
||||
|
||||
consumer.pollTask(integration).run();
|
||||
|
||||
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
|
||||
List.of(first.awsRecord()));
|
||||
verify(redshiftService).updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
|
||||
Map.of(SHARD_ID, "s1"), true, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownWaitsForThePollInProgressSoItsCheckpointIsSavedFirst() throws Exception {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
List<String> events = new CopyOnWriteArrayList<>();
|
||||
CountDownLatch writing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
writing.countDown();
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
return null;
|
||||
}).when(writer).writeBatch(any(), any(), any(), any());
|
||||
doAnswer(invocation -> events.add("checkpoint saved"))
|
||||
.when(redshiftService).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
|
||||
Vertx vertx = mock(Vertx.class);
|
||||
when(vertx.setPeriodic(anyLong(), any())).thenReturn(7L);
|
||||
Integration integration = streamingIntegration();
|
||||
streams.shard(SHARD_ID, null).add(streamRecord("s1"));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(vertx, streams, dynamoDb,
|
||||
redshiftService, writer, MAPPER, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
consumer.startPolling(integration);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Handler<Long>> tick = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(vertx).setPeriodic(anyLong(), tick.capture());
|
||||
Thread shutdown = new Thread(() -> {
|
||||
consumer.shutdown();
|
||||
events.add("shutdown returned");
|
||||
});
|
||||
|
||||
try {
|
||||
tick.getValue().handle(7L);
|
||||
assertTrue(writing.await(10, TimeUnit.SECONDS), "the tick hands the poll to the poll executor");
|
||||
shutdown.start();
|
||||
assertEquals(Thread.State.TIMED_WAITING, awaitTimedWaitingOrTerminated(shutdown),
|
||||
"shutdown() returned while a poll was still writing");
|
||||
release.countDown();
|
||||
shutdown.join(10_000);
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
|
||||
assertEquals(List.of("checkpoint saved", "shutdown returned"), events);
|
||||
verify(redshiftService).updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
|
||||
Map.of(SHARD_ID, "s1"), true, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTickFromATimerCanceledByAResetDoesNotPoll() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
Vertx vertx = mock(Vertx.class);
|
||||
when(vertx.setPeriodic(anyLong(), any())).thenReturn(7L);
|
||||
Integration integration = streamingIntegration();
|
||||
streams.shard(SHARD_ID, null).add(streamRecord("s1"));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(vertx, streams, dynamoDb,
|
||||
redshiftService, writer, MAPPER, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
consumer.startPolling(integration);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Handler<Long>> tick = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(vertx).setPeriodic(anyLong(), tick.capture());
|
||||
|
||||
consumer.beforeReset();
|
||||
consumer.clear();
|
||||
consumer.afterReset();
|
||||
tick.getValue().handle(7L);
|
||||
// shutdown() waits for every submitted poll to end, so anything the tick submitted has run.
|
||||
consumer.shutdown();
|
||||
|
||||
assertTrue(streams.iteratorRequests.isEmpty(), "the stale tick read the stream");
|
||||
verifyNoInteractions(writer);
|
||||
verify(redshiftService, never()).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
/** Observes the thread park in a timed wait, or end, instead of sleeping to hope for either. */
|
||||
private static Thread.State awaitTimedWaitingOrTerminated(Thread thread) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
Thread.State state = thread.getState();
|
||||
while (state != Thread.State.TIMED_WAITING && state != Thread.State.TERMINATED) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
fail("the thread neither parked in a timed wait nor ended");
|
||||
}
|
||||
Thread.onSpinWait();
|
||||
state = thread.getState();
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Observes the reset thread park on the poll's lock instead of sleeping to hope for it. */
|
||||
private static void awaitWaiting(Thread thread) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (thread.getState() != Thread.State.WAITING) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
fail("beforeReset() returned or never waited while a write was in progress");
|
||||
}
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
}
|
||||
|
||||
private static Integration streamingIntegration() {
|
||||
Integration integration = integration("orders");
|
||||
integration.setBackfillCompleted(true);
|
||||
|
||||
Reference in new issue
Block a user