Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(kinesis): support AT_TIMESTAMP shard iterator type (#520)

TiM0642a28e7812
diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java
index d67e2ac50e..374b242efc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java
@@ -386,8 +386,24 @@ public class KinesisJsonHandler {
String shardId = request.path("ShardId").asText();
String type = request.path("ShardIteratorType").asText();
String seq = request.has("StartingSequenceNumber") ? request.path("StartingSequenceNumber").asText() : null;
+ // AWS sends Timestamp as epoch seconds (double with fractional ms).
+ // Convert to long millis at the boundary; the emulator stores time in ms everywhere.
+ // Use Math.round to avoid 1ms drift from FP multiplication (e.g. X.999...).
+ Long timestampMillis = null;
+ if (request.has("Timestamp") && !request.path("Timestamp").isNull()) {
+ JsonNode tsNode = request.path("Timestamp");
+ if (!tsNode.isNumber()) {
+ throw new io.github.hectorvent.floci.core.common.AwsException("InvalidArgumentException",
+ "Timestamp must be a number (epoch seconds)", 400);
+ }
+ timestampMillis = Math.round(tsNode.asDouble() * 1000);
+ }
+ if ("AT_TIMESTAMP".equals(type) && timestampMillis == null) {
+ throw new io.github.hectorvent.floci.core.common.AwsException("InvalidArgumentException",
+ "ShardIteratorType AT_TIMESTAMP requires a Timestamp", 400);
+ }
- String iterator = service.getShardIterator(streamName, shardId, type, seq, region);
+ String iterator = service.getShardIterator(streamName, shardId, type, seq, timestampMillis, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("ShardIterator", iterator);
diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java
index 9f3c1846ef..309f083f07 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java
@@ -371,16 +371,27 @@ public class KinesisService {
}
public String getShardIterator(String streamName, String shardId, String type, String sequenceNumber, String region) {
+ return getShardIterator(streamName, shardId, type, sequenceNumber, null, region);
+ }
+
+ public String getShardIterator(String streamName, String shardId, String type, String sequenceNumber,
+ Long timestampMillis, String region) {
resolveStream(streamName, region); // validate exists
- // Format: streamName|shardId|type|sequenceNumber|index
- String raw = String.format("%s|%s|%s|%s|%d",
- streamName, shardId, type, sequenceNumber != null ? sequenceNumber : "", 0);
+ // Format: streamName|shardId|type|sequenceNumber|index|timestampMillis
+ // The 6th slot was added for AT_TIMESTAMP; empty for other iterator types.
+ // Old 5-part iterators still decode via split(-1) compatibility in getRecords.
+ String raw = String.format("%s|%s|%s|%s|%d|%s",
+ streamName, shardId, type,
+ sequenceNumber != null ? sequenceNumber : "",
+ 0,
+ timestampMillis != null ? timestampMillis.toString() : "");
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
public Map<String, Object> getRecords(String shardIterator, Integer limit, String region) {
byte[] decoded = Base64.getDecoder().decode(shardIterator);
- String[] parts = new String(decoded, StandardCharsets.UTF_8).split(java.util.regex.Pattern.quote("|"), 5);
+ // Use limit=-1 so trailing empty slots round-trip and old 5-part iterators still work.
+ String[] parts = new String(decoded, StandardCharsets.UTF_8).split(java.util.regex.Pattern.quote("|"), -1);
if (parts.length < 5) throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400);
String streamName = parts[0];
@@ -388,6 +399,14 @@ public class KinesisService {
String type = parts[2];
String startSeq = parts[3];
int lastIndex = Integer.parseInt(parts[4]);
+ Long timestampMillis = null;
+ if (parts.length >= 6 && !parts[5].isEmpty()) {
+ try {
+ timestampMillis = Long.parseLong(parts[5]);
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidArgumentException", "Invalid timestamp in shard iterator", 400);
+ }
+ }
KinesisStream stream = resolveStream(streamName, region);
KinesisShard shard = stream.getShards().stream()
@@ -417,6 +436,21 @@ public class KinesisService {
break;
}
}
+ } else if ("AT_TIMESTAMP".equals(type)) {
+ if (timestampMillis == null) {
+ throw new AwsException("InvalidArgumentException",
+ "AT_TIMESTAMP iterator requires a Timestamp", 400);
+ }
+ // First record with ApproximateArrivalTimestamp >= requested timestamp.
+ // If none match (all records predate timestamp or shard is empty), start past end (no records returned, caught up).
+ startIndex = allRecords.size();
+ for (int i = 0; i < allRecords.size(); i++) {
+ Instant arr = allRecords.get(i).getApproximateArrivalTimestamp();
+ if (arr != null && arr.toEpochMilli() >= timestampMillis) {
+ startIndex = i;
+ break;
+ }
+ }
}
int max = limit != null ? Math.min(limit, 1000) : 1000;
@@ -427,8 +461,11 @@ public class KinesisService {
nextIndex = i + 1;
}
+ // Continuation iterator: type=TRIM_HORIZON + resume-at-nextIndex is the existing
+ // "resume by index" convention (the type label is misleading but preserved for compat).
+ // Timestamp slot empty on continuation.
String nextIterator = Base64.getEncoder().encodeToString(
- String.format("%s|%s|%s|%s|%d", streamName, shardId, "TRIM_HORIZON", "", nextIndex)
+ String.format("%s|%s|%s|%s|%d|", streamName, shardId, "TRIM_HORIZON", "", nextIndex)
.getBytes(StandardCharsets.UTF_8));
Map<String, Object> response = new HashMap<>();
diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisIntegrationTest.java
index 0384ae9c85..440d35d951 100644
--- a/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisIntegrationTest.java
@@ -722,4 +722,191 @@ class KinesisIntegrationTest {
.then().statusCode(200)
.body("Records.size()", equalTo(0));
}
+
+ // --- AT_TIMESTAMP iterator coverage ---
+
+ private String atTimestampCreateStream(String name) {
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.CreateStream")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"StreamName\": \"" + name + "\", \"ShardCount\": 1}")
+ .when().post("/").then().statusCode(200);
+ return "shardId-000000000000";
+ }
+
+ private String atTimestampPutAndGetSequence(String stream, String data) {
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.PutRecord")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"StreamName\": \"" + stream + "\", \"Data\": \"" + data + "\", \"PartitionKey\": \"pk\"}")
+ .when().post("/").then().statusCode(200);
+ return "ok";
+ }
+
+ private String atTimestampIterator(String stream, String shardId, double timestampSec) {
+ return given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"StreamName\": \"" + stream + "\", \"ShardId\": \"" + shardId
+ + "\", \"ShardIteratorType\": \"AT_TIMESTAMP\", \"Timestamp\": " + timestampSec + "}")
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().jsonPath().getString("ShardIterator");
+ }
+
+ @Test
+ @Order(50)
+ void atTimestampReturnsRecordsAtAndAfter() throws InterruptedException {
+ String stream = "at-timestamp-basic";
+ String shardId = atTimestampCreateStream(stream);
+
+ long[] tsMillis = new long[5];
+ for (int i = 0; i < 5; i++) {
+ tsMillis[i] = System.currentTimeMillis();
+ atTimestampPutAndGetSequence(stream, "cmVjMA=="); // "rec0" base64
+ Thread.sleep(100);
+ }
+
+ // tsMillis[i] is captured just before rec[i], so rec[i].arrival >= tsMillis[i]
+ // and rec[i-1].arrival < tsMillis[i]. AT_TIMESTAMP at tsMillis[2] returns rec 2,3,4.
+ double targetSec = tsMillis[2] / 1000.0;
+ String iterator = atTimestampIterator(stream, shardId, targetSec);
+
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetRecords")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"ShardIterator\": \"" + iterator + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Records.size()", equalTo(3));
+ }
+
+ @Test
+ @Order(51)
+ void atTimestampBeforeFirstRecordReturnsAll() {
+ String stream = "at-timestamp-before";
+ String shardId = atTimestampCreateStream(stream);
+ for (int i = 0; i < 3; i++) {
+ atTimestampPutAndGetSequence(stream, "YWJj");
+ }
+
+ // Timestamp at epoch 1s (way before any record).
+ String iterator = atTimestampIterator(stream, shardId, 1.0);
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetRecords")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"ShardIterator\": \"" + iterator + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Records.size()", equalTo(3));
+ }
+
+ @Test
+ @Order(52)
+ void atTimestampFutureReturnsZeroAndValidContinuation() {
+ String stream = "at-timestamp-future";
+ String shardId = atTimestampCreateStream(stream);
+ for (int i = 0; i < 3; i++) {
+ atTimestampPutAndGetSequence(stream, "eHl6");
+ }
+
+ double futureSec = (System.currentTimeMillis() + 3_600_000) / 1000.0;
+ String iterator = atTimestampIterator(stream, shardId, futureSec);
+
+ String nextIter = given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetRecords")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"ShardIterator\": \"" + iterator + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Records.size()", equalTo(0))
+ .body("NextShardIterator", not(isEmptyOrNullString()))
+ .extract().jsonPath().getString("NextShardIterator");
+
+ // NextShardIterator should be a valid (caught-up) iterator — re-use returns 0 records, no error.
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetRecords")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"ShardIterator\": \"" + nextIter + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Records.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(53)
+ void atTimestampOnEmptyShardReturnsZero() {
+ String stream = "at-timestamp-empty";
+ String shardId = atTimestampCreateStream(stream);
+
+ String iterator = atTimestampIterator(stream, shardId, System.currentTimeMillis() / 1000.0);
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetRecords")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"ShardIterator\": \"" + iterator + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Records.size()", equalTo(0))
+ .body("NextShardIterator", not(isEmptyOrNullString()));
+ }
+
+ @Test
+ @Order(54)
+ void atTimestampWithoutTimestampParamIs400() {
+ String stream = "at-timestamp-missing-param";
+ atTimestampCreateStream(stream);
+
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"StreamName\": \"" + stream
+ + "\", \"ShardId\": \"shardId-000000000000\", \"ShardIteratorType\": \"AT_TIMESTAMP\"}")
+ .when().post("/")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidArgumentException"));
+ }
+
+ @Test
+ @Order(56)
+ void atTimestampWithNonNumericTimestampIs400() {
+ String stream = "at-timestamp-bad-type";
+ atTimestampCreateStream(stream);
+
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"StreamName\": \"" + stream
+ + "\", \"ShardId\": \"shardId-000000000000\", \"ShardIteratorType\": \"AT_TIMESTAMP\", \"Timestamp\": \"not-a-number\"}")
+ .when().post("/")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidArgumentException"));
+ }
+
+ @Test
+ @Order(55)
+ void trimHorizonIteratorStillWorksAfterEncodingBump() {
+ // Regression: 5-part old iterators should still decode via split(-1) compat,
+ // and the new TRIM_HORIZON/LATEST/AT_SEQUENCE_NUMBER paths must not trip over the new 6th slot.
+ String stream = "post-bump-trim-horizon";
+ String shardId = atTimestampCreateStream(stream);
+ atTimestampPutAndGetSequence(stream, "YQ==");
+ atTimestampPutAndGetSequence(stream, "Yg==");
+
+ String iterator = given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"StreamName\": \"" + stream + "\", \"ShardId\": \"" + shardId
+ + "\", \"ShardIteratorType\": \"TRIM_HORIZON\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().jsonPath().getString("ShardIterator");
+
+ given()
+ .header("X-Amz-Target", "Kinesis_20131202.GetRecords")
+ .contentType(KINESIS_CONTENT_TYPE)
+ .body("{\"ShardIterator\": \"" + iterator + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Records.size()", equalTo(2));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java
index 1f6d7ec586..aa5ea24e49 100644
--- a/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java
@@ -352,4 +352,56 @@ class KinesisServiceTest {
assertEquals("NONE", unencrypted.getEncryptionType());
assertNull(unencrypted.getKeyId());
}
+
+ @Test
+ void legacyFivePartIteratorStillDecodes() {
+ kinesisService.createStream("my-stream", 1, REGION);
+ kinesisService.putRecord("my-stream", "a".getBytes(StandardCharsets.UTF_8), "pk", REGION);
+ kinesisService.putRecord("my-stream", "b".getBytes(StandardCharsets.UTF_8), "pk", REGION);
+
+ // Hand-crafted 5-part iterator in the pre-bump format.
+ String raw = "my-stream|shardId-000000000000|TRIM_HORIZON||0";
+ String legacyIterator = java.util.Base64.getEncoder()
+ .encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+
+ Map<String, Object> result = kinesisService.getRecords(legacyIterator, null, REGION);
+ @SuppressWarnings("unchecked")
+ List<KinesisRecord> records = (List<KinesisRecord>) result.get("Records");
+ assertEquals(2, records.size(), "5-part iterator must still decode after encoding bump");
+ }
+
+ @Test
+ void atTimestampIteratorRequiresTimestamp() {
+ kinesisService.createStream("my-stream", 1, REGION);
+ kinesisService.putRecord("my-stream", "a".getBytes(StandardCharsets.UTF_8), "pk", REGION);
+
+ // getShardIterator encodes even with null timestamp (handler is the enforcement point for the API).
+ // But getRecords must reject an AT_TIMESTAMP iterator that lacks the timestamp slot.
+ String iterator = kinesisService.getShardIterator("my-stream", "shardId-000000000000",
+ "AT_TIMESTAMP", null, null, REGION);
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kinesisService.getRecords(iterator, null, REGION));
+ assertEquals("InvalidArgumentException", ex.getErrorCode());
+ }
+
+ @Test
+ void atTimestampBoundaryIsInclusive() {
+ kinesisService.createStream("my-stream", 1, REGION);
+ kinesisService.putRecord("my-stream", "a".getBytes(StandardCharsets.UTF_8), "pk", REGION);
+ // Read back the exact timestamp of record 0 to use as the boundary.
+ String firstIter = kinesisService.getShardIterator("my-stream", "shardId-000000000000",
+ "TRIM_HORIZON", null, null, REGION);
+ @SuppressWarnings("unchecked")
+ List<KinesisRecord> first = (List<KinesisRecord>) kinesisService.getRecords(firstIter, null, REGION)
+ .get("Records");
+ Instant arrivedAt = first.get(0).getApproximateArrivalTimestamp();
+
+ String atIter = kinesisService.getShardIterator("my-stream", "shardId-000000000000",
+ "AT_TIMESTAMP", null, arrivedAt.toEpochMilli(), REGION);
+ @SuppressWarnings("unchecked")
+ List<KinesisRecord> got = (List<KinesisRecord>) kinesisService.getRecords(atIter, null, REGION)
+ .get("Records");
+ assertEquals(1, got.size(), "AT_TIMESTAMP boundary is >= (inclusive)");
+ }
}
\ No newline at end of file