diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsFilterPaginationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsFilterPaginationTest.java new file mode 100644 index 0000000000..118562e682 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsFilterPaginationTest.java @@ -0,0 +1,124 @@ +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.FilterLogEventsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilteredLogEvent; +import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("CloudWatch Logs FilterLogEvents pagination") +class CloudWatchLogsFilterPaginationTest { + + @Test + @DisplayName("the SDK paginator walks every match once and terminates") + void paginatorWalksEveryMatchOnceAndTerminates() { + String groupName = "/test/" + TestFixtures.uniqueName("logs-filter-pagination"); + String streamName = "stream-1"; + + try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) { + try { + logs.createLogGroup(request -> request.logGroupName(groupName)); + logs.createLogStream(request -> request + .logGroupName(groupName) + .logStreamName(streamName)); + + long base = System.currentTimeMillis(); + List events = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + int index = i; + events.add(InputLogEvent.builder() + .timestamp(base + index) + .message("msg-" + index) + .build()); + } + logs.putLogEvents(request -> request + .logGroupName(groupName) + .logStreamName(streamName) + .logEvents(events)); + + // The paginator is the point of the test. This SDK's FilterLogEventsIterable + // keeps requesting while nextToken is non-empty and, unlike GetLogEventsIterable, + // has no guard against being handed the same token twice. A response that + // advertises a next page on the final page therefore never terminates here. + List messages = new ArrayList<>(); + List pages = new ArrayList<>(); + logs.filterLogEventsPaginator(request -> request + .logGroupName(groupName) + .limit(2)) + .stream() + .forEach(page -> { + pages.add(page); + page.events().stream().map(FilteredLogEvent::message).forEach(messages::add); + }); + + assertThat(messages) + .as("every match is seen exactly once, oldest first") + .containsExactly("msg-0", "msg-1", "msg-2", "msg-3", "msg-4"); + assertThat(pages).hasSize(3); + assertThat(pages.get(pages.size() - 1).nextToken()) + .as("an absent token is how FilterLogEvents signals the end") + .isNull(); + } finally { + deleteIfPresent(logs, groupName); + } + } + } + + @Test + @DisplayName("a token from a previous page resumes rather than restarting") + void tokenResumesRatherThanRestarting() { + String groupName = "/test/" + TestFixtures.uniqueName("logs-filter-pagination-resume"); + String streamName = "stream-1"; + + try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) { + try { + logs.createLogGroup(request -> request.logGroupName(groupName)); + logs.createLogStream(request -> request + .logGroupName(groupName) + .logStreamName(streamName)); + + long base = System.currentTimeMillis(); + logs.putLogEvents(request -> request + .logGroupName(groupName) + .logStreamName(streamName) + .logEvents( + InputLogEvent.builder().timestamp(base).message("first").build(), + InputLogEvent.builder().timestamp(base + 1).message("second").build(), + InputLogEvent.builder().timestamp(base + 2).message("third").build())); + + FilterLogEventsResponse firstPage = logs.filterLogEvents(request -> request + .logGroupName(groupName) + .limit(2)); + assertThat(firstPage.events()).extracting(FilteredLogEvent::message) + .containsExactly("first", "second"); + assertThat(firstPage.nextToken()).isNotNull(); + + FilterLogEventsResponse secondPage = logs.filterLogEvents(request -> request + .logGroupName(groupName) + .limit(2) + .nextToken(firstPage.nextToken())); + assertThat(secondPage.events()).extracting(FilteredLogEvent::message) + .containsExactly("third"); + assertThat(secondPage.nextToken()).isNull(); + } finally { + deleteIfPresent(logs, groupName); + } + } + } + + 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/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index e6126391bf..09b1d5bb3f 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -87,6 +87,23 @@ For simple substring matching, `FilterLogEvents` is the more predictable option Floci matches `--filter-pattern` as a plain substring of the message; the real filter-pattern syntax (`?ERROR ?WARN`, `{ $.level = "ERROR" }`, and so on) is not parsed. +### Reading events past the limit + +`FilterLogEvents` and `GetLogEvents` both page, and they signal the end of the results differently +because the AWS APIs do. + +`FilterLogEvents` pages forward only. Its `nextToken` is an `f/` offset into the matched set, +so the offset counts matches, not stored events: a request narrowed by `--filter-pattern`, +`--start-time` or `--log-stream-names` pages through only what it matched. A missing token starts +from the oldest match, and **a response with no `nextToken` means pagination is finished**, so the +final page omits it. An unrecognized, non-numeric or negative token returns +`InvalidParameterException` (400). `startFromHead` is not supported, so results always run oldest +first. + +`GetLogEvents` pages in both directions with `f/` and `b/`, and always returns +`nextForwardToken` and `nextBackwardToken`. It signals the end by returning the same token it was +given rather than by omitting it, which is what its SDK paginators expect. + ### Configuration | Variable | Default | Description | 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 0a278e0f80..925104d5d8 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 @@ -203,12 +203,14 @@ public class CloudWatchLogsHandler { Long endTime = request.has("endTime") ? request.path("endTime").asLong() : null; String filterPattern = request.path("filterPattern").asText(null); int limit = request.path("limit").asInt(0); + String nextToken = request.has("nextToken") ? request.path("nextToken").asText(null) : null; List streamNames = new ArrayList<>(); request.path("logStreamNames").forEach(n -> streamNames.add(resolveLogStreamName(n.asText(null)))); CloudWatchLogsService.FilteredLogEventsResult result = - logsService.filterLogEvents(groupName, streamNames, startTime, endTime, filterPattern, limit, region); + logsService.filterLogEvents(groupName, streamNames, startTime, endTime, filterPattern, limit, + nextToken, region); ObjectNode response = objectMapper.createObjectNode(); response.set("events", buildFilteredEventsArray(result.events())); 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 b39f318876..b03fc09001 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 @@ -475,7 +475,7 @@ public class CloudWatchLogsService { public FilteredLogEventsResult filterLogEvents(String groupName, List streamNames, Long startTime, Long endTime, String filterPattern, int limit, - String region) { + String nextToken, String region) { int maxEvents = Math.min(limit > 0 ? limit : Integer.MAX_VALUE, maxEventsPerQuery); @@ -500,16 +500,38 @@ public class CloudWatchLogsService { all.sort(Comparator.comparing(FilteredEvent::event, EVENT_ORDER)); - List result = all.stream() + List matches = all.stream() .filter(f -> (startTime == null || f.event().getTimestamp() >= startTime) && (endTime == null || f.event().getTimestamp() <= endTime)) .filter(f -> filterPattern == null || filterPattern.isBlank() || f.event().getMessage().contains(filterPattern)) - .limit(maxEvents) .toList(); - String nextToken = result.size() >= maxEvents ? UUID.randomUUID().toString() : null; - return new FilteredLogEventsResult(result, nextToken); + // The cursor indexes matches rather than stored events, which is why the window is applied + // here instead of folded into the stream as a limit. Forward-only, so one prefix where + // GetLogEvents needs two. + int total = matches.size(); + int pageStart; + if (nextToken != null && nextToken.startsWith("f/")) { + pageStart = Math.min(parseTokenIndex(nextToken, 2), total); + } else if (nextToken != null) { + throw invalidNextToken(); + } else { + pageStart = 0; + } + // Subtracting from `total` rather than adding to `pageStart` keeps the arithmetic inside + // the list's own bounds, so a max-events cap configured near Integer.MAX_VALUE cannot + // overflow the end index negative. + int pageEnd = pageStart + Math.min(maxEvents, total - pageStart); + + List page = matches.subList(pageStart, pageEnd); + + // Unlike GetLogEvents, which echoes its token back so an SDK paginator can stop on a repeat, + // FilterLogEvents signals exhaustion by omitting the token, and its paginators keep going + // while one is present. The second clause refuses a cursor that cannot advance, which a + // max-events cap of zero would otherwise produce. + String pageToken = pageEnd < total && pageEnd > pageStart ? "f/" + pageEnd : null; + return new FilteredLogEventsResult(page, pageToken); } // ──────────────────────────── Logs Insights Queries ──────────────────────────── 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 d5a2b2bb39..2c7e6189c8 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 @@ -17,6 +17,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -374,6 +375,47 @@ class CloudWatchLogsHandlerTest { assertEquals(2, ((ObjectNode) response.getEntity()).path("events").size()); } + @Test + void filterLogEventsPagesForwardWithTheReturnedToken() { + // The wire-level version of the pagination contract: the token comes back on the + // response, goes out on the next request, and the second page carries the matches the + // first one capped off. + long now = System.currentTimeMillis(); + service.putLogEvents(GROUP, STREAM, java.util.List.of( + java.util.Map.of("timestamp", now, "message", "msg-0"), + java.util.Map.of("timestamp", now + 1, "message", "msg-1"), + java.util.Map.of("timestamp", now + 2, "message", "msg-2"), + java.util.Map.of("timestamp", now + 3, "message", "msg-3"), + java.util.Map.of("timestamp", now + 4, "message", "msg-4") + ), REGION); + + ObjectNode firstRequest = MAPPER.createObjectNode(); + firstRequest.put("logGroupName", GROUP); + firstRequest.put("limit", 3); + + Response firstResponse = handler.handle("FilterLogEvents", firstRequest, REGION); + assertEquals(200, firstResponse.getStatus()); + ObjectNode firstBody = (ObjectNode) firstResponse.getEntity(); + assertEquals(3, firstBody.path("events").size()); + assertEquals("msg-0", firstBody.path("events").get(0).path("message").asText()); + String nextToken = firstBody.path("nextToken").asText(null); + assertNotNull(nextToken, "a capped page must advertise the rest"); + + ObjectNode secondRequest = MAPPER.createObjectNode(); + secondRequest.put("logGroupName", GROUP); + secondRequest.put("limit", 3); + secondRequest.put("nextToken", nextToken); + + Response secondResponse = handler.handle("FilterLogEvents", secondRequest, REGION); + assertEquals(200, secondResponse.getStatus()); + ObjectNode secondBody = (ObjectNode) secondResponse.getEntity(); + assertEquals(2, secondBody.path("events").size()); + assertEquals("msg-3", secondBody.path("events").get(0).path("message").asText()); + assertEquals("msg-4", secondBody.path("events").get(1).path("message").asText()); + assertTrue(secondBody.path("nextToken").isMissingNode(), + "an absent nextToken is how FilterLogEvents says pagination is finished"); + } + // ──────────────────────────── Resilience ──────────────────────────── @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 7ce41e1bfa..f2f71c3fc2 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 @@ -284,7 +284,7 @@ class CloudWatchLogsServiceTest { service.putLogEvents("/app/logs", "stream-1", events, REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", null, null, null, "SEQLINE", 100, REGION); + "/app/logs", null, null, null, "SEQLINE", 100, null, REGION); assertEquals(10, result.events().size()); for (int i = 0; i < 10; i++) { @@ -323,7 +323,7 @@ class CloudWatchLogsServiceTest { ), REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", null, null, null, "ERROR", 100, REGION); + "/app/logs", null, null, null, "ERROR", 100, null, REGION); assertEquals(2, result.events().size()); assertTrue(result.events().stream().allMatch(f -> f.event().getMessage().contains("ERROR"))); } @@ -341,7 +341,7 @@ class CloudWatchLogsServiceTest { List.of(Map.of("timestamp", now + 1, "message", "ERROR: from two")), REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", null, null, null, "ERROR", 100, REGION); + "/app/logs", null, null, null, "ERROR", 100, null, REGION); assertEquals(2, result.events().size()); assertEquals("stream-1", result.events().get(0).logStreamName()); @@ -361,7 +361,7 @@ class CloudWatchLogsServiceTest { List.of(Map.of("timestamp", now + 1, "message", "drop me")), REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", List.of("stream-2"), null, null, null, 100, REGION); + "/app/logs", List.of("stream-2"), null, null, null, 100, null, REGION); assertEquals(1, result.events().size()); assertEquals("stream-2", result.events().getFirst().logStreamName()); @@ -384,7 +384,7 @@ class CloudWatchLogsServiceTest { List.of(Map.of("timestamp", now, "message", "archived")), REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", null, null, null, null, 100, REGION); + "/app/logs", null, null, null, null, 100, null, REGION); assertEquals(1, result.events().size()); assertEquals("live", result.events().getFirst().event().getMessage()); @@ -402,7 +402,7 @@ class CloudWatchLogsServiceTest { List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "hello")), REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", null, null, null, null, 100, REGION); + "/app/logs", null, null, null, null, 100, null, REGION); assertEquals(1, result.events().size()); assertEquals(awkward, result.events().getFirst().logStreamName()); @@ -420,7 +420,7 @@ class CloudWatchLogsServiceTest { ), REGION); CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( - "/app/logs", null, null, null, null, 100, REGION); + "/app/logs", null, null, null, null, 100, null, REGION); assertEquals(2, result.events().size()); } @@ -598,6 +598,276 @@ class CloudWatchLogsServiceTest { assertEquals("f/5", result.nextForwardToken()); } + @Test + void filterLogEventsPagesForwardToTheNewestMatches() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 5); + + CloudWatchLogsService.FilteredLogEventsResult page1 = service.filterLogEvents( + "/app/logs", null, null, null, null, 3, null, REGION); + + assertEquals(List.of("msg-0", "msg-1", "msg-2"), + page1.events().stream().map(f -> f.event().getMessage()).toList()); + assertEquals("f/3", page1.nextToken()); + + CloudWatchLogsService.FilteredLogEventsResult page2 = service.filterLogEvents( + "/app/logs", null, null, null, null, 3, page1.nextToken(), REGION); + + // The newest matches were unreachable before: the cap kept the oldest slice and the token + // carried no position, so this second page could never be requested. + assertEquals(List.of("msg-3", "msg-4"), + page2.events().stream().map(f -> f.event().getMessage()).toList()); + assertNull(page2.nextToken(), "a short final page must not advertise more results"); + } + + @Test + void filterLogEventsOmitsTokenOnASingleFullPage() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 3); + + CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( + "/app/logs", null, null, null, null, 3, null, REGION); + + assertEquals(3, result.events().size()); + assertNull(result.nextToken(), "a page that exactly exhausts the matches is the last one"); + } + + @Test + void filterLogEventsOmitsTokenOnAFullFinalPage() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 6); + + CloudWatchLogsService.FilteredLogEventsResult page1 = service.filterLogEvents( + "/app/logs", null, null, null, null, 3, null, REGION); + assertEquals(3, page1.events().size()); + assertEquals("f/3", page1.nextToken()); + + CloudWatchLogsService.FilteredLogEventsResult page2 = service.filterLogEvents( + "/app/logs", null, null, null, null, 3, page1.nextToken(), REGION); + + // Both pages are exactly full, so page size cannot distinguish "more to come" from + // "finished". Only the position can, which is what makes this the case that pins the + // emission condition. + assertEquals(3, page2.events().size()); + assertEquals("msg-5", page2.events().get(2).event().getMessage()); + assertNull(page2.nextToken()); + } + + @Test + void filterLogEventsEmptyGroupReturnsEmptyPageWithNoToken() { + service.createLogGroup("/app/logs", null, null, REGION); + + CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( + "/app/logs", null, null, null, null, 10, null, REGION); + + assertTrue(result.events().isEmpty()); + assertNull(result.nextToken()); + } + + @Test + void filterLogEventsAllMatchesExcludedReturnsEmptyPageWithNoToken() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 5); + + CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( + "/app/logs", null, null, null, "NOTHING-MATCHES-THIS", 3, null, REGION); + + assertTrue(result.events().isEmpty()); + assertNull(result.nextToken()); + } + + @Test + void filterLogEventsTokenPastTheEndReturnsEmptyPageWithNoToken() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 3); + + CloudWatchLogsService.FilteredLogEventsResult result = service.filterLogEvents( + "/app/logs", null, null, null, null, 10, "f/99", REGION); + + assertTrue(result.events().isEmpty()); + assertNull(result.nextToken()); + } + + @Test + void filterLogEventsCursorAppliesAfterPatternAndTimeFilters() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + + long now = System.currentTimeMillis(); + service.putLogEvents("/app/logs", "stream-1", List.of( + Map.of("timestamp", now, "message", "ERROR: one"), + Map.of("timestamp", now + 1, "message", "INFO: noise"), + Map.of("timestamp", now + 2, "message", "ERROR: two"), + Map.of("timestamp", now + 3, "message", "INFO: more noise"), + Map.of("timestamp", now + 4, "message", "ERROR: three") + ), REGION); + + CloudWatchLogsService.FilteredLogEventsResult page1 = service.filterLogEvents( + "/app/logs", null, null, null, "ERROR", 2, null, REGION); + assertEquals(2, page1.events().size()); + assertEquals("ERROR: one", page1.events().get(0).event().getMessage()); + assertEquals("ERROR: two", page1.events().get(1).event().getMessage()); + // Offset 2 indexes the three matches, not the five stored events. Indexing the raw scan + // would land on "ERROR: two" here. + assertEquals("f/2", page1.nextToken()); + + CloudWatchLogsService.FilteredLogEventsResult page2 = service.filterLogEvents( + "/app/logs", null, null, null, "ERROR", 2, page1.nextToken(), REGION); + assertEquals(1, page2.events().size()); + assertEquals("ERROR: three", page2.events().get(0).event().getMessage()); + assertNull(page2.nextToken()); + } + + @Test + void filterLogEventsPaginatesAcrossStreamsKeepingAttribution() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + service.createLogStream("/app/logs", "stream-2", REGION); + + long now = System.currentTimeMillis(); + service.putLogEvents("/app/logs", "stream-1", List.of( + Map.of("timestamp", now, "message", "ERROR: a"), + Map.of("timestamp", now + 2, "message", "ERROR: c") + ), REGION); + service.putLogEvents("/app/logs", "stream-2", List.of( + Map.of("timestamp", now + 1, "message", "ERROR: b"), + Map.of("timestamp", now + 3, "message", "ERROR: d") + ), REGION); + + CloudWatchLogsService.FilteredLogEventsResult page1 = service.filterLogEvents( + "/app/logs", null, null, null, "ERROR", 2, null, REGION); + assertEquals(List.of("stream-1", "stream-2"), + page1.events().stream().map(CloudWatchLogsService.FilteredEvent::logStreamName).toList()); + assertEquals("f/2", page1.nextToken()); + + CloudWatchLogsService.FilteredLogEventsResult page2 = service.filterLogEvents( + "/app/logs", null, null, null, "ERROR", 2, page1.nextToken(), REGION); + assertEquals(List.of("stream-1", "stream-2"), + page2.events().stream().map(CloudWatchLogsService.FilteredEvent::logStreamName).toList()); + assertEquals(List.of("ERROR: c", "ERROR: d"), + page2.events().stream().map(f -> f.event().getMessage()).toList()); + assertNull(page2.nextToken()); + } + + @Test + void filterLogEventsPaginatesWithinNamedStreamsOnly() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + service.createLogStream("/app/logs", "stream-2", REGION); + + long now = System.currentTimeMillis(); + service.putLogEvents("/app/logs", "stream-1", List.of( + Map.of("timestamp", now, "message", "kept-0"), + Map.of("timestamp", now + 2, "message", "kept-1"), + Map.of("timestamp", now + 4, "message", "kept-2") + ), REGION); + service.putLogEvents("/app/logs", "stream-2", List.of( + Map.of("timestamp", now + 1, "message", "excluded-0"), + Map.of("timestamp", now + 3, "message", "excluded-1") + ), REGION); + + CloudWatchLogsService.FilteredLogEventsResult page1 = service.filterLogEvents( + "/app/logs", List.of("stream-1"), null, null, null, 2, null, REGION); + assertEquals(List.of("kept-0", "kept-1"), + page1.events().stream().map(f -> f.event().getMessage()).toList()); + // The excluded stream's events are dropped before the offset is computed, so the cursor + // never has to skip over them. + assertEquals("f/2", page1.nextToken()); + + CloudWatchLogsService.FilteredLogEventsResult page2 = service.filterLogEvents( + "/app/logs", List.of("stream-1"), null, null, null, 2, page1.nextToken(), REGION); + assertEquals(List.of("kept-2"), + page2.events().stream().map(f -> f.event().getMessage()).toList()); + assertNull(page2.nextToken()); + } + + @Test + void filterLogEventsNeverEmitsACursorThatCannotAdvance() { + CloudWatchLogsService capped = new CloudWatchLogsService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + 0, + new RegionResolver("us-east-1", "000000000000") + ); + capped.createLogGroup("/app/logs", null, null, REGION); + capped.createLogStream("/app/logs", "stream-1", REGION); + capped.putLogEvents("/app/logs", "stream-1", + List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "msg")), REGION); + + CloudWatchLogsService.FilteredLogEventsResult result = capped.filterLogEvents( + "/app/logs", null, null, null, null, 0, null, REGION); + + // A zero cap yields an empty page. Emitting a token here would point at the same offset + // forever, so a paginating client would never terminate. + assertTrue(result.events().isEmpty()); + assertNull(result.nextToken()); + } + + @Test + void filterLogEventsRejectsMalformedNextToken() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 3); + + AwsException exception = assertThrows(AwsException.class, () -> + service.filterLogEvents("/app/logs", null, null, null, null, 10, "f/not-a-token", REGION)); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + assertEquals(400, exception.getHttpStatus()); + assertEquals("The specified nextToken is invalid.", exception.getMessage()); + } + + @Test + void filterLogEventsRejectsNegativeNextToken() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 3); + + AwsException exception = assertThrows(AwsException.class, () -> + service.filterLogEvents("/app/logs", null, null, null, null, 10, "f/-1", REGION)); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + assertEquals(400, exception.getHttpStatus()); + } + + @Test + void filterLogEventsRejectsOverflowNextToken() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 3); + + AwsException exception = assertThrows(AwsException.class, () -> + service.filterLogEvents("/app/logs", null, null, null, null, 10, "f/2147483648", REGION)); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + assertEquals(400, exception.getHttpStatus()); + } + + @Test + void filterLogEventsRejectsUnrecognizedNextTokens() { + service.createLogGroup("/app/logs", null, null, REGION); + service.createLogStream("/app/logs", "stream-1", REGION); + putEvents("/app/logs", "stream-1", System.currentTimeMillis(), 3); + + // "b/0" is a GetLogEvents backward token; FilterLogEvents pages forward only, so it is + // not a token this action can have issued. + for (String token : List.of("", "b/0", "x/1", "garbage")) { + AwsException exception = assertThrows(AwsException.class, () -> + service.filterLogEvents("/app/logs", null, null, null, null, 10, token, REGION)); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + assertEquals(400, exception.getHttpStatus()); + assertEquals("The specified nextToken is invalid.", exception.getMessage()); + } + } + // ──────────────────────────── Subscription Filters ──────────────────────────── @Test