mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): route Kinesis CDC to the table owner's account and retry failed forwards (#3063)
* fix(dynamodb): resolve Kinesis CDC forwards against the table owner's account DynamoDB->Kinesis CDC forwarding resolved the target stream against the ambient account. Out of request scope -- notably the TTL sweep, which forwards a REMOVE per expired item after the request completes -- the ambient account falls back to the default, so CDC records could be written into the default account's same-named stream (a cross-tenant leak) or dropped as ResourceNotFound. This was a live bug on the TTL path. - Add KinesisService.putRecordForAccount: resolve, append and persist against a specified account (a null account preserves the ambient behavior). It keeps the per-stream append lock keyed on region+stream (not account) so explicit-account appends stay serialized with request-path producers, preserving the concurrent- append fix; and it migrates a legacy unprefixed stream into the account partition on write (ownership validated by the stream's ARN/account) so installs upgraded from pre-multi-account storage keep forwarding. - KinesisStreamingForwarder.forward now takes the table owner account and forwards via putRecordForAccount. - DynamoDbService passes the owner account at every forward site: the request paths use the request account; the TTL sweep uses the account it derives from the storage key. AWS Compatibility: CDC records land in the table owner's stream, matching AWS per-account isolation. Known residual: the DynamoDB Streams subsystem (DynamoDbStreamsService) has the same ambient-account exposure and is not addressed here. * fix(dynamodb): retry and park failed Kinesis CDC forwards instead of dropping them Change data capture forwarding to a Kinesis streaming destination dropped the change event whenever putRecord threw, so a transient Kinesis error silently lost DynamoDB INSERT/MODIFY/REMOVE (and TTL) events. Forwarding is now a bounded best-effort, in-process retry queue. The write path only enqueues (it never blocks or throws), and a per-destination single-flight background drain performs the send outside the lock: - transient/unknown failures retry with capped exponential backoff (250ms->8s, up to 10 attempts) instead of dropping on the first exception; - deterministic terminal failures (Validation/InvalidArgument) drop only the poison record without wedging the queue behind it; - per-destination FIFO is preserved across retries; - the buffer is bounded (1000 records per destination, oldest evicted on overflow); - after the retry budget is exhausted the episode gives up, and a later event starts a fresh episode that self-heals once the stream recovers. Disabling a destination or deleting the table discards its buffered records and stops all future sends for it (a send already in flight may still complete). Dropped records are counted and per-destination delivery health (forwarded/retried/dropped, queue depth, last error) is tracked for inspection. Buffered records are in memory only and are not durable across restarts. * style(dynamodb): remove em dashes from lines this branch adds AGENTS.md requires colons, commas or periods instead of em dashes. Comment, javadoc and docs prose only; no code or string literals change. * fix(kinesis): resolve the stream inside the append lock, not before it putRecordInternal resolved the stream before taking the per-stream monitor. That resolve is not a read: for a legacy unprefixed stream it migrates the entry, and the two migration paths disagree. The explicit-account path moves it into the account partition behind an ownership predicate and is synchronized on the backend, while AccountAwareStorageBackend.get adopts it into the request account with no ownership check and no synchronization. Racing outside the monitor, an ambient producer and the owner's CDC producer could migrate the same stream concurrently, forking it across partitions or adopting it into the default account, which is the cross-account leak this branch set out to close. Resolve and validate inside the monitor instead. The separate pre-lock resolve is gone, so there is one resolve rather than two, and deleteStream holding the same monitor still makes a concurrently deleted stream fail cleanly. Residual, pre-existing and not addressed here: AccountAwareStorageBackend.get still adopts an unprefixed entry into the request account unchecked and unsynchronized for callers that do not hold a per-resource lock. * fix(storage): migrate a legacy unprefixed entry under the account monitor AccountAwareStorageBackend has two migrate-on-read paths that disagree. getForAccountMigratingLegacy is synchronized and ownership-gated; get is neither. Because get does not take the monitor the migrating variants hold, two readers resolving the same pre-multi-account key from different account contexts can each copy it into their own partition, and the two copies then diverge independently. The migration branch now runs under that same monitor and re-checks the prefixed key inside it, so a reader that lost the race returns the winner's entry instead of migrating again. The hit path stays outside the monitor, so only a miss pays for it. This closes the fork for every caller rather than one at a time. The preceding commit fixed it for KinesisService.putRecordInternal by resolving inside the append lock, but the Kinesis batch PutRecords handler and roughly twenty read paths (DescribeStream, GetRecords, GetShardIterator, tag reads) resolve without any per-resource lock and were still exposed. Not addressed here: get still adopts an unprefixed entry into whatever account the request context resolves to, with no ownership check. get is generic over the stored type and has no notion of an owner, which is why getForAccountMigratingLegacy takes the predicate from its caller. Gating it generically needs a per-resource-type predicate and is filed separately.
This commit is contained in:
1 parent
148ea6f3db
commit
a9df872956
14 files changed
+1236
-116
No files matched your search
+70
@@ -6,8 +6,16 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AccountAwareStorageBackendTest {
|
||||
@@ -210,4 +218,66 @@ class AccountAwareStorageBackendTest {
|
||||
new AccountAwareStorageBackend.AccountEntry<>("000000000000", "us-east-1::legacy", "legacy")),
|
||||
Set.copyOf(storage.scanAllAccountEntries(key -> key.startsWith("us-east-1::"))));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code get} and {@code getForAccountMigratingLegacy} both migrate a pre-multi-account entry, and
|
||||
* both delete the legacy key once they have copied it. Unless they hold the same monitor, two readers
|
||||
* resolving that key from different account contexts each copy it into their own partition and the two
|
||||
* copies then diverge. Made deterministic by parking the first reader inside its legacy read, at the
|
||||
* exact point where the unsynchronized version let the second reader in.
|
||||
*/
|
||||
@Test
|
||||
void concurrentLegacyMigrationsDoNotForkTheEntryAcrossAccounts() throws Exception {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
raw.put("resource", "v");
|
||||
|
||||
CountDownLatch parked = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
StorageBackend<String, String> parking = new StorageBackend<>() {
|
||||
@Override public void put(String k, String v) { raw.put(k, v); }
|
||||
@Override public void delete(String k) { raw.delete(k); }
|
||||
@Override public List<String> scan(Predicate<String> f) { return raw.scan(f); }
|
||||
@Override public Set<String> keys() { return raw.keys(); }
|
||||
@Override public void flush() { raw.flush(); }
|
||||
@Override public void load() { raw.load(); }
|
||||
@Override public void clear() { raw.clear(); }
|
||||
@Override public Optional<String> get(String k) {
|
||||
if ("resource".equals(k) && parked.getCount() > 0) {
|
||||
parked.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
return raw.get(k);
|
||||
}
|
||||
};
|
||||
AccountAwareStorageBackend<String> storage =
|
||||
new AccountAwareStorageBackend<>(parking, null, "111111111111");
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> ambient = pool.submit(() -> storage.get("resource"));
|
||||
assertTrue(parked.await(2, TimeUnit.SECONDS), "the ambient reader reached its legacy read");
|
||||
|
||||
Future<?> owner = pool.submit(
|
||||
() -> storage.getForAccountMigratingLegacy("222222222222", "resource", v -> true));
|
||||
// The owner must be unable to proceed: without a shared monitor it would migrate a second copy.
|
||||
assertThrows(TimeoutException.class, () -> owner.get(300, TimeUnit.MILLISECONDS),
|
||||
"the second migration ran concurrently with the first");
|
||||
|
||||
release.countDown();
|
||||
ambient.get(2, TimeUnit.SECONDS);
|
||||
owner.get(2, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
assertTrue(raw.get("resource").isEmpty(), "the legacy key is consumed exactly once");
|
||||
long copies = List.of("111111111111/resource", "222222222222/resource").stream()
|
||||
.filter(k -> raw.get(k).isPresent())
|
||||
.count();
|
||||
assertEquals(1, copies, "the entry landed in exactly one account partition, not forked into both");
|
||||
}
|
||||
}
|
||||
+5
@@ -542,6 +542,11 @@ class DynamoDbConcurrencyIntegrationTest {
|
||||
});
|
||||
assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors);
|
||||
|
||||
// CDC delivery is asynchronous (bounded best-effort retry queue): wait for the background drain to
|
||||
// flush every buffered record before reading the shard, otherwise this reads a partial stream.
|
||||
assertTrue(forwarder.awaitIdle(java.time.Duration.ofSeconds(10)),
|
||||
"the CDC drain must flush all buffered records");
|
||||
|
||||
// Paginated drain of the single shard.
|
||||
String shardId = kinesis.describeStream("cdc-stream", region).getShards().getFirst().getShardId();
|
||||
String iterator = kinesis.getShardIterator("cdc-stream", shardId, "TRIM_HORIZON", null, region);
|
||||
|
||||
+14
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -12,6 +13,7 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
@@ -26,11 +28,20 @@ class DynamoDbKinesisStreamingIntegrationTest {
|
||||
private static final String KINESIS_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static String kinesisStreamArn;
|
||||
|
||||
// CDC forwarding is asynchronous (bounded best-effort retry queue): after a write enqueues, the send
|
||||
// happens on a background drain. Await it before reading the stream so these assertions are deterministic.
|
||||
@Inject
|
||||
KinesisStreamingForwarder forwarder;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private void awaitCdcDelivery() {
|
||||
forwarder.awaitIdle(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void setupKinesisStream() {
|
||||
@@ -178,6 +189,7 @@ class DynamoDbKinesisStreamingIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
awaitCdcDelivery();
|
||||
String shardIterator = given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
@@ -248,6 +260,7 @@ class DynamoDbKinesisStreamingIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
awaitCdcDelivery();
|
||||
String shardIterator = given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
@@ -292,6 +305,7 @@ class DynamoDbKinesisStreamingIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
awaitCdcDelivery();
|
||||
String shardIterator = given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
|
||||
.contentType(KINESIS_CONTENT_TYPE)
|
||||
|
||||
+31
-8
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
@@ -27,15 +28,30 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* TTL sweep must forward a REMOVE per expired item to Kinesis (happy path) and must isolate
|
||||
* forwarding failures: a throwing forwarder cannot abort the sweep or block persistence.
|
||||
* See issue #571.
|
||||
* forwarding from Kinesis health: because forwarding is now enqueue-only (delivered/retried on a
|
||||
* background drain, see {@link KinesisStreamingForwarderTest}), a broken Kinesis cannot abort the
|
||||
* sweep, block persistence, or silently drop the change events. See issue #571.
|
||||
*/
|
||||
class DynamoDbTtlForwardingTest {
|
||||
|
||||
/** A Scheduler that never runs the drain, so buffered CDC records stay put for inspection. */
|
||||
private static final KinesisStreamingForwarder.Scheduler NO_DRAIN =
|
||||
new KinesisStreamingForwarder.Scheduler() {
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMillis) {
|
||||
// intentionally never executes the drain
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
}
|
||||
};
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
@@ -109,6 +125,8 @@ class DynamoDbTtlForwardingTest {
|
||||
table.getKinesisStreamingDestinations().add(new KinesisStreamingDestination(stream.getStreamArn()));
|
||||
|
||||
svc.deleteExpiredItems();
|
||||
// Delivery is asynchronous now; wait for the background drain to flush before reading the stream.
|
||||
assertTrue(forwarder.awaitIdle(Duration.ofSeconds(5)), "CDC forwards should drain promptly");
|
||||
|
||||
List<KinesisRecord> drained = drain(kinesis, "ttl-stream");
|
||||
assertEquals(expired, drained.size(), "one Kinesis record per expired item");
|
||||
@@ -131,9 +149,9 @@ class DynamoDbTtlForwardingTest {
|
||||
StorageBackend<String, Map<String, JsonNode>> itemStore = new InMemoryStorage<>();
|
||||
|
||||
KinesisService throwingKinesis = mock(KinesisService.class);
|
||||
when(throwingKinesis.putRecord(anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("kinesis unavailable"));
|
||||
KinesisStreamingForwarder forwarder = new KinesisStreamingForwarder(throwingKinesis, mapper);
|
||||
// No-drain scheduler: the sweep only ENQUEUES, so Kinesis is never touched during the sweep at
|
||||
// all. (Retry/give-up drop accounting on the drain is covered by KinesisStreamingForwarderTest.)
|
||||
KinesisStreamingForwarder forwarder = new KinesisStreamingForwarder(throwingKinesis, mapper, NO_DRAIN);
|
||||
DynamoDbService svc = new DynamoDbService(
|
||||
tableStore, itemStore, new RegionResolver("us-east-1", "000000000000"), null, forwarder);
|
||||
|
||||
@@ -143,11 +161,16 @@ class DynamoDbTtlForwardingTest {
|
||||
table.getKinesisStreamingDestinations().add(new KinesisStreamingDestination(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/ttl-stream"));
|
||||
|
||||
// A forwarding failure must not propagate out of the sweep.
|
||||
// A dead Kinesis must not propagate out of the sweep, and must not be called synchronously by it.
|
||||
assertDoesNotThrow(svc::deleteExpiredItems);
|
||||
verifyNoInteractions(throwingKinesis);
|
||||
|
||||
assertEquals(expired, forwarder.getForwardFailureCount(),
|
||||
"each failed forward must be counted, not swallowed silently");
|
||||
// Every expired change event is safely BUFFERED (not silently dropped): the fix for the
|
||||
// drop-on-forward-exception gap. The drain would deliver these once Kinesis recovers.
|
||||
List<DestinationForwardingStats> stats = forwarder.forwardingStats();
|
||||
assertEquals(1, stats.size());
|
||||
assertEquals(expired, stats.get(0).queueDepth(), "each expired item's REMOVE must be enqueued");
|
||||
assertEquals(0L, forwarder.getForwardFailureCount(), "buffered records are not (yet) dropped");
|
||||
|
||||
// Removed in-memory AND persisted: a fresh service over the same stores must not see them.
|
||||
for (int i = 0; i < expired; i++) {
|
||||
|
||||
+447
-46
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination;
|
||||
@@ -10,96 +11,496 @@ import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
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;
|
||||
|
||||
/**
|
||||
* The CDC delivery contract (issue: DynamoDB→Kinesis records dropped on forward exception).
|
||||
*
|
||||
* <p>{@code forward} is proven ENQUEUE-ONLY (no synchronous Kinesis I/O, never throws); the actual send,
|
||||
* retry, terminal-drop, give-up, overflow, FIFO, and lifecycle behaviour are exercised deterministically
|
||||
* by driving a manual {@link KinesisStreamingForwarder.Scheduler} step by step: no real timers, no sleeps
|
||||
* in the delivery assertions.
|
||||
*/
|
||||
class KinesisStreamingForwarderTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String STREAM_ARN = "arn:aws:kinesis:us-east-1:000000000000:stream/test-stream";
|
||||
|
||||
private KinesisService kinesisService;
|
||||
private KinesisStreamingForwarder forwarder;
|
||||
private ObjectMapper objectMapper;
|
||||
private ManualScheduler scheduler;
|
||||
private KinesisStreamingForwarder forwarder;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
kinesisService = mock(KinesisService.class);
|
||||
objectMapper = new ObjectMapper();
|
||||
forwarder = new KinesisStreamingForwarder(kinesisService, objectMapper);
|
||||
scheduler = new ManualScheduler();
|
||||
forwarder = new KinesisStreamingForwarder(kinesisService, objectMapper, scheduler);
|
||||
}
|
||||
|
||||
private TableDefinition createTable(String tableName) {
|
||||
return new TableDefinition(tableName,
|
||||
// ──────────────────────────── helpers ────────────────────────────
|
||||
|
||||
/** A Scheduler the test drives by hand: tasks queue up and run only when the test asks. */
|
||||
static final class ManualScheduler implements KinesisStreamingForwarder.Scheduler {
|
||||
final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
|
||||
final List<Long> delays = new ArrayList<>();
|
||||
boolean shutdown;
|
||||
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMillis) {
|
||||
tasks.addLast(task);
|
||||
delays.add(delayMillis);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
shutdown = true;
|
||||
}
|
||||
|
||||
boolean runOne() {
|
||||
Runnable r = tasks.pollFirst();
|
||||
if (r == null) {
|
||||
return false;
|
||||
}
|
||||
r.run();
|
||||
return true;
|
||||
}
|
||||
|
||||
int runUntilQuiet() {
|
||||
int steps = 0;
|
||||
while (steps < 20_000 && runOne()) {
|
||||
steps++;
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
}
|
||||
|
||||
/** A Scheduler that rejects while {@code reject} is set (executor-shutdown simulation), else queues. */
|
||||
static final class RejectingScheduler implements KinesisStreamingForwarder.Scheduler {
|
||||
final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
|
||||
boolean reject = true;
|
||||
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMillis) {
|
||||
if (reject) {
|
||||
throw new RejectedExecutionException("executor is shutting down");
|
||||
}
|
||||
tasks.addLast(task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
}
|
||||
|
||||
boolean runOne() {
|
||||
Runnable r = tasks.pollFirst();
|
||||
if (r == null) {
|
||||
return false;
|
||||
}
|
||||
r.run();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private TableDefinition tableWithDestination(String... streamArns) {
|
||||
TableDefinition table = new TableDefinition("test-table",
|
||||
List.of(new KeySchemaElement("pk", "HASH")),
|
||||
List.of(new AttributeDefinition("pk", "S")));
|
||||
for (String arn : streamArns) {
|
||||
table.getKinesisStreamingDestinations().add(new KinesisStreamingDestination(arn));
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
private ObjectNode createItem(String pk) {
|
||||
ObjectNode item = objectMapper.createObjectNode();
|
||||
private ObjectNode item(String pk) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
ObjectNode pkValue = objectMapper.createObjectNode();
|
||||
pkValue.put("S", pk);
|
||||
item.set("pk", pkValue);
|
||||
return item;
|
||||
node.set("pk", pkValue);
|
||||
return node;
|
||||
}
|
||||
|
||||
private DestinationForwardingStats onlyStat() {
|
||||
List<DestinationForwardingStats> stats = forwarder.forwardingStats();
|
||||
assertEquals(1, stats.size(), "expected exactly one destination state");
|
||||
return stats.get(0);
|
||||
}
|
||||
|
||||
// ──────────────────────────── enqueue path ────────────────────────────
|
||||
|
||||
@Test
|
||||
void forwardsToActiveDestination() {
|
||||
TableDefinition table = createTable("test-table");
|
||||
KinesisStreamingDestination dest = new KinesisStreamingDestination(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/test-stream");
|
||||
table.getKinesisStreamingDestinations().add(dest);
|
||||
void forwardOnlyEnqueues_neverCallsKinesisSynchronouslyNorThrows() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("kinesis down"));
|
||||
|
||||
when(kinesisService.putRecord(anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenReturn("seq-1");
|
||||
assertDoesNotThrow(() -> forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT));
|
||||
|
||||
forwarder.forward("INSERT", null, createItem("k1"), table, "us-east-1");
|
||||
|
||||
verify(kinesisService).putRecord(eq("test-stream"), any(byte[].class), eq("k1"), eq("us-east-1"));
|
||||
// The write path did no Kinesis I/O: the record is buffered, not delivered and not dropped.
|
||||
verifyNoInteractions(kinesisService);
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(1, s.queueDepth());
|
||||
assertEquals(0L, s.forwarded());
|
||||
assertEquals(0L, s.dropped());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsDisabledDestination() {
|
||||
TableDefinition table = createTable("test-table");
|
||||
KinesisStreamingDestination dest = new KinesisStreamingDestination(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/test-stream");
|
||||
dest.setDestinationStatus("DISABLED");
|
||||
table.getKinesisStreamingDestinations().add(dest);
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
table.getKinesisStreamingDestinations().get(0).setDestinationStatus("DISABLED");
|
||||
|
||||
forwarder.forward("INSERT", null, createItem("k1"), table, "us-east-1");
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
|
||||
verifyNoInteractions(kinesisService);
|
||||
assertTrue(forwarder.forwardingStats().isEmpty(), "a disabled destination is never enqueued");
|
||||
assertFalse(scheduler.runOne(), "nothing scheduled for a disabled destination");
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsWhenNoDestinations() {
|
||||
TableDefinition table = createTable("test-table");
|
||||
forwarder.forward("INSERT", null, item("k1"), tableWithDestination(), "us-east-1", ACCOUNT);
|
||||
verifyNoInteractions(kinesisService);
|
||||
assertTrue(forwarder.forwardingStats().isEmpty());
|
||||
}
|
||||
|
||||
forwarder.forward("INSERT", null, createItem("k1"), table, "us-east-1");
|
||||
// ──────────────────────────── happy-path drain ────────────────────────────
|
||||
|
||||
@Test
|
||||
void deliversBufferedRecordOnDrain() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenReturn("seq-1");
|
||||
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
verify(kinesisService).putRecordForAccount(eq(ACCOUNT), eq("test-stream"), any(byte[].class),
|
||||
eq("k1"), eq("us-east-1"));
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(1L, s.forwarded());
|
||||
assertEquals(0, s.queueDepth());
|
||||
assertEquals("HEALTHY", s.health());
|
||||
}
|
||||
|
||||
@Test
|
||||
void threadsTableOwnerAccountToThePut() {
|
||||
// The owning account is threaded through so an out-of-request-scope forward lands in the owner's stream.
|
||||
TableDefinition table = tableWithDestination("arn:aws:kinesis:us-east-1:111111111111:stream/test-stream");
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenReturn("seq-1");
|
||||
|
||||
forwarder.forward("REMOVE", item("k1"), null, table, "us-east-1", "111111111111");
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
verify(kinesisService).putRecordForAccount(eq("111111111111"), eq("test-stream"), any(byte[].class),
|
||||
eq("k1"), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesFifoAcrossARetry() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
List<String> delivered = new ArrayList<>();
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
if (calls.getAndIncrement() == 0) {
|
||||
throw new RuntimeException("transient on the very first attempt");
|
||||
}
|
||||
delivered.add(inv.getArgument(3)); // partitionKey
|
||||
return "seq";
|
||||
});
|
||||
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
forwarder.forward("INSERT", null, item("k2"), table, "us-east-1", ACCOUNT);
|
||||
forwarder.forward("INSERT", null, item("k3"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
// k1 was retried, yet ordering is preserved: the head is not skipped past.
|
||||
assertEquals(List.of("k1", "k2", "k3"), delivered);
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(3L, s.forwarded());
|
||||
assertEquals(1L, s.retried());
|
||||
assertEquals(0L, s.dropped());
|
||||
}
|
||||
|
||||
// ──────────────────────────── failure classification ────────────────────────────
|
||||
|
||||
@Test
|
||||
void unknownFailureIsRetriedNotDropped() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("transient"));
|
||||
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runOne(); // exactly one drain attempt
|
||||
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(1, s.queueDepth(), "an unknown failure keeps the record buffered for retry");
|
||||
assertEquals(0L, s.dropped());
|
||||
assertEquals(1L, s.retried());
|
||||
assertEquals("RETRYING", s.health());
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminalFailureDropsThePoisonRecordWithoutWedgingTheQueue() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
List<String> delivered = new ArrayList<>();
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
String pk = inv.getArgument(3);
|
||||
if ("k1".equals(pk)) {
|
||||
throw new AwsException("ValidationException", "record too large", 400);
|
||||
}
|
||||
delivered.add(pk);
|
||||
return "seq";
|
||||
});
|
||||
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT); // poison
|
||||
forwarder.forward("INSERT", null, item("k2"), table, "us-east-1", ACCOUNT); // good
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
// The poison record is dropped immediately; the good record behind it is still delivered.
|
||||
assertEquals(List.of("k2"), delivered);
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(1L, s.dropped());
|
||||
assertEquals(1L, s.forwarded());
|
||||
assertEquals("ValidationException", s.lastErrorType());
|
||||
assertEquals(1L, forwarder.getForwardFailureCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givesUpAfterProbeBudgetThenSelfHealsOnALaterEvent() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
AtomicBoolean healthy = new AtomicBoolean(false);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
if (!healthy.get()) {
|
||||
throw new RuntimeException("stream unavailable");
|
||||
}
|
||||
return "seq";
|
||||
});
|
||||
|
||||
// Episode 1: persistent failure exhausts the probe budget and drops the buffered record.
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
DestinationForwardingStats gaveUp = onlyStat();
|
||||
assertEquals("GAVE_UP", gaveUp.health());
|
||||
assertEquals(1L, gaveUp.dropped());
|
||||
assertEquals(0, gaveUp.queueDepth());
|
||||
// Exactly MAX_PROBES (10) send attempts: the initial immediate run + 9 retry schedules, backoff
|
||||
// 250ms doubling to the 8s cap. Give-up fires on the 10th failure (no 11th schedule).
|
||||
assertEquals(List.of(0L, 250L, 500L, 1000L, 2000L, 4000L, 8000L, 8000L, 8000L, 8000L),
|
||||
List.copyOf(scheduler.delays));
|
||||
|
||||
// Episode 2: a fresh event with a recovered stream re-attempts (budget was reset) and heals.
|
||||
healthy.set(true);
|
||||
forwarder.forward("INSERT", null, item("k2"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
DestinationForwardingStats healed = onlyStat();
|
||||
assertEquals("HEALTHY", healed.health());
|
||||
assertEquals(1L, healed.forwarded());
|
||||
assertEquals(1L, healed.dropped(), "the episode-1 drop is retained in the cumulative count");
|
||||
assertEquals(0, healed.queueDepth());
|
||||
}
|
||||
|
||||
// ──────────────────────────── overflow ────────────────────────────
|
||||
|
||||
@Test
|
||||
void overflowDropsOldestBeyondTheBufferCap() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
int over = 2;
|
||||
for (int i = 0; i < KinesisStreamingForwarder.MAX_BUFFERED + over; i++) {
|
||||
forwarder.forward("INSERT", null, item("k" + i), table, "us-east-1", ACCOUNT);
|
||||
}
|
||||
// Never drained: the buffer is capped and the oldest are evicted.
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(KinesisStreamingForwarder.MAX_BUFFERED, s.queueDepth());
|
||||
assertEquals(over, s.overflowed());
|
||||
assertEquals(over, s.dropped());
|
||||
assertEquals(over, forwarder.getForwardFailureCount());
|
||||
}
|
||||
|
||||
// ──────────────────────────── lifecycle ────────────────────────────
|
||||
|
||||
@Test
|
||||
void disableDiscardsBufferAndStalesTheInFlightDrain() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
|
||||
forwarder.onDestinationDisabled(ACCOUNT, "us-east-1", "test-table", STREAM_ARN);
|
||||
|
||||
DestinationForwardingStats s = onlyStat(); // state retained on disable
|
||||
assertEquals(0, s.queueDepth());
|
||||
assertEquals(1L, s.discardedOnDisable());
|
||||
|
||||
// The drain scheduled before the disable is now stale: running it is a no-op (epoch bumped).
|
||||
scheduler.runUntilQuiet();
|
||||
verifyNoInteractions(kinesisService);
|
||||
assertEquals(0L, onlyStat().forwarded());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableDeleteRemovesStateAndStalesTheInFlightDrain() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
|
||||
forwarder.onTableDeleted(ACCOUNT, "us-east-1", "test-table");
|
||||
|
||||
assertTrue(forwarder.forwardingStats().isEmpty(), "table delete drops the destination state");
|
||||
scheduler.runUntilQuiet();
|
||||
verifyNoInteractions(kinesisService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuesOnPutRecordFailure() {
|
||||
TableDefinition table = createTable("test-table");
|
||||
KinesisStreamingDestination dest1 = new KinesisStreamingDestination(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/stream-1");
|
||||
KinesisStreamingDestination dest2 = new KinesisStreamingDestination(
|
||||
"arn:aws:kinesis:us-east-1:000000000000:stream/stream-2");
|
||||
table.getKinesisStreamingDestinations().add(dest1);
|
||||
table.getKinesisStreamingDestinations().add(dest2);
|
||||
void awaitIdleReflectsQueueState() {
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenReturn("seq");
|
||||
|
||||
when(kinesisService.putRecord(eq("stream-1"), any(byte[].class), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("stream-1 failed"));
|
||||
when(kinesisService.putRecord(eq("stream-2"), any(byte[].class), anyString(), anyString()))
|
||||
.thenReturn("seq-1");
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
assertFalse(forwarder.awaitIdle(Duration.ofMillis(50)), "buffered + drain pending is not idle");
|
||||
|
||||
forwarder.forward("INSERT", null, createItem("k1"), table, "us-east-1");
|
||||
scheduler.runUntilQuiet();
|
||||
assertTrue(forwarder.awaitIdle(Duration.ofMillis(50)), "drained empty is idle");
|
||||
}
|
||||
|
||||
verify(kinesisService).putRecord(eq("stream-1"), any(byte[].class), anyString(), anyString());
|
||||
verify(kinesisService).putRecord(eq("stream-2"), any(byte[].class), anyString(), anyString());
|
||||
assertEquals(1L, forwarder.getForwardFailureCount(),
|
||||
"the single failed forward must be counted");
|
||||
// ──────────────────────────── race / robustness ────────────────────────────
|
||||
|
||||
@Test
|
||||
void overflowWhileTheHeadIsInFlightNeverEvictsTheRecordBeingSent() {
|
||||
// Deterministically reproduces the overflow-vs-in-flight race: while k0 is being sent, a burst of
|
||||
// producers overfills the buffer. The in-flight record must not be evicted, and nothing may be lost
|
||||
// without accounting (the peek-then-poll approach would evict k0 and then poll a different record).
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
int burst = KinesisStreamingForwarder.MAX_BUFFERED + 5;
|
||||
List<String> delivered = new ArrayList<>();
|
||||
AtomicBoolean filled = new AtomicBoolean(false);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
String pk = inv.getArgument(3);
|
||||
if ("k0".equals(pk) && filled.compareAndSet(false, true)) {
|
||||
for (int i = 1; i <= burst; i++) {
|
||||
forwarder.forward("INSERT", null, item("k" + i), table, "us-east-1", ACCOUNT);
|
||||
}
|
||||
}
|
||||
delivered.add(pk);
|
||||
return "seq";
|
||||
});
|
||||
|
||||
forwarder.forward("INSERT", null, item("k0"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
// k0 (in flight during the overflow) was delivered, not evicted; the 5 oldest buffered were dropped.
|
||||
assertEquals("k0", delivered.get(0));
|
||||
assertFalse(delivered.contains("k1"), "the oldest buffered record is the overflow victim, not k0");
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(5L, s.overflowed());
|
||||
assertEquals(5L, s.dropped());
|
||||
assertEquals(burst + 1 - 5, s.forwarded());
|
||||
// Every one of the burst+1 records is accounted for exactly once: no silent loss.
|
||||
assertEquals(burst + 1, s.forwarded() + s.dropped());
|
||||
assertEquals(0, s.queueDepth());
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulerRejectionNeitherEscapesForwardNorWedgesTheDestination() {
|
||||
RejectingScheduler rejecting = new RejectingScheduler();
|
||||
KinesisStreamingForwarder f = new KinesisStreamingForwarder(kinesisService, objectMapper, rejecting);
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenReturn("seq");
|
||||
|
||||
// Executor down: scheduling the initial drain is rejected, but forward must not throw, and the
|
||||
// record stays buffered (not dropped).
|
||||
assertDoesNotThrow(() -> f.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT));
|
||||
assertEquals(1, f.forwardingStats().get(0).queueDepth());
|
||||
|
||||
// Executor recovers: a later event must be able to schedule a fresh drain (no wedge), and BOTH the
|
||||
// previously-buffered and the new record drain in FIFO order.
|
||||
rejecting.reject = false;
|
||||
f.forward("INSERT", null, item("k2"), table, "us-east-1", ACCOUNT);
|
||||
while (rejecting.runOne()) {
|
||||
// drive the recovered drain to completion
|
||||
}
|
||||
DestinationForwardingStats s = f.forwardingStats().get(0);
|
||||
assertEquals(2L, s.forwarded());
|
||||
assertEquals(0, s.queueDepth());
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminalHeadDropGivesTheNextRecordItsOwnFullProbeBudget() {
|
||||
// k1 fails transiently then terminally; k2 must then get a FRESH MAX_PROBES budget, not the leftover.
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
Map<String, Integer> attempts = new HashMap<>();
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
String pk = inv.getArgument(3);
|
||||
int n = attempts.merge(pk, 1, Integer::sum);
|
||||
if ("k1".equals(pk)) {
|
||||
if (n <= 3) {
|
||||
throw new RuntimeException("transient");
|
||||
}
|
||||
throw new AwsException("ValidationException", "poison", 400); // 4th attempt: terminal
|
||||
}
|
||||
throw new RuntimeException("k2 stream down"); // k2 always transient
|
||||
});
|
||||
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
forwarder.forward("INSERT", null, item("k2"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
assertEquals(4, attempts.get("k1"), "3 transient retries then the terminal attempt");
|
||||
// If the budget had not been reset on the terminal drop, k2 would give up after only
|
||||
// MAX_PROBES - 3 attempts. A fresh budget means exactly MAX_PROBES attempts for k2.
|
||||
assertEquals(KinesisStreamingForwarder.MAX_PROBES, attempts.get("k2"));
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(2L, s.dropped()); // k1 (terminal) + k2 (give-up)
|
||||
assertEquals("GAVE_UP", s.health());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableDuringInFlightSendCompletesButDoesNotResurrectOrDoubleCount() {
|
||||
// Characterizes the inherent teardown race (documented as best-effort): a send dispatched before a
|
||||
// disable may complete, but the torn-down destination is neither re-counted nor resurrected.
|
||||
TableDefinition table = tableWithDestination(STREAM_ARN);
|
||||
when(kinesisService.putRecordForAccount(anyString(), anyString(), any(byte[].class), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
forwarder.onDestinationDisabled(ACCOUNT, "us-east-1", "test-table", STREAM_ARN);
|
||||
return "seq";
|
||||
});
|
||||
|
||||
forwarder.forward("INSERT", null, item("k1"), table, "us-east-1", ACCOUNT);
|
||||
scheduler.runUntilQuiet();
|
||||
|
||||
// The dispatched send ran exactly once; its result is discarded (epoch bumped), the buffer is empty,
|
||||
// and no further drain runs.
|
||||
verify(kinesisService, times(1)).putRecordForAccount(anyString(), anyString(), any(byte[].class),
|
||||
anyString(), anyString());
|
||||
DestinationForwardingStats s = onlyStat();
|
||||
assertEquals(0, s.queueDepth());
|
||||
assertEquals(0L, s.forwarded());
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package io.github.hectorvent.floci.services.kinesis;
|
||||
|
||||
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.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisConsumer;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Verifies that {@code putRecordForAccount} resolves, persists, and legacy-migrates against the SPECIFIED
|
||||
* account rather than the ambient/default one, so an out-of-request-scope producer (TTL sweep, CDC
|
||||
* forwarding) never writes into another tenant's same-named stream and keeps working after an upgrade
|
||||
* from unprefixed (pre-multi-account) storage. Real {@link KinesisService} over in-memory account-aware
|
||||
* storage (no Vert.x → runs in the offline sandbox).
|
||||
*/
|
||||
class KinesisServiceAccountTest {
|
||||
|
||||
private static final String KEY_S = "us-east-1::s";
|
||||
// jsr310 module registered so cloning a shard's Instant (creationTimestamp) round-trips.
|
||||
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
|
||||
|
||||
private KinesisService serviceOver(AccountAwareStorageBackend<KinesisStream> streams) {
|
||||
return new KinesisService(streams, AccountAwareStorageBackend.inMemory("000000000000"),
|
||||
mock(RegionResolver.class));
|
||||
}
|
||||
|
||||
private static int recordCount(KinesisStream stream) {
|
||||
return stream.getShards().stream().mapToInt(KinesisShard::recordCount).sum();
|
||||
}
|
||||
|
||||
private KinesisStream cloneStream(KinesisStream template) {
|
||||
try {
|
||||
return mapper.treeToValue(mapper.valueToTree(template), KinesisStream.class);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordForAccountResolvesAgainstThatAccountNotDefault() {
|
||||
KinesisService svc = serviceOver(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
svc.createStream("s", 1, "us-east-1"); // created in the ambient/default account (000000000000)
|
||||
byte[] data = "x".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
assertNotNull(svc.putRecord("s", data, "pk", "us-east-1"));
|
||||
assertNotNull(svc.putRecordForAccount(null, "s", data, "pk", "us-east-1"));
|
||||
assertNotNull(svc.putRecordForAccount("000000000000", "s", data, "pk", "us-east-1"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> svc.putRecordForAccount("111111111111", "s", data, "pk", "us-east-1"));
|
||||
assertEquals("ResourceNotFoundException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordForAccountPersistsToThatAccountPartition() {
|
||||
AccountAwareStorageBackend<KinesisStream> streams = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
KinesisService svc = serviceOver(streams);
|
||||
svc.createStream("s", 1, "us-east-1"); // in the default account
|
||||
// Seed an INDEPENDENT same-named stream in account 111 (deep copy so the append can't leak back).
|
||||
KinesisStream in111 = cloneStream(streams.getForAccount("000000000000", KEY_S).orElseThrow());
|
||||
streams.putForAccount("111111111111", KEY_S, in111);
|
||||
|
||||
svc.putRecordForAccount("111111111111", "s", "x".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
|
||||
// Persisted into account 111's partition only; the default partition is untouched. (A regression
|
||||
// that used the ambient put would land the record in the default account here.)
|
||||
assertEquals(1, recordCount(streams.getForAccount("111111111111", KEY_S).orElseThrow()));
|
||||
assertEquals(0, recordCount(streams.getForAccount("000000000000", KEY_S).orElseThrow()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRecordForAccountMigratesLegacyUnprefixedStream() {
|
||||
// Upgrade scenario: a pre-multi-account (unprefixed) stream owned by account 111 exists in the
|
||||
// raw delegate. An out-of-request-scope forward for 111 must migrate + use it, not drop as RNF.
|
||||
InMemoryStorage<String, KinesisStream> raw = new InMemoryStorage<>();
|
||||
AccountAwareStorageBackend<KinesisStream> streams = new AccountAwareStorageBackend<>(raw, null, "000000000000");
|
||||
KinesisService svc = serviceOver(streams);
|
||||
|
||||
// Build a shard-carrying stream (via createStream on a throwaway key) and place a copy under the
|
||||
// UNPREFIXED legacy key, owned (by ARN) by account 111.
|
||||
KinesisStream legacy = cloneStream(svc.createStream("tmpl", 1, "us-east-1"));
|
||||
legacy.setStreamArn("arn:aws:kinesis:us-east-1:111111111111:stream/s2");
|
||||
raw.put("us-east-1::s2", legacy); // unprefixed = legacy pre-multi-account data
|
||||
|
||||
// Migrates on write and appends; no ResourceNotFoundException.
|
||||
assertNotNull(svc.putRecordForAccount("111111111111", "s2", "x".getBytes(StandardCharsets.UTF_8),
|
||||
"pk", "us-east-1"));
|
||||
// The record is now in account 111's partition (migrated).
|
||||
assertEquals(1, recordCount(streams.getForAccount("111111111111", "us-east-1::s2").orElseThrow()));
|
||||
}
|
||||
}
|
||||
@@ -835,7 +835,8 @@ class KinesisServiceTest {
|
||||
* append lock, the producer must fail cleanly (ResourceNotFoundException) rather than append to
|
||||
* and re-persist the stale instance. Deterministic via the pre-lock hook: the producer parks
|
||||
* WITHOUT holding the monitor, so the deleter wins the lock first. Fails on code lacking the
|
||||
* in-lock re-resolve: the producer would resurrect the stream and throw nothing.
|
||||
* in-lock resolve: a producer that resolved before the lock would append to and re-persist the
|
||||
* stale pre-delete instance, resurrecting the stream and throwing nothing.
|
||||
*/
|
||||
@Test
|
||||
void putRecord_failsCleanly_whenStreamDeletedBeforeLockAcquired() throws Exception {
|
||||
|
||||
Reference in new issue
Block a user