Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudwatch): Adds support for orderBy, pagination, limit in DescribeLogStreams response (#2362)

floverfelt846e78db12a2
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsDescribeStreamsOrderingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsDescribeStreamsOrderingTest.java
new file mode 100644
index 0000000000..9d7c5c21f2
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsDescribeStreamsOrderingTest.java
@@ -0,0 +1,134 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
+import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
+import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
+import software.amazon.awssdk.services.cloudwatchlogs.model.InvalidParameterException;
+import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream;
+import software.amazon.awssdk.services.cloudwatchlogs.model.OrderBy;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@DisplayName("CloudWatch Logs DescribeLogStreams ordering and pagination")
+class CloudWatchLogsDescribeStreamsOrderingTest {
+
+ @Test
+ @DisplayName("orderBy LastEventTime descending with limit 1 returns the most recently active stream")
+ void lastEventTimeDescendingWithLimitReturnsMostRecentStream() {
+ String groupName = "/test/" + TestFixtures.uniqueName("logs-describe-streams-order");
+
+ try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) {
+ try {
+ logs.createLogGroup(request -> request.logGroupName(groupName));
+ // Alphabetical order deliberately disagrees with event recency, so a
+ // name-sorted result (the pre-fix behavior) fails the assertion.
+ long base = System.currentTimeMillis();
+ createStreamWithEvent(logs, groupName, "a-oldest", base - 2000);
+ createStreamWithEvent(logs, groupName, "b-newest", base);
+ createStreamWithEvent(logs, groupName, "c-middle", base - 1000);
+
+ DescribeLogStreamsResponse response = logs.describeLogStreams(request -> request
+ .logGroupName(groupName)
+ .orderBy(OrderBy.LAST_EVENT_TIME)
+ .descending(true)
+ .limit(1));
+
+ assertThat(response.logStreams())
+ .as("limit is honored on the wire")
+ .hasSize(1);
+ assertThat(response.logStreams().get(0).logStreamName())
+ .as("descending LastEventTime puts the most recently active stream first")
+ .isEqualTo("b-newest");
+ assertThat(response.nextToken())
+ .as("more streams remain, so a next page is advertised")
+ .isNotNull();
+ } finally {
+ deleteIfPresent(logs, groupName);
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("the SDK paginator walks every stream once and terminates")
+ void paginatorWalksEveryStreamOnceAndTerminates() {
+ String groupName = "/test/" + TestFixtures.uniqueName("logs-describe-streams-paging");
+
+ try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) {
+ try {
+ logs.createLogGroup(request -> request.logGroupName(groupName));
+ for (int i = 0; i < 5; i++) {
+ int index = i;
+ logs.createLogStream(request -> request
+ .logGroupName(groupName)
+ .logStreamName("stream-" + index));
+ }
+
+ List<String> names = new ArrayList<>();
+ logs.describeLogStreamsPaginator(request -> request
+ .logGroupName(groupName)
+ .limit(2))
+ .stream()
+ .forEach(page -> page.logStreams().stream()
+ .map(LogStream::logStreamName)
+ .forEach(names::add));
+
+ assertThat(names)
+ .as("every stream is seen exactly once, name-ascending by default")
+ .containsExactly("stream-0", "stream-1", "stream-2", "stream-3", "stream-4");
+ } finally {
+ deleteIfPresent(logs, groupName);
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("orderBy LastEventTime combined with a name prefix is rejected like real AWS")
+ void lastEventTimeWithPrefixIsRejected() {
+ String groupName = "/test/" + TestFixtures.uniqueName("logs-describe-streams-reject");
+
+ try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) {
+ try {
+ logs.createLogGroup(request -> request.logGroupName(groupName));
+
+ assertThatThrownBy(() -> logs.describeLogStreams(request -> request
+ .logGroupName(groupName)
+ .logStreamNamePrefix("stream")
+ .orderBy(OrderBy.LAST_EVENT_TIME)))
+ .as("real AWS rejects LastEventTime ordering with a logStreamNamePrefix")
+ .isInstanceOf(InvalidParameterException.class);
+ } finally {
+ deleteIfPresent(logs, groupName);
+ }
+ }
+ }
+
+ private static void createStreamWithEvent(CloudWatchLogsClient logs, String groupName,
+ String streamName, long timestamp) {
+ logs.createLogStream(request -> request
+ .logGroupName(groupName)
+ .logStreamName(streamName));
+ logs.putLogEvents(request -> request
+ .logGroupName(groupName)
+ .logStreamName(streamName)
+ .logEvents(InputLogEvent.builder()
+ .timestamp(timestamp)
+ .message("event for " + streamName)
+ .build()));
+ }
+
+ private static void deleteIfPresent(CloudWatchLogsClient logs, String groupName) {
+ boolean present = logs.describeLogGroups(request -> request.logGroupNamePrefix(groupName))
+ .logGroups()
+ .stream()
+ .anyMatch(group -> groupName.equals(group.logGroupName()));
+ if (present) {
+ logs.deleteLogGroup(request -> request.logGroupName(groupName));
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
index 925104d5d8..ed3f900978 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
@@ -135,12 +135,17 @@ public class CloudWatchLogsHandler {
private Response handleDescribeLogStreams(JsonNode request, String region) {
String groupName = resolveLogGroupName(request);
String prefix = request.path("logStreamNamePrefix").asText(null);
- List<LogStream> streams = logsService.describeLogStreams(groupName, prefix, region);
+ String orderBy = request.path("orderBy").asText(null);
+ boolean descending = request.path("descending").asBoolean(false);
+ int limit = request.path("limit").asInt(0);
+ String nextToken = request.has("nextToken") ? request.path("nextToken").asText(null) : null;
+ CloudWatchLogsService.DescribeLogStreamsResult result =
+ logsService.describeLogStreams(groupName, prefix, orderBy, descending, limit, nextToken, region);
String logGroupArn = logsService.buildArn(groupName, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode streamsArray = objectMapper.createArrayNode();
- for (LogStream s : streams) {
+ for (LogStream s : result.logStreams()) {
ObjectNode node = objectMapper.createObjectNode();
node.put("logStreamName", s.getLogStreamName());
node.put("arn", logGroupArn + ":log-stream:" + s.getLogStreamName());
@@ -157,6 +162,9 @@ public class CloudWatchLogsHandler {
streamsArray.add(node);
}
response.set("logStreams", streamsArray);
+ if (result.nextToken() != null) {
+ response.put("nextToken", result.nextToken());
+ }
return Response.ok(response).build();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
index 6ddba64111..faa70c4e9c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
@@ -15,7 +15,9 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
@@ -24,6 +26,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
@@ -61,6 +64,13 @@ public class CloudWatchLogsService {
// self-healing emulator artifact we accept rather than complicate the injectable clock with nanoTime.
private final LongSupplier clock;
+ /**
+ * DescribeLogStreams pagination snapshots keyed by the snapshot id embedded in nextToken.
+ * TTL-evicted on snapshot creation; see describeLogStreams for why pagination is
+ * snapshot-based rather than offset- or cursor-based.
+ */
+ private final ConcurrentHashMap<String, StreamPageSnapshot> streamPageSnapshots = new ConcurrentHashMap<>();
+
/** Cached Logs Insights queries keyed by queryId, bounded with LRU-style eviction. */
private static final int MAX_STORED_QUERIES = 100;
private final Map<String, QueryRecord> insightsQueries = Collections.synchronizedMap(
@@ -305,12 +315,48 @@ public class CloudWatchLogsService {
LOG.infov("Deleted log stream: {0}/{1}", groupName, streamName);
}
+ public record DescribeLogStreamsResult(List<LogStream> logStreams, String nextToken) {}
+
public List<LogStream> describeLogStreams(String groupName, String prefix, String region) {
+ return describeLogStreams(groupName, prefix, null, false, 0, null, region).logStreams();
+ }
+
+ public DescribeLogStreamsResult describeLogStreams(String groupName, String prefix, String orderBy,
+ boolean descending, int limit, String nextToken,
+ String region) {
+ boolean byLastEventTime = "LastEventTime".equals(orderBy);
+ if (orderBy != null && !orderBy.isBlank() && !byLastEventTime && !"LogStreamName".equals(orderBy)) {
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value '" + orderBy + "' at 'orderBy' failed to satisfy "
+ + "constraint: Member must satisfy enum value set: [LogStreamName, LastEventTime]", 400);
+ }
+ // Matches real AWS: LastEventTime ordering cannot be combined with a name prefix.
+ if (byLastEventTime && prefix != null && !prefix.isBlank()) {
+ throw new AwsException("InvalidParameterException",
+ "Cannot order by LastEventTime with a logStreamNamePrefix.", 400);
+ }
+
// Verify group exists
groupStore.get(groupKey(region, groupName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log group does not exist: " + groupName, 400));
+ int maxResults = Math.min(limit > 0 ? limit : 50, 50);
+
+ // Pagination works over a snapshot of the ordering taken when the first page is
+ // served: the token names a stored snapshot plus a position in it. Re-sorting the
+ // live collection on every page (whether resumed by offset or by sort-key cursor)
+ // skips or repeats streams whenever creates, deletes or PutLogEvents reorder streams
+ // across a page boundary — e.g. an unreturned stream that receives a newer event
+ // between descending LastEventTime pages jumps ahead of any cursor and is never
+ // returned. The snapshot freezes membership and order; attributes are re-read live
+ // per page and streams deleted since the snapshot are dropped, so every stream that
+ // existed when pagination started is returned at most once, with current attributes.
+ if (nextToken != null && !nextToken.isBlank()) {
+ return resumeStreamPage(nextToken, groupName, prefix, byLastEventTime, descending,
+ maxResults, region);
+ }
+
String storagePrefix = streamKeyPrefix(region, groupName);
List<LogStream> result = streamStore.scan(k -> {
if (!k.startsWith(storagePrefix)) {
@@ -322,8 +368,89 @@ public class CloudWatchLogsService {
String streamName = k.substring(storagePrefix.length());
return streamName.startsWith(prefix);
});
- result.sort(Comparator.comparing(LogStream::getLogStreamName));
- return result;
+ // Streams that never received events have no lastEventTimestamp; sort them oldest,
+ // with the name as tie-break so the order stays deterministic.
+ Comparator<LogStream> base = byLastEventTime
+ ? Comparator.comparingLong((LogStream s) ->
+ s.getLastEventTimestamp() == null ? Long.MIN_VALUE : s.getLastEventTimestamp())
+ .thenComparing(LogStream::getLogStreamName)
+ : Comparator.comparing(LogStream::getLogStreamName);
+ result.sort(descending ? base.reversed() : base);
+
+ int end = Math.min(maxResults, result.size());
+ String token = null;
+ if (end < result.size()) {
+ String snapshotId = UUID.randomUUID().toString();
+ streamPageSnapshots.put(snapshotId, new StreamPageSnapshot(
+ groupKey(region, groupName), prefix == null ? "" : prefix,
+ byLastEventTime, descending,
+ result.stream().map(LogStream::getLogStreamName).toList(),
+ clock.getAsLong()));
+ evictExpiredStreamPageSnapshots();
+ token = encodeStreamPageToken(snapshotId, end);
+ }
+ return new DescribeLogStreamsResult(result.subList(0, end), token);
+ }
+
+ private DescribeLogStreamsResult resumeStreamPage(String nextToken, String groupName, String prefix,
+ boolean byLastEventTime, boolean descending,
+ int maxResults, String region) {
+ String[] parts;
+ try {
+ String raw = new String(Base64.getUrlDecoder().decode(nextToken), StandardCharsets.UTF_8);
+ parts = raw.split(":", 3);
+ } catch (IllegalArgumentException e) {
+ throw invalidNextToken();
+ }
+ int position;
+ if (parts.length != 3 || !"v2".equals(parts[0])) {
+ throw invalidNextToken();
+ }
+ try {
+ position = Integer.parseInt(parts[2]);
+ } catch (NumberFormatException e) {
+ throw invalidNextToken();
+ }
+ StreamPageSnapshot snapshot = streamPageSnapshots.get(parts[1]);
+ // A token replayed against a different group or query shape resumes at a meaningless
+ // position; reject it like an unknown or expired token.
+ if (snapshot == null
+ || position < 0
+ || !snapshot.groupKey().equals(groupKey(region, groupName))
+ || !snapshot.prefix().equals(prefix == null ? "" : prefix)
+ || snapshot.byLastEventTime() != byLastEventTime
+ || snapshot.descending() != descending) {
+ throw invalidNextToken();
+ }
+
+ List<LogStream> page = new ArrayList<>();
+ List<String> names = snapshot.streamNames();
+ int index = position;
+ while (index < names.size() && page.size() < maxResults) {
+ streamStore.get(streamKey(region, groupName, names.get(index))).ifPresent(page::add);
+ index++;
+ }
+ String token = index < names.size() ? encodeStreamPageToken(parts[1], index) : null;
+ return new DescribeLogStreamsResult(page, token);
+ }
+
+ private record StreamPageSnapshot(String groupKey, String prefix, boolean byLastEventTime,
+ boolean descending, List<String> streamNames, long createdAtMs) {}
+
+ private static final long STREAM_PAGE_SNAPSHOT_TTL_MS = 15 * 60 * 1000;
+
+ private void evictExpiredStreamPageSnapshots() {
+ long cutoff = clock.getAsLong() - STREAM_PAGE_SNAPSHOT_TTL_MS;
+ streamPageSnapshots.values().removeIf(s -> s.createdAtMs() < cutoff);
+ }
+
+ private static String encodeStreamPageToken(String snapshotId, int position) {
+ String raw = "v2:" + snapshotId + ":" + position;
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static AwsException invalidNextToken() {
+ return new AwsException("InvalidParameterException", "The specified nextToken is invalid.", 400);
}
// ──────────────────────────── Log Events ────────────────────────────
@@ -463,9 +590,6 @@ public class CloudWatchLogsService {
return index;
}
- private AwsException invalidNextToken() {
- return new AwsException("InvalidParameterException", "The specified nextToken is invalid.", 400);
- }
/**
* A FilterLogEvents match paired with the stream that emitted it. FilterLogEvents is the
* cross-stream API, so the stream is what lets a caller attribute a hit; GetLogEvents needs
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java
index 2c7e6189c8..ed4af602e9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java
@@ -74,6 +74,34 @@ class CloudWatchLogsHandlerTest {
assertEquals(STREAM, streams.get(0).path("logStreamName").asText());
}
+ @Test
+ void describeLogStreamsHonorsOrderByDescendingLimitAndReturnsNextToken() {
+ service.createLogStream(GROUP, "another-stream", REGION);
+ service.putLogEvents(GROUP, STREAM,
+ java.util.List.of(java.util.Map.of("timestamp", 2000L, "message", "new")), REGION);
+ service.putLogEvents(GROUP, "another-stream",
+ java.util.List.of(java.util.Map.of("timestamp", 1000L, "message", "old")), REGION);
+ ObjectNode request = MAPPER.createObjectNode()
+ .put("logGroupName", GROUP)
+ .put("orderBy", "LastEventTime")
+ .put("descending", true)
+ .put("limit", 1);
+
+ Response response = handler.handle("DescribeLogStreams", request, REGION);
+
+ assertEquals(200, response.getStatus());
+ ObjectNode entity = (ObjectNode) response.getEntity();
+ JsonNode streams = entity.path("logStreams");
+ assertEquals(1, streams.size());
+ assertEquals(STREAM, streams.get(0).path("logStreamName").asText());
+ assertTrue(entity.has("nextToken"));
+
+ ObjectNode nextRequest = request.deepCopy().put("nextToken", entity.path("nextToken").asText());
+ ObjectNode nextEntity = (ObjectNode) handler.handle("DescribeLogStreams", nextRequest, REGION).getEntity();
+ assertEquals("another-stream", nextEntity.path("logStreams").get(0).path("logStreamName").asText());
+ assertFalse(nextEntity.has("nextToken"));
+ }
+
// ──────────────────────────── GetDataProtectionPolicy ────────────────────────────
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
index 70ace48154..210933e862 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
@@ -215,6 +215,184 @@ class CloudWatchLogsServiceTest {
assertTrue(service.describeLogStreams("/app/logs", null, REGION).isEmpty());
}
+ @Test
+ void describeLogStreamsOrdersByLastEventTimeDescendingWithLimit() {
+ // The SDK idiom for "find the most recently active stream":
+ // orderBy(LAST_EVENT_TIME).descending(true).limit(1). Alphabetical order is set up
+ // to disagree with event recency so a name-sorted result would fail the assertion.
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "a-oldest", REGION);
+ service.createLogStream("/app/logs", "b-newest", REGION);
+ service.createLogStream("/app/logs", "c-middle", REGION);
+ service.putLogEvents("/app/logs", "a-oldest", List.of(Map.of("timestamp", 1000L, "message", "old")), REGION);
+ service.putLogEvents("/app/logs", "b-newest", List.of(Map.of("timestamp", 3000L, "message", "new")), REGION);
+ service.putLogEvents("/app/logs", "c-middle", List.of(Map.of("timestamp", 2000L, "message", "mid")), REGION);
+
+ var result = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 1, null, REGION);
+
+ assertEquals(1, result.logStreams().size());
+ assertEquals("b-newest", result.logStreams().getFirst().getLogStreamName());
+ assertNotNull(result.nextToken());
+ }
+
+ @Test
+ void describeLogStreamsSortsStreamsWithoutEventsOldestByLastEventTime() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "z-empty", REGION);
+ service.createLogStream("/app/logs", "a-active", REGION);
+ service.putLogEvents("/app/logs", "a-active", List.of(Map.of("timestamp", 1000L, "message", "x")), REGION);
+
+ var descending = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 0, null, REGION);
+ assertEquals(List.of("a-active", "z-empty"),
+ descending.logStreams().stream().map(LogStream::getLogStreamName).toList());
+
+ var ascending = service.describeLogStreams("/app/logs", null, "LastEventTime", false, 0, null, REGION);
+ assertEquals(List.of("z-empty", "a-active"),
+ ascending.logStreams().stream().map(LogStream::getLogStreamName).toList());
+ }
+
+ @Test
+ void describeLogStreamsPaginatesWithNextToken() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "stream-1", REGION);
+ service.createLogStream("/app/logs", "stream-2", REGION);
+ service.createLogStream("/app/logs", "stream-3", REGION);
+
+ var page1 = service.describeLogStreams("/app/logs", null, null, false, 2, null, REGION);
+ assertEquals(List.of("stream-1", "stream-2"),
+ page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
+ assertNotNull(page1.nextToken());
+
+ var page2 = service.describeLogStreams("/app/logs", null, null, false, 2, page1.nextToken(), REGION);
+ assertEquals(List.of("stream-3"),
+ page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
+ assertNull(page2.nextToken());
+ }
+
+ @Test
+ void describeLogStreamsRejectsMalformedNextToken() {
+ // A garbage token must fail loudly: silently restarting from the first page makes
+ // custom pagination loops duplicate results or never progress.
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "stream-1", REGION);
+
+ AwsException e = assertThrows(AwsException.class, () ->
+ service.describeLogStreams("/app/logs", null, null, false, 0, "not-a-token", REGION));
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ }
+
+ @Test
+ void describeLogStreamsRejectsTokenFromDifferentOrdering() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "stream-1", REGION);
+ service.createLogStream("/app/logs", "stream-2", REGION);
+
+ String nameOrderToken = service
+ .describeLogStreams("/app/logs", null, null, false, 1, null, REGION)
+ .nextToken();
+ assertNotNull(nameOrderToken);
+
+ AwsException e = assertThrows(AwsException.class, () ->
+ service.describeLogStreams("/app/logs", null, "LastEventTime", true, 1, nameOrderToken, REGION));
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ }
+
+ @Test
+ void describeLogStreamsPaginationDoesNotSkipAfterDeletionBetweenPages() {
+ // A positional offset applied to the re-scanned collection would skip stream-3 here:
+ // deleting already-returned stream-1 shifts everything left by one. The cursor keeps
+ // the resume point anchored to the last returned stream instead.
+ service.createLogGroup("/app/logs", null, null, REGION);
+ for (int i = 1; i <= 4; i++) {
+ service.createLogStream("/app/logs", "stream-" + i, REGION);
+ }
+
+ var page1 = service.describeLogStreams("/app/logs", null, null, false, 2, null, REGION);
+ assertEquals(List.of("stream-1", "stream-2"),
+ page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
+
+ service.deleteLogStream("/app/logs", "stream-1", REGION);
+
+ var page2 = service.describeLogStreams("/app/logs", null, null, false, 2, page1.nextToken(), REGION);
+ assertEquals(List.of("stream-3", "stream-4"),
+ page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
+ assertNull(page2.nextToken());
+ }
+
+ @Test
+ void describeLogStreamsLastEventTimePaginationDoesNotRepeatReorderedStreams() {
+ // PutLogEvents to an already-returned stream between pages moves it even further
+ // ahead in descending order. A positional offset would then re-serve the stream at
+ // the boundary; the cursor never returns anything at-or-before the last seen key.
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "a", REGION);
+ service.createLogStream("/app/logs", "b", REGION);
+ service.createLogStream("/app/logs", "c", REGION);
+ service.createLogStream("/app/logs", "d", REGION);
+ service.putLogEvents("/app/logs", "a", List.of(Map.of("timestamp", 1000L, "message", "x")), REGION);
+ service.putLogEvents("/app/logs", "b", List.of(Map.of("timestamp", 2000L, "message", "x")), REGION);
+ service.putLogEvents("/app/logs", "c", List.of(Map.of("timestamp", 3000L, "message", "x")), REGION);
+ service.putLogEvents("/app/logs", "d", List.of(Map.of("timestamp", 4000L, "message", "x")), REGION);
+
+ var page1 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, null, REGION);
+ assertEquals(List.of("d", "c"),
+ page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
+
+ service.putLogEvents("/app/logs", "d", List.of(Map.of("timestamp", 5000L, "message", "x")), REGION);
+
+ var page2 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, page1.nextToken(), REGION);
+ assertEquals(List.of("b", "a"),
+ page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
+ assertNull(page2.nextToken());
+ }
+
+ @Test
+ void describeLogStreamsReturnsUnseenStreamThatReorderedAcrossThePageBoundary() {
+ // An unreturned stream that receives a newer event between descending LastEventTime
+ // pages sorts ahead of any saved sort-key cursor on the next request and would be
+ // skipped forever. The snapshot freezes the ordering at page one, so the stream is
+ // still returned in its original position.
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.createLogStream("/app/logs", "a", REGION);
+ service.createLogStream("/app/logs", "b", REGION);
+ service.createLogStream("/app/logs", "c", REGION);
+ service.createLogStream("/app/logs", "d", REGION);
+ service.putLogEvents("/app/logs", "a", List.of(Map.of("timestamp", 1000L, "message", "x")), REGION);
+ service.putLogEvents("/app/logs", "b", List.of(Map.of("timestamp", 2000L, "message", "x")), REGION);
+ service.putLogEvents("/app/logs", "c", List.of(Map.of("timestamp", 3000L, "message", "x")), REGION);
+ service.putLogEvents("/app/logs", "d", List.of(Map.of("timestamp", 4000L, "message", "x")), REGION);
+
+ var page1 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, null, REGION);
+ assertEquals(List.of("d", "c"),
+ page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
+
+ // b was not returned yet; this would now sort it ahead of c, the last returned stream.
+ service.putLogEvents("/app/logs", "b", List.of(Map.of("timestamp", 9000L, "message", "x")), REGION);
+
+ var page2 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, page1.nextToken(), REGION);
+ assertEquals(List.of("b", "a"),
+ page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
+ assertNull(page2.nextToken());
+ // Attributes are live even though the position is frozen.
+ assertEquals(9000L, page2.logStreams().getFirst().getLastEventTimestamp());
+ }
+
+ @Test
+ void describeLogStreamsRejectsLastEventTimeWithPrefix() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ AwsException e = assertThrows(AwsException.class, () ->
+ service.describeLogStreams("/app/logs", "stream", "LastEventTime", true, 0, null, REGION));
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ }
+
+ @Test
+ void describeLogStreamsRejectsUnknownOrderBy() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ AwsException e = assertThrows(AwsException.class, () ->
+ service.describeLogStreams("/app/logs", null, "CreationTime", false, 0, null, REGION));
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ }
+
@Test
void deleteLogGroupCascadesStreamsAndEvents() {
service.createLogGroup("/app/logs", null, null, REGION);