mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -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
+16
-6
@@ -66,13 +66,23 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
if (result.isPresent()) {
|
||||
return result;
|
||||
}
|
||||
// Backward-compat: try un-prefixed key (pre-multi-account data) and migrate on read.
|
||||
result = delegate.get(key);
|
||||
if (result.isPresent()) {
|
||||
delegate.put(prefixedKey, result.get());
|
||||
delegate.delete(key);
|
||||
// Backward-compat: try un-prefixed key (pre-multi-account data) and migrate on read. The
|
||||
// migration is a write (put then delete), so it runs under the same monitor the explicit-account
|
||||
// migrators hold, or two readers resolving the same legacy key from different account contexts
|
||||
// would each copy it into their own partition and the two copies would then diverge. The hit
|
||||
// path above stays outside the monitor, so only a miss pays for it.
|
||||
synchronized (this) {
|
||||
Optional<V> migratedByAnotherReader = delegate.get(prefixedKey);
|
||||
if (migratedByAnotherReader.isPresent()) {
|
||||
return migratedByAnotherReader;
|
||||
}
|
||||
result = delegate.get(key);
|
||||
if (result.isPresent()) {
|
||||
delegate.put(prefixedKey, result.get());
|
||||
delegate.delete(key);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
/**
|
||||
* An immutable snapshot of a single Kinesis CDC destination's forwarding health, produced by
|
||||
* {@link KinesisStreamingForwarder#forwardingStats()}. Copied under the destination's monitor so
|
||||
* the counters and queue depth are internally consistent.
|
||||
*
|
||||
* @param health one of HEALTHY, RETRYING, GAVE_UP
|
||||
*/
|
||||
record DestinationForwardingStats(
|
||||
String health,
|
||||
long forwarded,
|
||||
long retried,
|
||||
long dropped,
|
||||
long overflowed,
|
||||
long discardedOnDisable,
|
||||
int queueDepth,
|
||||
String lastErrorType) {
|
||||
}
|
||||
@@ -1853,6 +1853,8 @@ public class DynamoDbJsonHandler {
|
||||
existing.get().setDestinationStatus("DISABLED");
|
||||
existing.get().setDestinationStatusDescription("Kinesis streaming is disabled for this table");
|
||||
dynamoDbService.persistTable(resolvedTableName, table, region);
|
||||
// Stop forwarding and discard buffered CDC records for this now-disabled destination.
|
||||
dynamoDbService.onKinesisStreamingDestinationDisabled(resolvedTableName, streamArn, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("TableName", resolvedTableName);
|
||||
|
||||
@@ -480,9 +480,24 @@ public class DynamoDbService implements ResourceProvider {
|
||||
if (streamService != null) {
|
||||
streamService.deleteStream(canonicalTableName, region);
|
||||
}
|
||||
if (kinesisForwarder != null) {
|
||||
// Discard any buffered CDC records and stop draining: the destination stream is gone.
|
||||
kinesisForwarder.onTableDeleted(regionResolver.getAccountId(), region, canonicalTableName);
|
||||
}
|
||||
LOG.infov("Deleted table: {0}", canonicalTableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the CDC forwarder that a Kinesis streaming destination was disabled so it discards any
|
||||
* buffered records for it and stops draining. {@code tableName} must be the resolved (canonical)
|
||||
* table name, the same value the forward path keys destination state on. No-op without a forwarder.
|
||||
*/
|
||||
public void onKinesisStreamingDestinationDisabled(String tableName, String streamArn, String region) {
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.onDestinationDisabled(regionResolver.getAccountId(), region, tableName, streamArn);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> listTables(String region) {
|
||||
String prefix = region + "::";
|
||||
return tableStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
@@ -571,12 +586,16 @@ public class DynamoDbService implements ResourceProvider {
|
||||
LOG.tracev("Put item in {0}: key={1} item={2}", canonicalTableName, itemKey, item);
|
||||
|
||||
String eventName = existing == null ? "INSERT" : "MODIFY";
|
||||
// Captured in request scope on purpose: this event may be deferred to the batch drain,
|
||||
// and resolving the account inside the lambda would fall back to the default account,
|
||||
// which is the ambient-account bug this commit exists to remove.
|
||||
String ownerAccountId = regionResolver.getAccountId();
|
||||
Runnable streamEvent = () -> {
|
||||
if (streamService != null) {
|
||||
streamService.captureEvent(canonicalTableName, eventName, existing, item, table, region);
|
||||
}
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.forward(eventName, existing, item, table, region);
|
||||
kinesisForwarder.forward(eventName, existing, item, table, region, ownerAccountId);
|
||||
}
|
||||
};
|
||||
if (deferredStreamEvents != null) {
|
||||
@@ -660,12 +679,16 @@ public class DynamoDbService implements ResourceProvider {
|
||||
LOG.tracev("Deleted item from {0}: key={1} removed={2}", canonicalTableName, itemKey, removed);
|
||||
|
||||
if (removed != null) {
|
||||
// Captured in request scope on purpose: this event may be deferred to the batch drain,
|
||||
// and resolving the account inside the lambda would fall back to the default account,
|
||||
// which is the ambient-account bug this commit exists to remove.
|
||||
String ownerAccountId = regionResolver.getAccountId();
|
||||
Runnable streamEvent = () -> {
|
||||
if (streamService != null) {
|
||||
streamService.captureEvent(canonicalTableName, "REMOVE", removed, null, table, region);
|
||||
}
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.forward("REMOVE", removed, null, table, region);
|
||||
kinesisForwarder.forward("REMOVE", removed, null, table, region, ownerAccountId);
|
||||
}
|
||||
};
|
||||
if (deferredStreamEvents != null) {
|
||||
@@ -828,12 +851,16 @@ public class DynamoDbService implements ResourceProvider {
|
||||
LOG.tracev("Updated item in {0}: key={1} updateExpression={2} item={3}",
|
||||
canonicalTableName, itemKey, updateExpression, item);
|
||||
|
||||
// Captured in request scope on purpose: this event may be deferred to the batch drain,
|
||||
// and resolving the account inside the lambda would fall back to the default account,
|
||||
// which is the ambient-account bug this commit exists to remove.
|
||||
String ownerAccountId = regionResolver.getAccountId();
|
||||
Runnable streamEvent = () -> {
|
||||
if (streamService != null) {
|
||||
streamService.captureEvent(canonicalTableName, "MODIFY", existing, item, table, region);
|
||||
}
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.forward("MODIFY", existing, item, table, region);
|
||||
kinesisForwarder.forward("MODIFY", existing, item, table, region, ownerAccountId);
|
||||
}
|
||||
};
|
||||
if (deferredStreamEvents != null) {
|
||||
@@ -1840,7 +1867,9 @@ public class DynamoDbService implements ResourceProvider {
|
||||
streamService.captureEvent(table.getTableName(), "REMOVE", removed, null, table, region);
|
||||
}
|
||||
if (kinesisForwarder != null) {
|
||||
kinesisForwarder.forward("REMOVE", removed, null, table, region);
|
||||
// Out of request scope here: pass the table owner's account explicitly so the CDC
|
||||
// record lands in the owner's stream, not the default account's same-named stream.
|
||||
kinesisForwarder.forward("REMOVE", removed, null, table, region, accountId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+399
-41
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
@@ -7,73 +8,416 @@ import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Forwards DynamoDB change events to Kinesis with a <strong>bounded best-effort, in-process retry</strong>
|
||||
* delivery contract (NOT durable at-least-once: the buffer is in memory and lost on restart).
|
||||
*
|
||||
* <p>The write path only ENQUEUES (it never performs Kinesis I/O or blocks: a slow/dead destination can
|
||||
* neither stall a DynamoDB write nor the TTL sweep). A per-destination single-flight drain, scheduled on a
|
||||
* small daemon pool, performs the actual {@code putRecord} outside the destination lock and:
|
||||
* <ul>
|
||||
* <li>retries transient/unknown failures with capped exponential backoff (≤{@value #MAX_PROBES} probes),</li>
|
||||
* <li>drops a record immediately on a deterministic terminal failure (invalid argument / validation /
|
||||
* serialization) so a poison record cannot wedge the queue,</li>
|
||||
* <li>gives up the whole per-destination episode after the probe budget (dropping the buffered records
|
||||
* and marking the destination GAVE_UP until the next successful send),</li>
|
||||
* <li>preserves per-destination FIFO across retries (stronger than AWS, which may reorder/duplicate),</li>
|
||||
* <li>evicts the oldest buffered record on overflow (max {@value #MAX_BUFFERED} per destination).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The destination's {@code DestinationStatus} is intentionally NOT auto-demoted (AWS has no
|
||||
* delivery-failure status); delivery health is surfaced separately via {@link #forwardingStats()}.
|
||||
* Records dropped/retried are counted and their last error retained for observability.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KinesisStreamingForwarder {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KinesisStreamingForwarder.class);
|
||||
|
||||
static final int MAX_BUFFERED = 1000;
|
||||
static final int MAX_PROBES = 10;
|
||||
static final long INITIAL_BACKOFF_MS = 250;
|
||||
static final long MAX_BACKOFF_MS = 8000;
|
||||
|
||||
/** Schedules drain runs; abstracted so tests can drive drains deterministically. */
|
||||
interface Scheduler {
|
||||
void schedule(Runnable task, long delayMillis);
|
||||
|
||||
void shutdown();
|
||||
}
|
||||
|
||||
enum Health { HEALTHY, RETRYING, GAVE_UP }
|
||||
|
||||
record PendingRecord(String accountId, String region, String streamName, String tableName,
|
||||
byte[] data, String partitionKey, Instant enqueuedAt) {
|
||||
}
|
||||
|
||||
/** Per-destination delivery state. Every field is accessed only while holding {@code this} monitor. */
|
||||
static final class DestinationState {
|
||||
final String key;
|
||||
final String accountId;
|
||||
final String region;
|
||||
final String tableName;
|
||||
final String streamArn;
|
||||
final ArrayDeque<PendingRecord> queue = new ArrayDeque<>();
|
||||
long epoch;
|
||||
int consecutiveFailedProbes;
|
||||
boolean drainScheduled;
|
||||
long forwarded;
|
||||
long retried;
|
||||
long dropped;
|
||||
long overflowed;
|
||||
long discardedOnDisable;
|
||||
String lastErrorType;
|
||||
String lastErrorMessage;
|
||||
Health health = Health.HEALTHY;
|
||||
|
||||
DestinationState(String key, String accountId, String region, String tableName, String streamArn) {
|
||||
this.key = key;
|
||||
this.accountId = accountId;
|
||||
this.region = region;
|
||||
this.tableName = tableName;
|
||||
this.streamArn = streamArn;
|
||||
}
|
||||
}
|
||||
|
||||
private final KinesisService kinesisService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicLong forwardFailures = new AtomicLong();
|
||||
private final Scheduler scheduler;
|
||||
private final ConcurrentHashMap<String, DestinationState> states = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public KinesisStreamingForwarder(KinesisService kinesisService, ObjectMapper objectMapper) {
|
||||
this.kinesisService = kinesisService;
|
||||
this.objectMapper = objectMapper;
|
||||
this(kinesisService, objectMapper, defaultScheduler());
|
||||
}
|
||||
|
||||
public void forward(String eventName, JsonNode oldItem, JsonNode newItem,
|
||||
TableDefinition table, String region) {
|
||||
List<KinesisStreamingDestination> destinations = table.getKinesisStreamingDestinations();
|
||||
if (destinations == null || destinations.isEmpty()) return;
|
||||
/** Test seam: inject a deterministic Scheduler so drains run on demand rather than on real timers. */
|
||||
KinesisStreamingForwarder(KinesisService kinesisService, ObjectMapper objectMapper, Scheduler scheduler) {
|
||||
this.kinesisService = kinesisService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
private static Scheduler defaultScheduler() {
|
||||
ScheduledExecutorService exec = Executors.newScheduledThreadPool(2, r -> {
|
||||
Thread t = new Thread(r, "cdc-forward-drain");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
return new Scheduler() {
|
||||
@Override
|
||||
public void schedule(Runnable task, long delayMillis) {
|
||||
exec.schedule(task, delayMillis, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
exec.shutdownNow();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ──────────────────────────── Enqueue (write path: never blocks, never throws) ────────────────────────────
|
||||
|
||||
public void forward(String eventName, JsonNode oldItem, JsonNode newItem,
|
||||
TableDefinition table, String region, String ownerAccountId) {
|
||||
List<KinesisStreamingDestination> destinations = table.getKinesisStreamingDestinations();
|
||||
if (destinations == null || destinations.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
JsonNode sourceItem = newItem != null ? newItem : oldItem;
|
||||
ObjectNode keys = buildKeys(sourceItem, table);
|
||||
|
||||
byte[] data;
|
||||
String partitionKey;
|
||||
try {
|
||||
ObjectNode payload = buildPayload(eventName, keys, newItem, oldItem, table.getTableName(), region, now);
|
||||
data = objectMapper.writeValueAsBytes(payload);
|
||||
partitionKey = extractPartitionKey(keys, table);
|
||||
} catch (Exception e) {
|
||||
// Serialization is a deterministic terminal failure: nothing can be forwarded for this event.
|
||||
for (KinesisStreamingDestination dest : destinations) {
|
||||
if (!"ACTIVE".equals(dest.getDestinationStatus())) {
|
||||
continue;
|
||||
}
|
||||
DestinationState st = stateFor(ownerAccountId, region, table.getTableName(), dest.getStreamArn());
|
||||
synchronized (st) {
|
||||
st.dropped++;
|
||||
recordError(st, e);
|
||||
}
|
||||
}
|
||||
LOG.errorv(e, "Dropped DynamoDB CDC event for table {0}: failed to serialize payload", table.getTableName());
|
||||
return;
|
||||
}
|
||||
|
||||
for (KinesisStreamingDestination dest : destinations) {
|
||||
if (!"ACTIVE".equals(dest.getDestinationStatus())) continue;
|
||||
|
||||
try {
|
||||
ObjectNode payload = buildPayload(eventName, keys, newItem, oldItem,
|
||||
table.getTableName(), region, now);
|
||||
byte[] data = objectMapper.writeValueAsBytes(payload);
|
||||
|
||||
String partitionKey = extractPartitionKey(keys, table);
|
||||
String streamName = extractStreamName(dest.getStreamArn());
|
||||
|
||||
kinesisService.putRecord(streamName, data, partitionKey, region);
|
||||
LOG.debugv("Forwarded DynamoDB event to Kinesis stream {0}: {1} on {2}",
|
||||
streamName, eventName, table.getTableName());
|
||||
} catch (Exception e) {
|
||||
// Do NOT rethrow: put/delete/update persist before forwarding, so a rethrow would
|
||||
// turn a committed write into a spurious 5xx; the TTL sweep forwards mid-loop and
|
||||
// persists only after the batch, so a rethrow would abort the sweep. Surface the
|
||||
// drop loudly (ERROR + stack trace) and count it for process-local diagnostics.
|
||||
forwardFailures.incrementAndGet();
|
||||
LOG.errorv(e, "Dropped DynamoDB CDC event: failed to forward {0} on table {1} to Kinesis destination {2}",
|
||||
eventName, table.getTableName(), dest.getStreamArn());
|
||||
if (!"ACTIVE".equals(dest.getDestinationStatus())) {
|
||||
continue;
|
||||
}
|
||||
String streamName = extractStreamName(dest.getStreamArn());
|
||||
DestinationState st = stateFor(ownerAccountId, region, table.getTableName(), dest.getStreamArn());
|
||||
PendingRecord rec = new PendingRecord(ownerAccountId, region, streamName, table.getTableName(),
|
||||
data, partitionKey, now);
|
||||
synchronized (st) {
|
||||
if (st.queue.size() >= MAX_BUFFERED) {
|
||||
st.queue.pollFirst(); // drop OLDEST
|
||||
st.overflowed++;
|
||||
st.dropped++;
|
||||
LOG.warnv("CDC buffer full for stream {0} (>{1} records); dropped the oldest",
|
||||
st.streamArn, MAX_BUFFERED);
|
||||
}
|
||||
st.queue.addLast(rec);
|
||||
if (!st.drainScheduled) {
|
||||
scheduleDrain(st, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Process-local count of CDC events dropped because forwarding to Kinesis threw. */
|
||||
public long getForwardFailureCount() {
|
||||
return forwardFailures.get();
|
||||
private DestinationState stateFor(String accountId, String region, String tableName, String streamArn) {
|
||||
String key = accountId + "|" + region + "|" + tableName + "|" + streamArn;
|
||||
return states.computeIfAbsent(key,
|
||||
k -> new DestinationState(k, accountId, region, tableName, streamArn));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Drain (per-destination single-flight; I/O outside the lock) ────────────────────────────
|
||||
|
||||
private void drain(DestinationState st, long scheduledEpoch) {
|
||||
while (true) {
|
||||
PendingRecord head;
|
||||
synchronized (st) {
|
||||
if (scheduledEpoch != st.epoch) {
|
||||
return; // this destination was disabled/deleted; a fresh episode (if any) owns the queue
|
||||
}
|
||||
if (st.queue.isEmpty()) {
|
||||
st.drainScheduled = false;
|
||||
if (st.health != Health.GAVE_UP) {
|
||||
st.health = Health.HEALTHY;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Lease the head OUT of the queue for the duration of the send. A concurrent overflow
|
||||
// eviction can then only drop a still-buffered record, never the one being delivered,
|
||||
// and completion below reconciles exactly this leased record (no blind pollFirst).
|
||||
head = st.queue.pollFirst();
|
||||
}
|
||||
|
||||
boolean success = false;
|
||||
boolean terminal = false;
|
||||
Throwable failure = null;
|
||||
try {
|
||||
if (head.accountId() != null) {
|
||||
kinesisService.putRecordForAccount(head.accountId(), head.streamName(), head.data(),
|
||||
head.partitionKey(), head.region());
|
||||
} else {
|
||||
kinesisService.putRecord(head.streamName(), head.data(), head.partitionKey(), head.region());
|
||||
}
|
||||
success = true;
|
||||
} catch (AwsException e) {
|
||||
failure = e;
|
||||
terminal = isTerminal(e);
|
||||
} catch (Exception e) {
|
||||
failure = e; // unknown/operational failure -> retryable
|
||||
}
|
||||
|
||||
synchronized (st) {
|
||||
if (scheduledEpoch != st.epoch) {
|
||||
// Torn down mid-send: the leased record is discarded along with the rest of the buffer.
|
||||
// The dispatched send may still complete, an inherent and harmless race for an in-memory
|
||||
// emulator (teardown stops all FUTURE sends; it cannot recall one already in flight).
|
||||
return;
|
||||
}
|
||||
if (success) {
|
||||
st.forwarded++;
|
||||
st.consecutiveFailedProbes = 0;
|
||||
st.health = Health.HEALTHY;
|
||||
continue;
|
||||
}
|
||||
recordError(st, failure);
|
||||
if (terminal) {
|
||||
// The leased poison record is already out of the queue: drop it (do NOT wedge) and let
|
||||
// the records behind it flow. Its probe budget dies with it: the next record earns a fresh one.
|
||||
st.dropped++;
|
||||
st.consecutiveFailedProbes = 0;
|
||||
LOG.errorv(failure, "Dropped DynamoDB CDC record (terminal {0}) for stream {1}",
|
||||
st.lastErrorType, st.streamArn);
|
||||
continue;
|
||||
}
|
||||
// retryable: return the leased record to the head so per-destination FIFO is preserved.
|
||||
st.queue.addFirst(head);
|
||||
st.retried++;
|
||||
st.consecutiveFailedProbes++;
|
||||
st.health = Health.RETRYING;
|
||||
if (st.consecutiveFailedProbes >= MAX_PROBES) {
|
||||
long gaveUp = st.queue.size();
|
||||
st.dropped += gaveUp;
|
||||
st.queue.clear();
|
||||
st.health = Health.GAVE_UP;
|
||||
st.drainScheduled = false;
|
||||
// Reset the budget so a later event starts a fresh episode: a transient outage must
|
||||
// not permanently wedge delivery: the next forward re-attempts and self-heals.
|
||||
st.consecutiveFailedProbes = 0;
|
||||
LOG.errorv("CDC delivery gave up for stream {0} after {1} attempts; dropped {2} buffered "
|
||||
+ "record(s). Last error: {3}",
|
||||
st.streamArn, MAX_PROBES, gaveUp, st.lastErrorMessage);
|
||||
return;
|
||||
}
|
||||
scheduleDrain(st, backoff(st.consecutiveFailedProbes));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a drain run. The caller MUST hold {@code st}'s monitor. A scheduler fault (e.g.
|
||||
* {@link java.util.concurrent.RejectedExecutionException} once the executor is shutting down) must
|
||||
* never escape into the DynamoDB write path and must not wedge the destination: on failure the
|
||||
* {@code drainScheduled} flag is cleared so a later event can schedule a fresh drain.
|
||||
*/
|
||||
private void scheduleDrain(DestinationState st, long delayMillis) {
|
||||
st.drainScheduled = true;
|
||||
long ep = st.epoch;
|
||||
try {
|
||||
scheduler.schedule(() -> drain(st, ep), delayMillis);
|
||||
} catch (RuntimeException rex) {
|
||||
st.drainScheduled = false;
|
||||
LOG.warnv(rex, "CDC drain scheduling failed for stream {0}; buffered records await a later event",
|
||||
st.streamArn);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isTerminal(AwsException e) {
|
||||
String code = e.getErrorCode();
|
||||
return "InvalidArgumentException".equals(code) || "ValidationException".equals(code);
|
||||
}
|
||||
|
||||
private static long backoff(int probe) {
|
||||
long shifted = INITIAL_BACKOFF_MS * (1L << Math.min(probe - 1, 20));
|
||||
return Math.min(MAX_BACKOFF_MS, shifted);
|
||||
}
|
||||
|
||||
private static void recordError(DestinationState st, Throwable failure) {
|
||||
st.lastErrorType = failure instanceof AwsException a && a.getErrorCode() != null
|
||||
? a.getErrorCode() : failure.getClass().getSimpleName();
|
||||
st.lastErrorMessage = failure.getMessage();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Lifecycle ────────────────────────────
|
||||
|
||||
/**
|
||||
* Disable of a specific destination: discard its buffer and stop any in-flight drain (epoch bump).
|
||||
* The state is RETAINED (not removed) so its cumulative delivery stats stay inspectable and a
|
||||
* subsequent re-enable reuses it; only a table deletion removes it.
|
||||
*/
|
||||
public void onDestinationDisabled(String accountId, String region, String tableName, String streamArn) {
|
||||
DestinationState st = states.get(accountId + "|" + region + "|" + tableName + "|" + streamArn);
|
||||
if (st != null) {
|
||||
invalidate(st);
|
||||
}
|
||||
}
|
||||
|
||||
/** Table deletion: discard all of its destinations' buffers, stop their drains, and drop their state. */
|
||||
public void onTableDeleted(String accountId, String region, String tableName) {
|
||||
String prefix = accountId + "|" + region + "|" + tableName + "|";
|
||||
states.entrySet().removeIf(entry -> {
|
||||
if (entry.getKey().startsWith(prefix)) {
|
||||
invalidate(entry.getValue());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
private void invalidate(DestinationState st) {
|
||||
synchronized (st) {
|
||||
st.epoch++; // a scheduled drain from the old epoch will abort on its next check
|
||||
st.discardedOnDisable += st.queue.size();
|
||||
st.queue.clear();
|
||||
st.drainScheduled = false;
|
||||
st.consecutiveFailedProbes = 0; // a re-enable starts a fresh delivery episode
|
||||
st.health = Health.HEALTHY;
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
}
|
||||
|
||||
/** Blocks until every destination's queue is empty and no drain is scheduled, or the timeout elapses. */
|
||||
public boolean awaitIdle(Duration timeout) {
|
||||
long deadlineNanos = System.nanoTime() + timeout.toNanos();
|
||||
while (System.nanoTime() < deadlineNanos) {
|
||||
boolean idle = true;
|
||||
for (DestinationState st : states.values()) {
|
||||
synchronized (st) {
|
||||
if (!st.queue.isEmpty() || st.drainScheduled) {
|
||||
idle = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (idle) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(5);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Observability ────────────────────────────
|
||||
|
||||
/** Total CDC records permanently dropped across all destinations (terminal, give-up, or overflow). */
|
||||
public long getForwardFailureCount() {
|
||||
long sum = 0;
|
||||
for (DestinationState st : states.values()) {
|
||||
synchronized (st) {
|
||||
sum += st.dropped;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/** Immutable per-destination delivery-health snapshots (each copied under its destination lock). */
|
||||
List<DestinationForwardingStats> forwardingStats() {
|
||||
List<DestinationForwardingStats> out = new ArrayList<>();
|
||||
for (DestinationState st : states.values()) {
|
||||
synchronized (st) {
|
||||
out.add(new DestinationForwardingStats(st.health.name(), st.forwarded,
|
||||
st.retried, st.dropped, st.overflowed, st.discardedOnDisable,
|
||||
st.queue.size(), st.lastErrorType));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Payload construction (unchanged) ────────────────────────────
|
||||
|
||||
private ObjectNode buildPayload(String eventName, JsonNode keys,
|
||||
JsonNode newImage, JsonNode oldImage,
|
||||
String tableName, String region, Instant timestamp) {
|
||||
JsonNode newImage, JsonNode oldImage,
|
||||
String tableName, String region, Instant timestamp) {
|
||||
ObjectNode payload = objectMapper.createObjectNode();
|
||||
payload.put("awsRegion", region);
|
||||
payload.put("eventID", UUID.randomUUID().toString());
|
||||
@@ -103,7 +447,9 @@ public class KinesisStreamingForwarder {
|
||||
|
||||
private ObjectNode buildKeys(JsonNode item, TableDefinition table) {
|
||||
ObjectNode keys = objectMapper.createObjectNode();
|
||||
if (item == null) return keys;
|
||||
if (item == null) {
|
||||
return keys;
|
||||
}
|
||||
for (KeySchemaElement ks : table.getKeySchema()) {
|
||||
String attrName = ks.getAttributeName();
|
||||
if (item.has(attrName)) {
|
||||
@@ -114,19 +460,31 @@ public class KinesisStreamingForwarder {
|
||||
}
|
||||
|
||||
private String extractPartitionKey(JsonNode keys, TableDefinition table) {
|
||||
if (keys == null || keys.isEmpty()) return "default";
|
||||
if (keys == null || keys.isEmpty()) {
|
||||
return "default";
|
||||
}
|
||||
String pkName = table.getPartitionKeyName();
|
||||
JsonNode pkValue = keys.get(pkName);
|
||||
if (pkValue == null) return "default";
|
||||
if (pkValue.has("S")) return pkValue.get("S").asText();
|
||||
if (pkValue.has("N")) return pkValue.get("N").asText();
|
||||
if (pkValue.has("B")) return pkValue.get("B").asText();
|
||||
if (pkValue == null) {
|
||||
return "default";
|
||||
}
|
||||
if (pkValue.has("S")) {
|
||||
return pkValue.get("S").asText();
|
||||
}
|
||||
if (pkValue.has("N")) {
|
||||
return pkValue.get("N").asText();
|
||||
}
|
||||
if (pkValue.has("B")) {
|
||||
return pkValue.get("B").asText();
|
||||
}
|
||||
return pkValue.toString();
|
||||
}
|
||||
|
||||
private String extractStreamName(String streamArn) {
|
||||
int idx = streamArn.lastIndexOf('/');
|
||||
if (idx >= 0) return streamArn.substring(idx + 1);
|
||||
if (idx >= 0) {
|
||||
return streamArn.substring(idx + 1);
|
||||
}
|
||||
return streamArn;
|
||||
}
|
||||
}
|
||||
@@ -557,31 +557,65 @@ public class KinesisService implements ResourceProvider {
|
||||
|
||||
public PutRecordResult putRecordWithShardId(String streamName, byte[] data, String partitionKey,
|
||||
String explicitHashKey, String region) {
|
||||
return putRecordInternal(null, streamName, data, partitionKey, explicitHashKey, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a record on behalf of a specific account. Used by producers that run outside request scope
|
||||
* (the DynamoDB TTL sweep and DynamoDB→Kinesis CDC forwarding) so the record lands in the table
|
||||
* owner's stream rather than the ambient/default account's same-named stream. A {@code null}
|
||||
* accountId behaves exactly like {@link #putRecord}.
|
||||
*/
|
||||
public String putRecordForAccount(String accountId, String streamName, byte[] data, String partitionKey,
|
||||
String region) {
|
||||
return putRecordInternal(accountId, streamName, data, partitionKey, null, region).sequenceNumber();
|
||||
}
|
||||
|
||||
private PutRecordResult putRecordInternal(String accountId, String streamName, byte[] data,
|
||||
String partitionKey, String explicitHashKey, String region) {
|
||||
String key = regionKey(region, streamName);
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateExplicitHashKey(explicitHashKey);
|
||||
validateRecordSize(stream, data, partitionKey);
|
||||
putRecordBeforeLockHook.run();
|
||||
|
||||
// Serialize shard selection, sequence allocation, append and persistence per stream so
|
||||
// concurrent producers can neither lose an append (plain ArrayList) nor store records
|
||||
// out of sequence order (which would break AT_/AFTER_SEQUENCE_NUMBER scans and WAL replay).
|
||||
// The lock is keyed on region+streamName (NOT the account): an account-qualified key would stop
|
||||
// explicit-account appends from serializing against request-path producers on the same stream,
|
||||
// reintroducing the append race. Cross-account same-named streams therefore share one monitor
|
||||
// (over-coarse but safe).
|
||||
synchronized (lockFor(key)) {
|
||||
// Re-resolve under the lock. deleteStream holds this same monitor, so a stream deleted
|
||||
// between the resolve above and here is now absent from the store. Appending to and
|
||||
// persisting the stale pre-delete instance would resurrect a deleted stream, so bind to
|
||||
// the instance currently in the store and fail like any missing stream if it is gone.
|
||||
KinesisStream current = resolveStream(streamName, region);
|
||||
// Resolve under the lock, not before it. Resolving a legacy unprefixed stream MIGRATES it,
|
||||
// which is a write: the explicit-account path moves it into the account partition behind an
|
||||
// ownership predicate, while AccountAwareStorageBackend.get adopts it into the request
|
||||
// account with no ownership check and no synchronization. Resolved outside this monitor,
|
||||
// an ambient producer and the owner's producer could migrate the same stream concurrently
|
||||
// and fork it across partitions. deleteStream holds this same monitor too, so a stream
|
||||
// deleted before we get here is absent and this fails like any other missing stream rather
|
||||
// than appending to a stale instance and resurrecting it.
|
||||
KinesisStream current = resolveStreamForAccountMigrating(accountId, streamName, region);
|
||||
// Ordered exactly as before this moved under the monitor: a missing stream still reports
|
||||
// ResourceNotFoundException ahead of an invalid ExplicitHashKey, and the size check runs
|
||||
// against the same lock-protected instance that shard selection and the append use.
|
||||
validateExplicitHashKey(explicitHashKey);
|
||||
validateRecordSize(current, data, partitionKey);
|
||||
KinesisShard shard = selectShard(current, partitionKey, explicitHashKey);
|
||||
String sequenceNumber = String.valueOf(sequenceGenerator.incrementAndGet());
|
||||
putRecordAppendHook.run();
|
||||
KinesisRecord record = new KinesisRecord(data, partitionKey, sequenceNumber, Instant.now());
|
||||
shard.addRecord(record);
|
||||
store.put(key, current);
|
||||
persistStream(accountId, key, current);
|
||||
return new PutRecordResult(sequenceNumber, shard.getShardId());
|
||||
}
|
||||
}
|
||||
|
||||
private void persistStream(String accountId, String key, KinesisStream stream) {
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<KinesisStream> aware) {
|
||||
aware.putForAccount(accountId, key, stream);
|
||||
} else {
|
||||
store.put(key, stream);
|
||||
}
|
||||
}
|
||||
|
||||
public String getShardIterator(String streamName, String shardId, String type, String sequenceNumber, String region) {
|
||||
return getShardIterator(streamName, shardId, type, sequenceNumber, null, region);
|
||||
}
|
||||
@@ -806,6 +840,24 @@ public class KinesisService implements ResourceProvider {
|
||||
return resolveStream(streamName, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve for an out-of-request-scope PRODUCER (CDC forwarding, TTL sweep), migrating a legacy
|
||||
* unprefixed stream into the account partition on write, mirroring the ambient {@code store.get()}
|
||||
* fallback the producer used before account-scoping, so an installation with an existing CDC
|
||||
* destination and an unmigrated stream keeps forwarding after upgrade. Ownership is validated by the
|
||||
* stream's own accountId/ARN so one tenant cannot adopt another's unprefixed stream.
|
||||
*/
|
||||
private KinesisStream resolveStreamForAccountMigrating(String accountId, String streamName, String region) {
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<KinesisStream> aware) {
|
||||
return aware.getForAccountMigratingLegacy(accountId, regionKey(region, streamName),
|
||||
s -> accountId.equals(s.getAccountId())
|
||||
|| (s.getStreamArn() != null && s.getStreamArn().contains(":" + accountId + ":")))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Stream " + streamName + " not found", 400));
|
||||
}
|
||||
return resolveStream(streamName, region);
|
||||
}
|
||||
|
||||
public String getShardIteratorForAccount(String accountId, String streamName, String shardId,
|
||||
String type, String sequenceNumber, String region) {
|
||||
KinesisStream stream = resolveStreamForAccount(accountId, streamName, region);
|
||||
|
||||
Reference in new issue
Block a user