mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(kinesis): stop dropping shard records under concurrent producers and resharding (#3000)
* fix(kinesis): serialize shard record appends under concurrent producers
Concurrent PutItem->Kinesis CDC forwarding raced on a plain ArrayList in
KinesisShard, silently dropping ~1-3% of change records under load (rows
persisted in DynamoDB, no stream event emitted, no error).
- KinesisShard: encapsulate records behind a monitor; getRecords() returns a
snapshot; add addRecord()/recordCount(); null-safe setRecords().
- KinesisService: per-stream lock across sequence allocation + shard select +
append + store.put (fixes lost updates, sequence-vs-append ordering, and
stale-snapshot WAL replay); split/merge and deleteStream run under the same
lock with an in-lock re-resolve, closing the delete-vs-append resurrection
race; iteratorStartIndex uses recordCount().
- fix(dynamodb): KinesisStreamingForwarder no longer swallows forwarding
failures as a WARN-and-drop; logs ERROR with stack trace and increments a
forwardFailures counter (no rethrow: forwarding runs post-commit, and the
TTL sweep forwards mid-loop before persisting).
- Tests: concurrent CDC end-to-end, service-layer stress with sequence-order
and AFTER_SEQUENCE_NUMBER continuation, deterministic mutual-exclusion, WAL
persistence/reload, TTL happy + failure-isolation, delete-vs-append.
* fix(kinesis): make shard-list reads safe under concurrent resharding
Follow-up to the CDC record-loss fix, closing the reader-vs-reshard race and a
related shard-id defect.
- KinesisStream.shards -> volatile CopyOnWriteArrayList (+ null-safe setter):
lock-free shard readers (getRecords/peekRecords/getRecordsForAccount/
iterators/inspection) get CME-free snapshots while split/merge (under the
per-stream lock) append. The list is only ever add()-ed, so COWAL is a
drop-in; shard counts are tiny so copy-on-write cost is negligible.
- KinesisJsonHandler.paginateShards: snapshot (List.copyOf) before subList --
a COWAL subList is not snapshot-safe and could still throw CME on ListShards
during a concurrent reshard.
- splitShard: publish both children with a single atomic addAll, and derive
distinct child ids from the base size (previously both children got the same
id on a single-shard split, and a reader could observe a half-built
{parent, child1} topology with a hash-range gap).
Known residual (documented): parent-shard close is not fully atomic w.r.t. the
children add for lock-free readers; producers are unaffected.
Tests: reader-mid-iteration survives split; ListShards page survives concurrent
split; no half-published topology observable (RepeatedTest); child-id
uniqueness + hash-range tiling.
* fix(kinesis): serialize stream metadata writes with deleteStream
Every metadata action did a read-modify-write on the stored stream without the
per-stream monitor: resolve, mutate, store.put. The store hands back the live
instance, so a write that overlapped deleteStream could persist the stale
pre-delete instance after the locked delete had already removed it, resurrecting
the stream, or clobber a stream since recreated under the same name. On the WAL
backend that trailing put also appends a PUT entry after the DELETE, so the
resurrection survives replay.
Ten paths were exposed: updateStreamMode, addTagsToStream, removeTagsFromStream,
startStreamEncryption, stopStreamEncryption, increaseStreamRetentionPeriod,
decreaseStreamRetentionPeriod, enableEnhancedMonitoring,
disableEnhancedMonitoring and updateMaxRecordSize. Each now takes the same
monitor the append and split/merge paths take, and resolves the stream inside it,
so a stream deleted in the meantime surfaces ResourceNotFoundException instead of
being re-persisted. Validation order and the same-value no-op short-circuits are
unchanged, so no client-visible behaviour moves.
The monitor lookup moves behind lockFor, which carries the two-part contract
(hold the monitor, and resolve inside it) and the reason monitors are never
removed from the map. createStream is deliberately left alone: it builds a fresh
instance rather than retaining a resolved one, so it has no stale state to
re-persist and cannot resurrect a deleted stream.
Tests: all ten actions driven through the same interleaving, each wedged inside
its in-lock resolve while a concurrent deleteStream must block on the shared
monitor. That proves the delete lands after the persist and the stream stays
gone. Reverting either half of the fix on a single action fails only that case.
* style: remove em dashes from lines this branch adds
AGENTS.md, Documentation Style: "No em-dashes anywhere, in any content. Use
colons, commas, or periods." Twelve lines added by this branch used one, three
of them in files the branch creates, which also trips the doc-style workflow
since that job scans newly added files.
Scoped strictly to lines this branch adds. Pre-existing em dashes on untouched
lines are left alone, including three in KinesisService and KinesisJsonHandler
that main already carries. A few clauses are reworded rather than resegmented
where a bare colon or comma read badly.
This commit is contained in:
1 parent
1f87f7c482
commit
73deb13c01
12 files changed
+1468
-173
No files matched your search
+14
-2
@@ -14,6 +14,7 @@ import org.jboss.logging.Logger;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@ApplicationScoped
|
||||
public class KinesisStreamingForwarder {
|
||||
@@ -22,6 +23,7 @@ public class KinesisStreamingForwarder {
|
||||
|
||||
private final KinesisService kinesisService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicLong forwardFailures = new AtomicLong();
|
||||
|
||||
@Inject
|
||||
public KinesisStreamingForwarder(KinesisService kinesisService, ObjectMapper objectMapper) {
|
||||
@@ -53,12 +55,22 @@ public class KinesisStreamingForwarder {
|
||||
LOG.debugv("Forwarded DynamoDB event to Kinesis stream {0}: {1} on {2}",
|
||||
streamName, eventName, table.getTableName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to forward DynamoDB event to Kinesis destination {0}: {1}",
|
||||
dest.getStreamArn(), e.getMessage());
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Process-local count of CDC events dropped because forwarding to Kinesis threw. */
|
||||
public long getForwardFailureCount() {
|
||||
return forwardFailures.get();
|
||||
}
|
||||
|
||||
private ObjectNode buildPayload(String eventName, JsonNode keys,
|
||||
JsonNode newImage, JsonNode oldImage,
|
||||
String tableName, String region, Instant timestamp) {
|
||||
|
||||
+2
-2
@@ -104,7 +104,7 @@ public class KinesisInspectionController {
|
||||
node.put("StreamCreationTimestamp", stream.getStreamCreationTimestamp().toString());
|
||||
}
|
||||
node.put("OpenShardCount", stream.getShards().stream().filter(s -> !s.isClosed()).count());
|
||||
node.put("RecordCount", stream.getShards().stream().mapToInt(s -> s.getRecords().size()).sum());
|
||||
node.put("RecordCount", stream.getShards().stream().mapToInt(KinesisShard::recordCount).sum());
|
||||
ArrayNode enhancedMonitoring = node.putArray("EnhancedMonitoring");
|
||||
Set<String> metrics = stream.getEnhancedMonitoringMetrics();
|
||||
if (metrics != null) {
|
||||
@@ -130,7 +130,7 @@ public class KinesisInspectionController {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("ShardId", shard.getShardId());
|
||||
node.put("Closed", shard.isClosed());
|
||||
node.put("RecordCount", shard.getRecords().size());
|
||||
node.put("RecordCount", shard.recordCount());
|
||||
if (shard.getParentShardId() != null) {
|
||||
node.put("ParentShardId", shard.getParentShardId());
|
||||
}
|
||||
|
||||
@@ -638,7 +638,7 @@ public class KinesisJsonHandler {
|
||||
}
|
||||
|
||||
int maxResults = request.has("MaxResults") ? request.path("MaxResults").asInt(1000) : 1000;
|
||||
List<KinesisShard> page = shards.size() > maxResults ? shards.subList(0, maxResults) : shards;
|
||||
List<KinesisShard> page = paginateShards(shards, maxResults);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode shardsArray = response.putArray("Shards");
|
||||
@@ -666,6 +666,18 @@ public class KinesisJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Take a ListShards page, snapshotting first. The shard list is a live
|
||||
* {@link java.util.concurrent.CopyOnWriteArrayList}: its {@code subList} view is NOT an independent
|
||||
* snapshot. It stays bound to the backing array and throws {@link java.util.ConcurrentModificationException}
|
||||
* the moment a concurrent split/merge appends a shard. Copying to an immutable list first gives a page
|
||||
* that reads consistently regardless of concurrent resharding.
|
||||
*/
|
||||
static List<KinesisShard> paginateShards(List<KinesisShard> shards, int maxResults) {
|
||||
List<KinesisShard> snapshot = List.copyOf(shards);
|
||||
return snapshot.size() > maxResults ? snapshot.subList(0, maxResults) : snapshot;
|
||||
}
|
||||
|
||||
private Response handleEnableEnhancedMonitoring(JsonNode request, String region) {
|
||||
String streamName = resolveStreamName(request);
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import org.jboss.logging.Logger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
@@ -47,6 +48,18 @@ public class KinesisService implements ResourceProvider {
|
||||
private final StorageBackend<String, KinesisConsumer> consumerStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final AtomicLong sequenceGenerator = new AtomicLong(System.currentTimeMillis());
|
||||
// One monitor per stream key, handed out by lockFor. Serializes sequence allocation + shard
|
||||
// append + persist so the in-memory log, the assigned sequence order and the WAL write order
|
||||
// all agree, and serializes every other read-modify-write on a stream against deleteStream.
|
||||
private final ConcurrentHashMap<String, Object> streamAppendLocks = new ConcurrentHashMap<>();
|
||||
// Package-private test seam, run inside the append critical section after the sequence is
|
||||
// allocated and before the record is appended. Default no-op in production.
|
||||
Runnable putRecordAppendHook = () -> {};
|
||||
// Package-private test seam, run after the pre-lock resolve/validation and before the append
|
||||
// lock is acquired. Lets a test deterministically wedge a producer in the window where a
|
||||
// concurrent deleteStream can win the lock first, exercising the in-lock re-resolve guard.
|
||||
// Default no-op in production.
|
||||
Runnable putRecordBeforeLockHook = () -> {};
|
||||
|
||||
@Inject
|
||||
public KinesisService(StorageFactory factory, RegionResolver regionResolver) {
|
||||
@@ -118,20 +131,23 @@ public class KinesisService implements ResourceProvider {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"StreamMode must be PROVISIONED or ON_DEMAND, got: " + streamMode, 400);
|
||||
}
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
if (!"ACTIVE".equals(stream.getStreamStatus())) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Stream " + streamName + " is not ACTIVE (current state: " + stream.getStreamStatus() + ")", 400);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
if (!"ACTIVE".equals(stream.getStreamStatus())) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Stream " + streamName + " is not ACTIVE (current state: " + stream.getStreamStatus() + ")", 400);
|
||||
}
|
||||
// Same-mode is a no-op. Mirrors the same-value behaviour in
|
||||
// increase/decreaseStreamRetentionPeriod (see #342). Avoids breaking
|
||||
// terraform-provider-aws which calls UpdateStreamMode on every refresh.
|
||||
if (streamMode.equals(stream.getStreamMode())) {
|
||||
return;
|
||||
}
|
||||
stream.setStreamMode(streamMode);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Updated stream mode for {0} to {1}", streamName, streamMode);
|
||||
}
|
||||
// Same-mode is a no-op. Mirrors the same-value behaviour in
|
||||
// increase/decreaseStreamRetentionPeriod (see #342). Avoids breaking
|
||||
// terraform-provider-aws which calls UpdateStreamMode on every refresh.
|
||||
if (streamMode.equals(stream.getStreamMode())) {
|
||||
return;
|
||||
}
|
||||
stream.setStreamMode(streamMode);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Updated stream mode for {0} to {1}", streamName, streamMode);
|
||||
}
|
||||
|
||||
public List<String> listStreams(String region) {
|
||||
@@ -193,20 +209,31 @@ public class KinesisService implements ResourceProvider {
|
||||
|
||||
public void deleteStream(String streamName, String region) {
|
||||
String storageKey = regionKey(region, streamName);
|
||||
store.delete(storageKey);
|
||||
// Delete under the per-stream monitor every writer takes, so the delete is serialized with
|
||||
// any in-flight append, split, merge or metadata write on this stream. See lockFor for why
|
||||
// the monitor is deliberately left in the map.
|
||||
synchronized (lockFor(storageKey)) {
|
||||
store.delete(storageKey);
|
||||
}
|
||||
LOG.infov("Deleted Kinesis stream: {0}", streamName);
|
||||
}
|
||||
|
||||
public void addTagsToStream(String streamName, Map<String, String> tags, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
stream.getTags().putAll(tags);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
stream.getTags().putAll(tags);
|
||||
store.put(key, stream);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeTagsFromStream(String streamName, List<String> tagKeys, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
tagKeys.forEach(stream.getTags()::remove);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
tagKeys.forEach(stream.getTags()::remove);
|
||||
store.put(key, stream);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForStream(String streamName, String region) {
|
||||
@@ -214,75 +241,90 @@ public class KinesisService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void startStreamEncryption(String streamName, String encryptionType, String keyId, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
stream.setEncryptionType(encryptionType);
|
||||
stream.setKeyId(keyId);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
stream.setEncryptionType(encryptionType);
|
||||
stream.setKeyId(keyId);
|
||||
store.put(key, stream);
|
||||
}
|
||||
}
|
||||
|
||||
public void increaseStreamRetentionPeriod(String streamName, int retentionPeriodHours, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
if (retentionPeriodHours > 8760) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Retention period must not exceed 8760 hours (365 days)", 400);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
if (retentionPeriodHours > 8760) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Retention period must not exceed 8760 hours (365 days)", 400);
|
||||
}
|
||||
if (retentionPeriodHours < stream.getRetentionPeriodHours()) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Requested retention period (" + retentionPeriodHours +
|
||||
" hours) must not be less than current retention period (" +
|
||||
stream.getRetentionPeriodHours() + " hours)", 400);
|
||||
}
|
||||
// Same value is a no-op on real AWS despite the API doc wording ("must be more than
|
||||
// current"). Proof: terraform-provider-aws calls IncreaseStreamRetentionPeriod on
|
||||
// stream creation unconditionally when retention_period is set (stream.go Create path),
|
||||
// so every default-retention TF stream would fail if AWS rejected same-value. See #342.
|
||||
if (retentionPeriodHours == stream.getRetentionPeriodHours()) {
|
||||
return;
|
||||
}
|
||||
stream.setRetentionPeriodHours(retentionPeriodHours);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Increased retention period for stream {0} to {1} hours", streamName, retentionPeriodHours);
|
||||
}
|
||||
if (retentionPeriodHours < stream.getRetentionPeriodHours()) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Requested retention period (" + retentionPeriodHours +
|
||||
" hours) must not be less than current retention period (" +
|
||||
stream.getRetentionPeriodHours() + " hours)", 400);
|
||||
}
|
||||
// Same value is a no-op on real AWS despite the API doc wording ("must be more than
|
||||
// current"). Proof: terraform-provider-aws calls IncreaseStreamRetentionPeriod on
|
||||
// stream creation unconditionally when retention_period is set (stream.go Create path),
|
||||
// so every default-retention TF stream would fail if AWS rejected same-value. See #342.
|
||||
if (retentionPeriodHours == stream.getRetentionPeriodHours()) {
|
||||
return;
|
||||
}
|
||||
stream.setRetentionPeriodHours(retentionPeriodHours);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Increased retention period for stream {0} to {1} hours", streamName, retentionPeriodHours);
|
||||
}
|
||||
|
||||
public void decreaseStreamRetentionPeriod(String streamName, int retentionPeriodHours, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
if (retentionPeriodHours < 24) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Retention period must not be less than 24 hours", 400);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
if (retentionPeriodHours < 24) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Retention period must not be less than 24 hours", 400);
|
||||
}
|
||||
if (retentionPeriodHours > stream.getRetentionPeriodHours()) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Requested retention period (" + retentionPeriodHours +
|
||||
" hours) must not be greater than current retention period (" +
|
||||
stream.getRetentionPeriodHours() + " hours)", 400);
|
||||
}
|
||||
// Same value is a no-op on real AWS (mirrors IncreaseStreamRetentionPeriod). See #342.
|
||||
if (retentionPeriodHours == stream.getRetentionPeriodHours()) {
|
||||
return;
|
||||
}
|
||||
stream.setRetentionPeriodHours(retentionPeriodHours);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Decreased retention period for stream {0} to {1} hours", streamName, retentionPeriodHours);
|
||||
}
|
||||
if (retentionPeriodHours > stream.getRetentionPeriodHours()) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Requested retention period (" + retentionPeriodHours +
|
||||
" hours) must not be greater than current retention period (" +
|
||||
stream.getRetentionPeriodHours() + " hours)", 400);
|
||||
}
|
||||
// Same value is a no-op on real AWS (mirrors IncreaseStreamRetentionPeriod). See #342.
|
||||
if (retentionPeriodHours == stream.getRetentionPeriodHours()) {
|
||||
return;
|
||||
}
|
||||
stream.setRetentionPeriodHours(retentionPeriodHours);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Decreased retention period for stream {0} to {1} hours", streamName, retentionPeriodHours);
|
||||
}
|
||||
|
||||
public Set<String> enableEnhancedMonitoring(String streamName, List<String> metrics, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
Set<String> current = new HashSet<>(stream.getEnhancedMonitoringMetrics());
|
||||
Set<String> desired = resolveMetrics(metrics);
|
||||
stream.getEnhancedMonitoringMetrics().addAll(desired);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Enabled enhanced monitoring for stream {0}: {1}", streamName, desired);
|
||||
return current;
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
Set<String> current = new HashSet<>(stream.getEnhancedMonitoringMetrics());
|
||||
Set<String> desired = resolveMetrics(metrics);
|
||||
stream.getEnhancedMonitoringMetrics().addAll(desired);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Enabled enhanced monitoring for stream {0}: {1}", streamName, desired);
|
||||
return current;
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> disableEnhancedMonitoring(String streamName, List<String> metrics, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
Set<String> current = new HashSet<>(stream.getEnhancedMonitoringMetrics());
|
||||
Set<String> toRemove = resolveMetrics(metrics);
|
||||
stream.getEnhancedMonitoringMetrics().removeAll(toRemove);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Disabled enhanced monitoring for stream {0}: {1}", streamName, toRemove);
|
||||
return current;
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
Set<String> current = new HashSet<>(stream.getEnhancedMonitoringMetrics());
|
||||
Set<String> toRemove = resolveMetrics(metrics);
|
||||
stream.getEnhancedMonitoringMetrics().removeAll(toRemove);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Disabled enhanced monitoring for stream {0}: {1}", streamName, toRemove);
|
||||
return current;
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> resolveMetrics(List<String> metrics) {
|
||||
@@ -306,80 +348,101 @@ public class KinesisService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void stopStreamEncryption(String streamName, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
stream.setEncryptionType("NONE");
|
||||
stream.setKeyId(null);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
stream.setEncryptionType("NONE");
|
||||
stream.setKeyId(null);
|
||||
store.put(key, stream);
|
||||
}
|
||||
}
|
||||
|
||||
public void splitShard(String streamName, String shardId, String newStartingHashKey, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
KinesisShard parent = stream.getShards().stream()
|
||||
.filter(s -> s.getShardId().equals(shardId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
|
||||
String key = regionKey(region, streamName);
|
||||
// Share the producer critical section so a split can't race an append: selectShard runs
|
||||
// under the same lock, so a producer never appends to a parent a completed split has closed.
|
||||
synchronized (lockFor(key)) {
|
||||
// Resolve under the lock so a concurrent deleteStream (same monitor) cannot leave us
|
||||
// mutating and re-persisting a stale, deleted instance.
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
KinesisShard parent = stream.getShards().stream()
|
||||
.filter(s -> s.getShardId().equals(shardId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
|
||||
|
||||
if (parent.isClosed()) {
|
||||
throw new AwsException("InvalidArgumentException", "Shard " + shardId + " is already closed", 400);
|
||||
if (parent.isClosed()) {
|
||||
throw new AwsException("InvalidArgumentException", "Shard " + shardId + " is already closed", 400);
|
||||
}
|
||||
|
||||
parent.setClosed(true);
|
||||
parent.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(
|
||||
parent.getSequenceNumberRange().startingSequenceNumber(),
|
||||
String.valueOf(sequenceGenerator.get())));
|
||||
|
||||
String start = parent.getHashKeyRange().startingHashKey();
|
||||
String end = parent.getHashKeyRange().endingHashKey();
|
||||
|
||||
// Derive both child ids from the base size WITHOUT relying on the first add: nextShardId
|
||||
// is size-based, so two sequential adds would either collide (both ids computed pre-add)
|
||||
// or expose a half-published topology (child1 visible before child2). Compute base+0 and
|
||||
// base+1 up front so the ids stay distinct, then publish BOTH children in one atomic
|
||||
// CopyOnWriteArrayList.addAll, so a lock-free reader can never observe {parent, child1}
|
||||
// without child2.
|
||||
int base = stream.getShards().size();
|
||||
KinesisShard child1 = new KinesisShard(String.format("shardId-%012d", base), start, subtractOne(newStartingHashKey), String.valueOf(sequenceGenerator.get()));
|
||||
child1.setParentShardId(shardId);
|
||||
|
||||
KinesisShard child2 = new KinesisShard(String.format("shardId-%012d", base + 1), newStartingHashKey, end, String.valueOf(sequenceGenerator.get()));
|
||||
child2.setParentShardId(shardId);
|
||||
|
||||
stream.getShards().addAll(List.of(child1, child2));
|
||||
store.put(key, stream);
|
||||
LOG.infov("Split shard {0} in stream {1}", shardId, streamName);
|
||||
}
|
||||
|
||||
parent.setClosed(true);
|
||||
parent.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(
|
||||
parent.getSequenceNumberRange().startingSequenceNumber(),
|
||||
String.valueOf(sequenceGenerator.get())));
|
||||
|
||||
String start = parent.getHashKeyRange().startingHashKey();
|
||||
String end = parent.getHashKeyRange().endingHashKey();
|
||||
|
||||
KinesisShard child1 = new KinesisShard(nextShardId(stream), start, subtractOne(newStartingHashKey), String.valueOf(sequenceGenerator.get()));
|
||||
child1.setParentShardId(shardId);
|
||||
|
||||
KinesisShard child2 = new KinesisShard(nextShardId(stream), newStartingHashKey, end, String.valueOf(sequenceGenerator.get()));
|
||||
child2.setParentShardId(shardId);
|
||||
|
||||
stream.getShards().add(child1);
|
||||
stream.getShards().add(child2);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Split shard {0} in stream {1}", shardId, streamName);
|
||||
}
|
||||
|
||||
public void mergeShards(String streamName, String shardId, String adjacentShardId, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
KinesisShard shard1 = stream.getShards().stream()
|
||||
.filter(s -> s.getShardId().equals(shardId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
|
||||
KinesisShard shard2 = stream.getShards().stream()
|
||||
.filter(s -> s.getShardId().equals(adjacentShardId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + adjacentShardId + " not found", 400));
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
// Resolve under the lock so a concurrent deleteStream (same monitor) cannot leave us
|
||||
// mutating and re-persisting a stale, deleted instance.
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
KinesisShard shard1 = stream.getShards().stream()
|
||||
.filter(s -> s.getShardId().equals(shardId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + shardId + " not found", 400));
|
||||
KinesisShard shard2 = stream.getShards().stream()
|
||||
.filter(s -> s.getShardId().equals(adjacentShardId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard " + adjacentShardId + " not found", 400));
|
||||
|
||||
if (shard1.isClosed() || shard2.isClosed()) {
|
||||
throw new AwsException("InvalidArgumentException", "One or both shards are already closed", 400);
|
||||
if (shard1.isClosed() || shard2.isClosed()) {
|
||||
throw new AwsException("InvalidArgumentException", "One or both shards are already closed", 400);
|
||||
}
|
||||
|
||||
shard1.setClosed(true);
|
||||
shard2.setClosed(true);
|
||||
String seq = String.valueOf(sequenceGenerator.get());
|
||||
shard1.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard1.getSequenceNumberRange().startingSequenceNumber(), seq));
|
||||
shard2.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard2.getSequenceNumberRange().startingSequenceNumber(), seq));
|
||||
|
||||
// Combine hash ranges (assuming they are adjacent)
|
||||
java.math.BigInteger s1Start = new java.math.BigInteger(shard1.getHashKeyRange().startingHashKey());
|
||||
java.math.BigInteger s2Start = new java.math.BigInteger(shard2.getHashKeyRange().startingHashKey());
|
||||
|
||||
String start = s1Start.min(s2Start).toString();
|
||||
java.math.BigInteger s1End = new java.math.BigInteger(shard1.getHashKeyRange().endingHashKey());
|
||||
java.math.BigInteger s2End = new java.math.BigInteger(shard2.getHashKeyRange().endingHashKey());
|
||||
String end = s1End.max(s2End).toString();
|
||||
|
||||
KinesisShard child = new KinesisShard(nextShardId(stream), start, end, seq);
|
||||
child.setParentShardId(shardId);
|
||||
child.setAdjacentParentShardId(adjacentShardId);
|
||||
|
||||
stream.getShards().add(child);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Merged shards {0} and {1} in stream {2}", shardId, adjacentShardId, streamName);
|
||||
}
|
||||
|
||||
shard1.setClosed(true);
|
||||
shard2.setClosed(true);
|
||||
String seq = String.valueOf(sequenceGenerator.get());
|
||||
shard1.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard1.getSequenceNumberRange().startingSequenceNumber(), seq));
|
||||
shard2.setSequenceNumberRange(new KinesisShard.SequenceNumberRange(shard2.getSequenceNumberRange().startingSequenceNumber(), seq));
|
||||
|
||||
// Combine hash ranges (assuming they are adjacent)
|
||||
java.math.BigInteger s1Start = new java.math.BigInteger(shard1.getHashKeyRange().startingHashKey());
|
||||
java.math.BigInteger s2Start = new java.math.BigInteger(shard2.getHashKeyRange().startingHashKey());
|
||||
|
||||
String start = s1Start.min(s2Start).toString();
|
||||
java.math.BigInteger s1End = new java.math.BigInteger(shard1.getHashKeyRange().endingHashKey());
|
||||
java.math.BigInteger s2End = new java.math.BigInteger(shard2.getHashKeyRange().endingHashKey());
|
||||
String end = s1End.max(s2End).toString();
|
||||
|
||||
KinesisShard child = new KinesisShard(nextShardId(stream), start, end, seq);
|
||||
child.setParentShardId(shardId);
|
||||
child.setAdjacentParentShardId(adjacentShardId);
|
||||
|
||||
stream.getShards().add(child);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Merged shards {0} and {1} in stream {2}", shardId, adjacentShardId, streamName);
|
||||
}
|
||||
|
||||
private String nextShardId(KinesisStream stream) {
|
||||
@@ -452,35 +515,49 @@ public class KinesisService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void updateMaxRecordSize(String streamName, int maxRecordSizeInKiB, String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateMaxRecordSize(maxRecordSizeInKiB, "ValidationException");
|
||||
if ("ON_DEMAND".equals(stream.getStreamMode())) {
|
||||
throw new AwsException("ValidationException",
|
||||
"UpdateMaxRecordSize is only supported for data streams with the provisioned capacity mode.",
|
||||
400);
|
||||
String key = regionKey(region, streamName);
|
||||
synchronized (lockFor(key)) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateMaxRecordSize(maxRecordSizeInKiB, "ValidationException");
|
||||
if ("ON_DEMAND".equals(stream.getStreamMode())) {
|
||||
throw new AwsException("ValidationException",
|
||||
"UpdateMaxRecordSize is only supported for data streams with the provisioned capacity mode.",
|
||||
400);
|
||||
}
|
||||
if (!"ACTIVE".equals(stream.getStreamStatus())) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Stream " + streamName + " is not ACTIVE (current state: "
|
||||
+ stream.getStreamStatus() + ")", 400);
|
||||
}
|
||||
stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB);
|
||||
store.put(key, stream);
|
||||
LOG.infov("Updated max record size for {0} to {1} KiB", streamName, maxRecordSizeInKiB);
|
||||
}
|
||||
if (!"ACTIVE".equals(stream.getStreamStatus())) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Stream " + streamName + " is not ACTIVE (current state: "
|
||||
+ stream.getStreamStatus() + ")", 400);
|
||||
}
|
||||
stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
LOG.infov("Updated max record size for {0} to {1} KiB", streamName, maxRecordSizeInKiB);
|
||||
}
|
||||
|
||||
public PutRecordResult putRecordWithShardId(String streamName, byte[] data, String partitionKey, String region) {
|
||||
String key = regionKey(region, streamName);
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
validateRecordSize(stream, data, partitionKey);
|
||||
KinesisShard shard = selectShard(stream, partitionKey);
|
||||
putRecordBeforeLockHook.run();
|
||||
|
||||
String sequenceNumber = String.valueOf(sequenceGenerator.incrementAndGet());
|
||||
KinesisRecord record = new KinesisRecord(data, partitionKey, sequenceNumber, Instant.now());
|
||||
|
||||
shard.getRecords().add(record);
|
||||
store.put(regionKey(region, streamName), stream);
|
||||
|
||||
return new PutRecordResult(sequenceNumber, shard.getShardId());
|
||||
// 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).
|
||||
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);
|
||||
KinesisShard shard = selectShard(current, partitionKey);
|
||||
String sequenceNumber = String.valueOf(sequenceGenerator.incrementAndGet());
|
||||
putRecordAppendHook.run();
|
||||
KinesisRecord record = new KinesisRecord(data, partitionKey, sequenceNumber, Instant.now());
|
||||
shard.addRecord(record);
|
||||
store.put(key, current);
|
||||
return new PutRecordResult(sequenceNumber, shard.getShardId());
|
||||
}
|
||||
}
|
||||
|
||||
public String getShardIterator(String streamName, String shardId, String type, String sequenceNumber, String region) {
|
||||
@@ -527,7 +604,7 @@ public class KinesisService implements ResourceProvider {
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard not found", 400));
|
||||
// LATEST resumes from the tip snapshot taken now; other types resolve in getRecords.
|
||||
return "LATEST".equals(type) ? shard.getRecords().size() : 0;
|
||||
return "LATEST".equals(type) ? shard.recordCount() : 0;
|
||||
}
|
||||
|
||||
private int parseIteratorIndex(String value) {
|
||||
@@ -786,6 +863,23 @@ public class KinesisService implements ResourceProvider {
|
||||
return region + "::" + name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The monitor guarding a stream key. Every path that mutates a stored stream takes it: record
|
||||
* appends, split and merge, the metadata writes, and {@link #deleteStream}.
|
||||
*
|
||||
* <p>Holding it is only half the contract: a writer must also resolve the stream inside the
|
||||
* monitor. A stream resolved before the monitor was acquired may already have been deleted, and
|
||||
* persisting that stale instance would resurrect it or clobber a stream since recreated under
|
||||
* the same name.
|
||||
*
|
||||
* <p>Monitors are never removed. One stable monitor per key is a bounded leak, whereas dropping
|
||||
* one on delete would let a writer that already resolved the stream create a fresh monitor and
|
||||
* persist the deleted instance under it, defeating the serialization.
|
||||
*/
|
||||
private Object lockFor(String storageKey) {
|
||||
return streamAppendLocks.computeIfAbsent(storageKey, k -> new Object());
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
|
||||
@@ -15,6 +15,7 @@ public class KinesisShard {
|
||||
private String adjacentParentShardId;
|
||||
private HashKeyRange hashKeyRange;
|
||||
private SequenceNumberRange sequenceNumberRange;
|
||||
private final Object recordsMonitor = new Object();
|
||||
private List<KinesisRecord> records = new ArrayList<>();
|
||||
private boolean closed = false;
|
||||
private Instant creationTimestamp = Instant.now();
|
||||
@@ -42,8 +43,38 @@ public class KinesisShard {
|
||||
public SequenceNumberRange getSequenceNumberRange() { return sequenceNumberRange; }
|
||||
public void setSequenceNumberRange(SequenceNumberRange range) { this.sequenceNumberRange = range; }
|
||||
|
||||
public List<KinesisRecord> getRecords() { return records; }
|
||||
public void setRecords(List<KinesisRecord> records) { this.records = records; }
|
||||
/**
|
||||
* A shallow snapshot of this shard's records. Safe to index and iterate without a
|
||||
* ConcurrentModificationException even while producers append concurrently. Structural
|
||||
* mutation of the returned list does NOT affect the shard (append via {@link #addRecord});
|
||||
* element references are shared, so per-element setters still write through.
|
||||
*/
|
||||
public List<KinesisRecord> getRecords() {
|
||||
synchronized (recordsMonitor) {
|
||||
return new ArrayList<>(records);
|
||||
}
|
||||
}
|
||||
|
||||
/** Appends a record. The sole production mutation path for a shard's log. */
|
||||
public void addRecord(KinesisRecord record) {
|
||||
synchronized (recordsMonitor) {
|
||||
records.add(record);
|
||||
}
|
||||
}
|
||||
|
||||
/** Number of records currently held, without copying the log. */
|
||||
public int recordCount() {
|
||||
synchronized (recordsMonitor) {
|
||||
return records.size();
|
||||
}
|
||||
}
|
||||
|
||||
/** Jackson rehydration only; not safe for concurrent replacement during live traffic. */
|
||||
public void setRecords(List<KinesisRecord> records) {
|
||||
synchronized (recordsMonitor) {
|
||||
this.records = records == null ? new ArrayList<>() : new ArrayList<>(records);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isClosed() { return closed; }
|
||||
public void setClosed(boolean closed) { this.closed = closed; }
|
||||
|
||||
@@ -4,12 +4,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -18,7 +18,7 @@ public class KinesisStream {
|
||||
private String streamArn;
|
||||
private String accountId;
|
||||
private String streamStatus;
|
||||
private List<KinesisShard> shards = new ArrayList<>();
|
||||
private volatile List<KinesisShard> shards = new CopyOnWriteArrayList<>();
|
||||
private int retentionPeriodHours = 24;
|
||||
private Instant streamCreationTimestamp;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
@@ -51,7 +51,9 @@ public class KinesisStream {
|
||||
public void setStreamStatus(String streamStatus) { this.streamStatus = streamStatus; }
|
||||
|
||||
public List<KinesisShard> getShards() { return shards; }
|
||||
public void setShards(List<KinesisShard> shards) { this.shards = shards; }
|
||||
public void setShards(List<KinesisShard> shards) {
|
||||
this.shards = shards == null ? new CopyOnWriteArrayList<>() : new CopyOnWriteArrayList<>(shards);
|
||||
}
|
||||
|
||||
public int getRetentionPeriodHours() { return retentionPeriodHours; }
|
||||
public void setRetentionPeriodHours(int retentionPeriodHours) { this.retentionPeriodHours = retentionPeriodHours; }
|
||||
|
||||
Reference in new issue
Block a user