Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudwatch): add Logs Insights query support (#1448)

Beytullah Gunduz89fadbad8165
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java
new file mode 100644
index 0000000000..e11081552e
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java
@@ -0,0 +1,186 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.*;
+import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
+import software.amazon.awssdk.services.cloudwatchlogs.model.*;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.*;
+
+/**
+ * CloudWatch Logs Insights compatibility: StartQuery / GetQueryResults / StopQuery.
+ *
+ * <p>Seeds a log group with structured JSON events and exercises the same query shape real
+ * clients send — filter on a nested JSON field ({@code params.job_id}), drop a log level,
+ * sort by {@code @timestamp}, and dedup. StartQuery times are epoch <em>seconds</em> while
+ * event timestamps are millis.
+ */
+@DisplayName("CloudWatch Logs Insights")
+class CloudWatchLogsInsightsTest {
+
+ private static CloudWatchLogsClient logs;
+
+ private static final String GROUP = "/test/" + TestFixtures.uniqueName("insights");
+ private static final String STREAM = "stream-01";
+ private static String jobId;
+ private static long baseMs;
+
+ @BeforeAll
+ static void setUp() {
+ logs = TestFixtures.cloudWatchLogsClient();
+ logs.createLogGroup(b -> b.logGroupName(GROUP));
+ logs.createLogStream(b -> b.logGroupName(GROUP).logStreamName(STREAM));
+
+ baseMs = System.currentTimeMillis();
+ jobId = TestFixtures.uniqueName("job");
+ logs.putLogEvents(b -> b
+ .logGroupName(GROUP)
+ .logStreamName(STREAM)
+ .logEvents(
+ InputLogEvent.builder().timestamp(baseMs - 3000).message(json("INFO", "job started", jobId)).build(),
+ InputLogEvent.builder().timestamp(baseMs - 2000).message(json("TRACE", "verbose noise", jobId)).build(),
+ InputLogEvent.builder().timestamp(baseMs - 1000).message(json("INFO", "unrelated", "other-job")).build(),
+ InputLogEvent.builder().timestamp(baseMs).message(json("ERROR", "job boom", jobId)).build()
+ ));
+ }
+
+ @AfterAll
+ static void tearDown() {
+ if (logs != null) {
+ try {
+ logs.deleteLogGroup(b -> b.logGroupName(GROUP));
+ } catch (RuntimeException ignored) {
+ // best-effort cleanup
+ }
+ logs.close();
+ }
+ }
+
+ @Test
+ @DisplayName("StartQuery returns a queryId")
+ void startQueryReturnsQueryId() {
+ StartQueryResponse start = startTestQuery();
+ assertThat(start.queryId()).isNotBlank();
+ }
+
+ @Test
+ @DisplayName("GetQueryResults filters by JSON field, drops TRACE, sorts desc and dedups")
+ void getQueryResultsFiltersSortsDedups() {
+ // On real AWS, events are not queryable for several seconds after ingestion; retry the
+ // full start+poll cycle until rows appear or the ~60s deadline elapses.
+ GetQueryResultsResponse res = pollUntilComplete(startTestQuery().queryId());
+ long deadline = System.currentTimeMillis() + 60_000;
+ while (res.results().isEmpty() && System.currentTimeMillis() < deadline) {
+ res = pollUntilComplete(startTestQuery().queryId());
+ }
+
+ assertThat(res.status()).isEqualTo(QueryStatus.COMPLETE);
+
+ // job_id filter keeps 3 events; level != TRACE drops 1 -> 2 rows.
+ assertThat(res.results()).hasSize(2);
+
+ // Every row projects @timestamp and @message.
+ assertThat(res.results()).allSatisfy(row -> {
+ assertThat(row).anySatisfy(f -> assertThat(f.field()).isEqualTo("@timestamp"));
+ assertThat(row).anySatisfy(f -> assertThat(f.field()).isEqualTo("@message"));
+ });
+
+ // sort @timestamp desc -> newest (ERROR "job boom") first, then INFO "job started".
+ assertThat(messageOf(res.results().get(0))).contains("job boom");
+ assertThat(messageOf(res.results().get(1))).contains("job started");
+
+ // The TRACE line and the unrelated job must be excluded.
+ List<String> messages = res.results().stream()
+ .map(CloudWatchLogsInsightsTest::messageOf)
+ .toList();
+ assertThat(messages).noneMatch(m -> m.contains("verbose noise") || m.contains("unrelated"));
+ }
+
+ @Test
+ @DisplayName("StopQuery on a finished query fails with InvalidParameterException")
+ void stopFinishedQueryFailsNotRunning() {
+ StartQueryResponse start = startTestQuery();
+ pollUntilComplete(start.queryId()); // ensure the query has ended
+
+ // AWS: stopping a query that is not running returns an error ("...is not running").
+ assertThatThrownBy(() -> logs.stopQuery(b -> b.queryId(start.queryId())))
+ .isInstanceOfSatisfying(CloudWatchLogsException.class,
+ e -> assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterException"));
+ }
+
+ @Test
+ @DisplayName("StopQuery on a running query returns success")
+ void stopRunningQuerySucceeds() {
+ StartQueryResponse start = startTestQuery();
+
+ // Only meaningful where the server models an async Running window: real AWS, or Floci with a
+ // non-zero query-completion-delay (FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS=2000).
+ // With Floci's default (instant completion) there is no Running phase, so this case is skipped
+ // rather than asserted.
+ String status = logs.getQueryResults(b -> b.queryId(start.queryId())).statusAsString();
+ Assumptions.assumeTrue("Running".equals(status) || "Scheduled".equals(status),
+ "no Running window (instant completion) — nothing to stop");
+
+ // On real AWS the query can complete in the gap between the status check and the stop call;
+ // treat InvalidParameterException from stopQuery as a valid outcome rather than a failure.
+ try {
+ StopQueryResponse stop = logs.stopQuery(b -> b.queryId(start.queryId()));
+ assertThat(stop.success()).isTrue();
+ } catch (CloudWatchLogsException e) {
+ if ("InvalidParameterException".equals(e.awsErrorDetails().errorCode())) {
+ Assumptions.abort("query completed before stop");
+ }
+ throw e;
+ }
+ }
+
+ // ──────────────────────────── helpers ────────────────────────────
+
+ private static StartQueryResponse startTestQuery() {
+ long nowSec = baseMs / 1000;
+ return logs.startQuery(b -> b
+ .logGroupNames(GROUP)
+ .startTime(nowSec - 300)
+ .endTime(nowSec + 300)
+ .queryString(query()));
+ }
+
+ private static String query() {
+ return "fields @timestamp, @message"
+ + " | filter params.job_id = '" + jobId + "'"
+ + " | filter level != 'TRACE'"
+ + " | sort @timestamp desc"
+ + " | dedup @timestamp, @message";
+ }
+
+ private static GetQueryResultsResponse pollUntilComplete(String queryId) {
+ GetQueryResultsResponse res = null;
+ for (int i = 0; i < 75; i++) { // ~15s budget; real AWS Insights queries run asynchronously
+ res = logs.getQueryResults(b -> b.queryId(queryId));
+ QueryStatus status = res.status();
+ if (status == QueryStatus.COMPLETE || status == QueryStatus.FAILED || status == QueryStatus.CANCELLED) {
+ break;
+ }
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ }
+ return res;
+ }
+
+ private static String messageOf(List<ResultField> row) {
+ return row.stream()
+ .filter(f -> "@message".equals(f.field()))
+ .map(ResultField::value)
+ .findFirst()
+ .orElse("");
+ }
+
+ private static String json(String level, String message, String job) {
+ return "{\"level\":\"" + level + "\",\"message\":\"" + message + "\",\"params\":{\"job_id\":\"" + job + "\"}}";
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 6e4bc9fc9c..801cb4ef22 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -871,6 +871,15 @@ public interface EmulatorConfig {
@WithDefault("10000")
int maxEventsPerQuery();
+
+ /**
+ * Artificial Logs Insights query completion delay, in milliseconds. With the default 0,
+ * queries complete immediately (fast local dev). A positive value emulates the real
+ * asynchronous lifecycle — StartQuery → Running → Complete after this delay — which also
+ * makes StopQuery on a still-running query return {@code success=true}.
+ */
+ @WithDefault("0")
+ long queryCompletionDelayMs();
}
interface CloudWatchMetricsServiceConfig {
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 f0472ea95b..c37b0f2b21 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
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;
@@ -15,6 +16,7 @@ import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -53,6 +55,9 @@ public class CloudWatchLogsHandler {
case "DescribeSubscriptionFilters" -> handleDescribeSubscriptionFilters(request, region);
case "DeleteSubscriptionFilter" -> handleDeleteSubscriptionFilter(request, region);
case "GetDataProtectionPolicy" -> handleGetDataProtectionPolicy(request, region);
+ case "StartQuery" -> handleStartQuery(request, region);
+ case "GetQueryResults" -> handleGetQueryResults(request, region);
+ case "StopQuery" -> handleStopQuery(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
@@ -196,6 +201,94 @@ public class CloudWatchLogsHandler {
return Response.ok(response).build();
}
+ // ──────────────────────────── Logs Insights Queries ────────────────────────────
+
+ private Response handleStartQuery(JsonNode request, String region) {
+ // AWS requires exactly one of logGroupName / logGroupNames / logGroupIdentifiers.
+ // The zero-selector case is enforced by the service (it throws when the resolved group
+ // list is empty); here we reject the other invalid shape: more than one selector type.
+ if (presentSelectorCount(request) > 1) {
+ throw new AwsException("InvalidParameterException",
+ "Exactly one of logGroupName, logGroupNames, or logGroupIdentifiers may be specified.",
+ 400);
+ }
+
+ List<String> logGroupNames = new ArrayList<>();
+ request.path("logGroupNames").forEach(n -> logGroupNames.add(extractLogGroupNameFromArn(n.asText())));
+ if (request.has("logGroupName")) {
+ logGroupNames.add(extractLogGroupNameFromArn(request.path("logGroupName").asText()));
+ }
+ request.path("logGroupIdentifiers").forEach(n -> logGroupNames.add(extractLogGroupNameFromArn(n.asText())));
+
+ long startTime = request.path("startTime").asLong();
+ long endTime = request.path("endTime").asLong();
+ String queryString = request.path("queryString").asText("");
+ Integer limit = request.has("limit") ? request.path("limit").asInt() : null;
+
+ String queryId = logsService.startQuery(logGroupNames, startTime, endTime, queryString, limit, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("queryId", queryId);
+ return Response.ok(response).build();
+ }
+
+ /**
+ * Counts how many of the three mutually exclusive StartQuery log-group selector <em>fields</em> the
+ * request carries: {@code logGroupName}, {@code logGroupNames}, {@code logGroupIdentifiers}. A field
+ * counts if it is present at all — even a blank string or empty array — using the same presence rule
+ * ({@code has}) as the merge path below, so a serialized-but-empty selector cannot slip past the
+ * mutual-exclusivity check. A single empty/blank selector yields no groups and is rejected downstream
+ * by the service. (The AWS SDK omits unset list fields, so a well-formed single-selector request
+ * still carries exactly one field.)
+ */
+ private int presentSelectorCount(JsonNode request) {
+ int count = 0;
+ if (request.has("logGroupName")) {
+ count++;
+ }
+ if (request.has("logGroupNames")) {
+ count++;
+ }
+ if (request.has("logGroupIdentifiers")) {
+ count++;
+ }
+ return count;
+ }
+
+ private Response handleGetQueryResults(JsonNode request, String region) {
+ String queryId = request.path("queryId").asText();
+ CloudWatchLogsService.QueryState state = logsService.getQueryResults(queryId);
+
+ ArrayNode results = objectMapper.createArrayNode();
+ for (LinkedHashMap<String, String> row : state.rows()) {
+ ArrayNode rowArray = objectMapper.createArrayNode();
+ row.forEach((field, value) -> {
+ ObjectNode fieldNode = objectMapper.createObjectNode();
+ fieldNode.put("field", field);
+ fieldNode.put("value", value);
+ rowArray.add(fieldNode);
+ });
+ results.add(rowArray);
+ }
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("results", results);
+ response.put("status", state.status());
+ ObjectNode statistics = objectMapper.createObjectNode();
+ statistics.put("recordsMatched", (double) state.recordsMatched());
+ statistics.put("recordsScanned", (double) state.recordsScanned());
+ statistics.put("bytesScanned", 0.0);
+ response.set("statistics", statistics);
+ return Response.ok(response).build();
+ }
+
+ private Response handleStopQuery(JsonNode request, String region) {
+ String queryId = request.path("queryId").asText();
+ boolean success = logsService.stopQuery(queryId);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("success", success);
+ return Response.ok(response).build();
+ }
+
private Response handlePutRetentionPolicy(JsonNode request, String region) {
String groupName = request.path("logGroupName").asText();
int days = request.path("retentionInDays").asInt();
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 fd2c528070..3a7dda7f54 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,12 +15,15 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
@ApplicationScoped
public class CloudWatchLogsService {
@@ -49,6 +52,22 @@ public class CloudWatchLogsService {
* the highest sequence already in the store so ordering survives persistence reloads.
*/
private final AtomicLong ingestionSequence;
+ private final long queryCompletionDelayMs;
+
+ // Wall-clock source of "now" for the query lifecycle, injected so tests can drive it deterministically.
+ // Non-monotonic: a backward NTP step could briefly flip a Complete query back to Running — a rare,
+ // self-healing emulator artifact we accept rather than complicate the injectable clock with nanoTime.
+ private final LongSupplier clock;
+
+ /** 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(
+ new LinkedHashMap<>(16, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry<String, QueryRecord> eldest) {
+ return size() > MAX_STORED_QUERIES;
+ }
+ });
@Inject
public CloudWatchLogsService(StorageFactory storageFactory,
@@ -64,7 +83,9 @@ public class CloudWatchLogsService {
storageFactory.create("cloudwatchlogs", "cwlogs-subscription-filters.json",
new TypeReference<>() {}),
config.services().cloudwatchlogs().maxEventsPerQuery(),
- regionResolver
+ regionResolver,
+ config.services().cloudwatchlogs().queryCompletionDelayMs(),
+ System::currentTimeMillis
);
}
@@ -74,6 +95,18 @@ public class CloudWatchLogsService {
StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
int maxEventsPerQuery,
RegionResolver regionResolver) {
+ this(groupStore, streamStore, eventStore, subscriptionFilterStore,
+ maxEventsPerQuery, regionResolver, 0L, System::currentTimeMillis);
+ }
+
+ CloudWatchLogsService(StorageBackend<String, LogGroup> groupStore,
+ StorageBackend<String, LogStream> streamStore,
+ StorageBackend<String, LogEvent> eventStore,
+ StorageBackend<String, SubscriptionFilter> subscriptionFilterStore,
+ int maxEventsPerQuery,
+ RegionResolver regionResolver,
+ long queryCompletionDelayMs,
+ LongSupplier clock) {
this.groupStore = groupStore;
this.streamStore = streamStore;
this.eventStore = eventStore;
@@ -85,6 +118,9 @@ public class CloudWatchLogsService {
.max()
.orElse(0L);
this.ingestionSequence = new AtomicLong(maxSequence);
+ // A negative delay is meaningless; treat it as instant completion.
+ this.queryCompletionDelayMs = Math.max(0, queryCompletionDelayMs);
+ this.clock = clock;
}
// ──────────────────────────── Log Groups ────────────────────────────
@@ -382,6 +418,166 @@ public class CloudWatchLogsService {
return new FilteredLogEventsResult(result, nextToken);
}
+ // ──────────────────────────── Logs Insights Queries ────────────────────────────
+
+ /** A query's status and (once Complete) its projected rows — the AWS GetQueryResults shape. */
+ public record QueryState(String status, List<LinkedHashMap<String, String>> rows,
+ long recordsScanned, long recordsMatched) {}
+
+ /** Lifecycle state of a stored Insights query; {@link #label()} is the AWS wire form. */
+ private enum InsightsQueryStatus {
+ RUNNING("Running"),
+ COMPLETE("Complete"),
+ CANCELLED("Cancelled");
+
+ private final String label;
+
+ InsightsQueryStatus(String label) {
+ this.label = label;
+ }
+
+ String label() {
+ return label;
+ }
+ }
+
+ /**
+ * A stored Insights query. Results are computed eagerly at StartQuery, but the query reports
+ * {@code Running} until {@code completeAtMs} (an artificial delay emulating AWS's asynchronous
+ * execution), then {@code Complete} — unless cancelled by StopQuery, after which it is
+ * {@code Cancelled}. State transitions are time-driven and computed on read. {@code recordsMatched}
+ * is captured at construction so it survives the Running/Cancelled row masking and the row-drop on cancel.
+ */
+ private static final class QueryRecord {
+ private List<LinkedHashMap<String, String>> rows;
+ private final long recordsScanned;
+ private final long recordsMatched;
+ private final long completeAtMs;
+ private boolean cancelled;
+
+ QueryRecord(List<LinkedHashMap<String, String>> rows, long recordsScanned, long completeAtMs) {
+ this.rows = rows;
+ this.recordsScanned = recordsScanned;
+ this.recordsMatched = rows.size();
+ this.completeAtMs = completeAtMs;
+ }
+
+ private InsightsQueryStatus status(long nowMs) {
+ if (cancelled) {
+ return InsightsQueryStatus.CANCELLED;
+ }
+ return nowMs >= completeAtMs ? InsightsQueryStatus.COMPLETE : InsightsQueryStatus.RUNNING;
+ }
+
+ /**
+ * Snapshot this query in the AWS GetQueryResults shape. Rows are exposed only once
+ * {@code Complete}, and always as a defensive copy (the cached list is never handed out); while
+ * Running or Cancelled the rows are masked empty, but {@code recordsMatched} still reports the
+ * full match count.
+ */
+ synchronized QueryState snapshot(long nowMs) {
+ InsightsQueryStatus status = status(nowMs);
+ List<LinkedHashMap<String, String>> visible =
+ status == InsightsQueryStatus.COMPLETE ? List.copyOf(rows) : List.of();
+ return new QueryState(status.label(), visible, recordsScanned, recordsMatched);
+ }
+
+ /** Cancels the query iff still running, dropping its now-unreachable rows. Returns true if this call stopped it. */
+ synchronized boolean stopIfRunning(long nowMs) {
+ if (!cancelled && nowMs < completeAtMs) {
+ cancelled = true;
+ rows = List.of();
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Start a CloudWatch Logs Insights query and cache it under a new queryId. Results are computed
+ * eagerly (the scan is in-memory); the query then reports {@code Running} until the configured
+ * completion delay elapses (default 0 = immediate), emulating AWS's async execution.
+ * {@code startTimeSeconds}/{@code endTimeSeconds} are epoch <em>seconds</em> (the StartQuery
+ * contract); {@link LogEvent} timestamps are epoch millis, so they are scaled for comparison.
+ */
+ public String startQuery(List<String> logGroupNames, long startTimeSeconds, long endTimeSeconds,
+ String queryString, Integer limit, String region) {
+ long startMs = startTimeSeconds * 1000L;
+ long endMs = endTimeSeconds * 1000L;
+
+ // De-duplicate the requested groups (the same group can arrive via multiple selectors, e.g.
+ // logGroupNames + logGroupIdentifiers) so it is scanned — and counted — once, not twice.
+ List<String> distinctGroups = logGroupNames.stream()
+ .filter(g -> g != null && !g.isBlank())
+ .distinct()
+ .toList();
+ if (distinctGroups.isEmpty()) {
+ // AWS StartQuery requires a log-group selector; an empty or all-blank one is an invalid
+ // request, not a valid query that happens to match nothing.
+ throw new AwsException("InvalidParameterException",
+ "StartQuery must specify at least one log group.", 400);
+ }
+
+ List<LogEvent> gathered = new ArrayList<>();
+ for (String groupName : distinctGroups) {
+ // Real AWS StartQuery returns ResourceNotFoundException for a log group that does not exist,
+ // rather than a successful empty query; mirror that instead of silently scanning nothing.
+ groupStore.get(groupKey(region, groupName)).orElseThrow(() ->
+ new AwsException("ResourceNotFoundException",
+ "The specified log group does not exist: " + groupName, 400));
+ String prefix = region + "::" + groupName + "::";
+ for (LogEvent e : eventStore.scan(k -> k.startsWith(prefix))) {
+ if (e.getTimestamp() >= startMs && e.getTimestamp() <= endMs) {
+ gathered.add(e);
+ }
+ }
+ }
+
+ int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery;
+ List<LinkedHashMap<String, String>> rows =
+ LogsInsightsQuery.parse(queryString).evaluate(gathered, effectiveLimit);
+
+ String queryId = UUID.randomUUID().toString();
+ long completeAtMs = clock.getAsLong() + queryCompletionDelayMs;
+ insightsQueries.put(queryId, new QueryRecord(rows, gathered.size(), completeAtMs));
+ LOG.infov("Logs Insights query {0}: scanned {1} event(s) across {2} group(s) -> {3} row(s)",
+ queryId, gathered.size(), distinctGroups.size(), rows.size());
+ return queryId;
+ }
+
+ /**
+ * Return a query's status and, once {@code Complete}, its rows. Mirrors AWS: while {@code Running}
+ * or after a StopQuery ({@code Cancelled}) the result set is empty (though {@code recordsMatched}
+ * still reports the full match count); only a Complete query exposes rows. An unknown queryId is an
+ * error on real AWS — and a query that has fallen out of the bounded LRU cache 404s the same way.
+ */
+ public QueryState getQueryResults(String queryId) {
+ QueryRecord rec = insightsQueries.get(queryId);
+ if (rec == null) {
+ throw new AwsException("ResourceNotFoundException",
+ "The specified query does not exist.", 400);
+ }
+ return rec.snapshot(clock.getAsLong());
+ }
+
+ /**
+ * Stop an in-progress query. Mirrors AWS StopQuery: a running query is cancelled and returns
+ * {@code success=true}; an already-ended query throws {@code InvalidParameterException} ("not
+ * running"); an unknown queryId throws {@code ResourceNotFoundException}.
+ */
+ public boolean stopQuery(String queryId) {
+ QueryRecord rec = insightsQueries.get(queryId);
+ if (rec == null) {
+ throw new AwsException("ResourceNotFoundException",
+ "The specified query does not exist.", 400);
+ }
+ if (rec.stopIfRunning(clock.getAsLong())) {
+ return true;
+ }
+ throw new AwsException("InvalidParameterException",
+ "The query you are trying to stop is not running.", 400);
+ }
+
// ──────────────────────────── Subscription Filters ────────────────────────────
public void putSubscriptionFilter(String logGroupName, String filterName, String filterPattern,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogsInsightsQuery.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogsInsightsQuery.java
new file mode 100644
index 0000000000..3f0bbb4412
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogsInsightsQuery.java
@@ -0,0 +1,331 @@
+package io.github.hectorvent.floci.services.cloudwatch.logs;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Minimal CloudWatch Logs Insights query engine.
+ *
+ * <p>Implements the subset of the Logs Insights query language that clients use in practice:
+ * <ul>
+ * <li>{@code fields a, b, ...} — projection (defaults to {@code @timestamp, @message})</li>
+ * <li>{@code filter <field> = 'v'} / {@code filter <field> != 'v'} — equality / inequality</li>
+ * <li>{@code sort <field> [asc|desc]}</li>
+ * <li>{@code dedup <field, ...>} — keep the first row per unique tuple (applied after sort)</li>
+ * <li>{@code limit N}</li>
+ * </ul>
+ * Fields may be the synthetic {@code @timestamp} / {@code @message} / {@code @ingestionTime} /
+ * {@code @ptr}, or a dotted path into the JSON log message (e.g. {@code params.job_id}, {@code level}).
+ *
+ * <p>This is intentionally <em>not</em> a full Insights implementation: unsupported commands
+ * (e.g. {@code stats}, {@code parse}) are ignored with a warning. Pipes ({@code |}) inside quoted
+ * filter values are respected and do not split the query into stages.
+ */
+final class LogsInsightsQuery {
+
+ private static final Logger LOG = Logger.getLogger(LogsInsightsQuery.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final DateTimeFormatter TS_FORMAT =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneOffset.UTC);
+
+ private final List<String> fields = new ArrayList<>();
+ private final List<Filter> filters = new ArrayList<>();
+ private String sortField;
+ private boolean sortDesc;
+ private List<String> dedupFields;
+ private Integer limit;
+
+ private record Filter(String field, boolean negate, String value) {}
+
+ private LogsInsightsQuery() {}
+
+ static LogsInsightsQuery parse(String queryString) {
+ LogsInsightsQuery q = new LogsInsightsQuery();
+ if (queryString != null && !queryString.isBlank()) {
+ for (String rawStage : splitStages(queryString)) {
+ String stage = rawStage.trim();
+ if (stage.isEmpty()) {
+ continue;
+ }
+ String[] parts = stage.split("\\s+", 2);
+ String cmd = parts[0].toLowerCase();
+ String args = parts.length > 1 ? parts[1].trim() : "";
+ q.applyStage(cmd, args);
+ }
+ }
+ if (q.fields.isEmpty()) {
+ q.fields.add("@timestamp");
+ q.fields.add("@message");
+ }
+ return q;
+ }
+
+ /**
+ * Split a query into pipeline stages on {@code |}, ignoring pipes inside single- or double-quoted
+ * values (so {@code filter x = 'a|b'} stays one stage). Escaped quotes are not interpreted.
+ */
+ private static List<String> splitStages(String query) {
+ List<String> stages = new ArrayList<>();
+ StringBuilder current = new StringBuilder();
+ char quote = 0;
+ for (int i = 0; i < query.length(); i++) {
+ char c = query.charAt(i);
+ if (quote != 0) {
+ if (c == quote) {
+ quote = 0;
+ }
+ current.append(c);
+ } else if (c == '\'' || c == '"') {
+ quote = c;
+ current.append(c);
+ } else if (c == '|') {
+ stages.add(current.toString());
+ current.setLength(0);
+ } else {
+ current.append(c);
+ }
+ }
+ stages.add(current.toString());
+ return stages;
+ }
+
+ private void applyStage(String cmd, String args) {
+ switch (cmd) {
+ case "fields", "display" -> splitCsv(args, fields);
+ case "filter", "where" -> {
+ Filter f = parseFilter(args);
+ if (f != null) {
+ filters.add(f);
+ }
+ }
+ case "sort", "order" -> {
+ String[] s = args.split("\\s+");
+ if (s.length > 0 && !s[0].isEmpty()) {
+ sortField = s[0].trim();
+ sortDesc = s.length > 1 && s[1].trim().equalsIgnoreCase("desc");
+ }
+ }
+ case "dedup" -> {
+ dedupFields = new ArrayList<>();
+ splitCsv(args, dedupFields);
+ }
+ case "limit" -> {
+ try {
+ limit = Integer.parseInt(args.trim());
+ } catch (NumberFormatException e) {
+ LOG.warnv("Ignoring invalid Logs Insights limit: {0}", args);
+ }
+ }
+ default -> LOG.warnv("Ignoring unsupported Logs Insights command: {0}", cmd);
+ }
+ }
+
+ private static void splitCsv(String args, List<String> target) {
+ for (String token : args.split(",")) {
+ String t = token.trim();
+ if (!t.isEmpty()) {
+ target.add(t);
+ }
+ }
+ }
+
+ private static Filter parseFilter(String expr) {
+ // Scan for the operator OUTSIDE any quoted value, taking the leftmost one and checking
+ // '!=' / '==' before '='. This avoids mistaking an operator inside a quoted literal
+ // (e.g. filter x = 'a==b') for the real one.
+ char quote = 0;
+ for (int i = 0; i < expr.length(); i++) {
+ char c = expr.charAt(i);
+ if (quote != 0) {
+ if (c == quote) {
+ quote = 0;
+ }
+ } else if (c == '\'' || c == '"') {
+ quote = c;
+ } else if (i > 0) {
+ String op = expr.startsWith("!=", i) ? "!="
+ : expr.startsWith("==", i) ? "=="
+ : c == '=' ? "="
+ : null;
+ if (op != null) {
+ String field = expr.substring(0, i).trim();
+ String value = unquote(expr.substring(i + op.length()).trim());
+ return new Filter(field, op.equals("!="), value);
+ }
+ }
+ }
+ LOG.warnv("Ignoring unsupported Logs Insights filter: {0}", expr);
+ return null;
+ }
+
+ private static String unquote(String s) {
+ if (s.length() >= 2) {
+ char first = s.charAt(0);
+ char last = s.charAt(s.length() - 1);
+ if ((first == '\'' && last == '\'') || (first == '"' && last == '"')) {
+ return s.substring(1, s.length() - 1);
+ }
+ }
+ return s;
+ }
+
+ /**
+ * Evaluate the query against the given events.
+ *
+ * @return ordered result rows; each row maps a projected field name to its string value,
+ * in the order declared by {@code fields}, with a synthetic {@code @ptr} appended.
+ */
+ List<LinkedHashMap<String, String>> evaluate(List<LogEvent> events, int defaultLimit) {
+ List<Row> rows = new ArrayList<>(events.size());
+ for (LogEvent e : events) {
+ rows.add(new Row(e, tryParse(e.getMessage())));
+ }
+
+ // filter (logical AND across all filter stages)
+ List<Row> matched = new ArrayList<>();
+ for (Row row : rows) {
+ if (passesFilters(row)) {
+ matched.add(row);
+ }
+ }
+
+ // sort
+ if (sortField != null) {
+ Comparator<Row> cmp = comparatorFor(sortField);
+ matched.sort(sortDesc ? cmp.reversed() : cmp);
+ } else if (dedupFields != null && !dedupFields.isEmpty()) {
+ // AWS: when dedup runs without an explicit preceding sort, results are ordered by the
+ // default descending @timestamp sort before duplicates are discarded, so the first
+ // (newest) row per tuple is the one kept. Reuse the @timestamp comparator reversed so
+ // the sequence/eventId tie-break stays consistent with an explicit `sort @timestamp desc`.
+ matched.sort(comparatorFor("@timestamp").reversed());
+ }
+
+ // dedup (keep first occurrence per tuple, after sorting)
+ if (dedupFields != null && !dedupFields.isEmpty()) {
+ List<Row> deduped = new ArrayList<>();
+ Set<String> seen = new HashSet<>();
+ for (Row row : matched) {
+ StringBuilder key = new StringBuilder();
+ for (String df : dedupFields) {
+ key.append(resolve(row, df)).append('\0');
+ }
+ if (seen.add(key.toString())) {
+ deduped.add(row);
+ }
+ }
+ matched = deduped;
+ }
+
+ // limit
+ int max = limit != null ? Math.min(limit, defaultLimit) : defaultLimit;
+ if (max >= 0 && matched.size() > max) {
+ matched = matched.subList(0, max);
+ }
+
+ // project
+ List<LinkedHashMap<String, String>> out = new ArrayList<>(matched.size());
+ for (Row row : matched) {
+ LinkedHashMap<String, String> projected = new LinkedHashMap<>();
+ for (String field : fields) {
+ String value = resolve(row, field);
+ projected.put(field, value != null ? value : "");
+ }
+ projected.putIfAbsent("@ptr", row.event.getEventId());
+ out.add(projected);
+ }
+ return out;
+ }
+
+ private boolean passesFilters(Row row) {
+ for (Filter f : filters) {
+ String actual = resolve(row, f.field());
+ boolean equals = actual != null && actual.equals(f.value());
+ boolean fails = f.negate() ? equals : !equals;
+ if (fails) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private Comparator<Row> comparatorFor(String field) {
+ if ("@timestamp".equals(field)) {
+ return Comparator.<Row>comparingLong(r -> r.event.getTimestamp())
+ .thenComparingLong(r -> r.event.getSequence())
+ .thenComparing(r -> r.event.getEventId());
+ }
+ if ("@ingestionTime".equals(field)) {
+ // ingestionTime is one wall-clock value per PutLogEvents batch, so whole batches tie on it;
+ // the sequence/eventId tie-break keeps same-batch events in a stable ingestion order.
+ return Comparator.<Row>comparingLong(r -> r.event.getIngestionTime())
+ .thenComparingLong(r -> r.event.getSequence())
+ .thenComparing(r -> r.event.getEventId());
+ }
+ return Comparator.comparing(r -> {
+ String v = resolve(r, field);
+ return v != null ? v : "";
+ });
+ }
+
+ private String resolve(Row row, String field) {
+ switch (field) {
+ case "@timestamp":
+ return TS_FORMAT.format(Instant.ofEpochMilli(row.event.getTimestamp()));
+ case "@ingestionTime":
+ return TS_FORMAT.format(Instant.ofEpochMilli(row.event.getIngestionTime()));
+ case "@message":
+ return row.event.getMessage();
+ case "@ptr":
+ return row.event.getEventId();
+ default:
+ if (row.json == null) {
+ return null;
+ }
+ JsonNode node = row.json;
+ for (String seg : field.split("\\.")) {
+ if (node == null) {
+ return null;
+ }
+ node = node.get(seg);
+ }
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ return node.isValueNode() ? node.asText() : node.toString();
+ }
+ }
+
+ private static JsonNode tryParse(String message) {
+ if (message == null || message.isBlank()) {
+ return null;
+ }
+ try {
+ return MAPPER.readTree(message);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private static final class Row {
+ final LogEvent event;
+ final JsonNode json;
+
+ Row(LogEvent event, JsonNode json) {
+ this.event = event;
+ this.json = json;
+ }
+ }
+}
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 647de15382..541bed0510 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
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import jakarta.ws.rs.core.Response;
@@ -15,6 +16,7 @@ import static org.hamcrest.Matchers.containsString;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -252,4 +254,39 @@ class CloudWatchLogsHandlerTest {
assertTrue(arn.contains(":log-stream:" + STREAM));
assertThat(arn, not(containsString(":*")));
}
+
+ // ──────────────────────────── StartQuery selector validation ────────────────────────────
+
+ @Test
+ void startQueryWithMultipleSelectorTypesThrowsInvalidParameter() {
+ // AWS requires exactly one of logGroupName / logGroupNames / logGroupIdentifiers.
+ // Supplying two selector types (here: logGroupName + logGroupIdentifiers) must be rejected
+ // with InvalidParameterException rather than silently querying the union of both.
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupName", GROUP);
+ request.putArray("logGroupIdentifiers").add(GROUP_ARN);
+ request.put("startTime", 0L);
+ request.put("endTime", 1L);
+ request.put("queryString", "fields @message");
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("StartQuery", request, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void startQueryWithBlankSelectorAlongsideRealOneIsRejected() {
+ // A serialized-but-blank logGroupName next to a real logGroupNames is still two selector fields,
+ // which AWS rejects — the guard must count serialized fields, not treat the blank one as absent.
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupName", "");
+ request.putArray("logGroupNames").add(GROUP);
+ request.put("startTime", 0L);
+ request.put("endTime", 1L);
+ request.put("queryString", "fields @message");
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("StartQuery", request, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java
new file mode 100644
index 0000000000..2c7998c941
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java
@@ -0,0 +1,640 @@
+package io.github.hectorvent.floci.services.cloudwatch.logs;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+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;
+
+/**
+ * Tests the CloudWatch Logs Insights subset ({@code StartQuery}/{@code GetQueryResults}/{@code StopQuery})
+ * against representative query shapes: filtering on nested JSON fields (including deep paths and
+ * whole-object resolution), level exclusion, sort, and dedup. Each test uses its own log group name,
+ * confirming the engine is not coupled to any particular group.
+ */
+class CloudWatchLogsInsightsQueryTest {
+
+ private static final String REGION = "us-east-1";
+ private static final long BASE_MS = 1_700_000_000_000L;
+
+ // A representative Logs Insights query: filter on a nested JSON field, drop a level, sort, dedup.
+ private static final String APP_QUERY = """
+ fields @timestamp, @message
+ | filter params.job_id = 'JOB-1'
+ | filter level != 'TRACE'
+ | sort @timestamp desc
+ | dedup @timestamp, @message
+ """;
+
+ private CloudWatchLogsService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new CloudWatchLogsService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ 10000,
+ new RegionResolver(REGION, "000000000000"));
+ }
+
+ @Test
+ void startQueryFiltersSortsAndDedups() {
+ String group = "/app/etl/worker-logs";
+ String stream = "worker-1";
+ createGroupStream(service, group, stream);
+
+ put(group, stream, BASE_MS + 2000, "INFO", "JOB-1", "alpha");
+ put(group, stream, BASE_MS + 3000, "TRACE", "JOB-1", "trace-line"); // excluded: level == TRACE
+ put(group, stream, BASE_MS + 4000, "INFO", "JOB-2", "other-job"); // excluded: different job_id
+ put(group, stream, BASE_MS + 2000, "INFO", "JOB-1", "alpha"); // duplicate @timestamp + @message
+ put(group, stream, BASE_MS + 5000, "DEBUG", "JOB-1", "delta");
+
+ long startSec = BASE_MS / 1000 - 10;
+ long endSec = startSec + 86400;
+ String queryId = service.startQuery(List.of(group), startSec, endSec, APP_QUERY, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(2, state.rows().size(), "delta + alpha survive filter/dedup");
+
+ // sorted @timestamp desc: delta (BASE+5000) before alpha (BASE+2000)
+ assertTrue(state.rows().get(0).get("@message").contains("delta"));
+ assertTrue(state.rows().get(1).get("@message").contains("alpha"));
+
+ for (LinkedHashMap<String, String> row : state.rows()) {
+ assertTrue(row.containsKey("@timestamp"), "row has @timestamp");
+ assertTrue(row.containsKey("@message"), "row has @message");
+ assertNotNull(row.get("@ptr"), "row has @ptr");
+ }
+ }
+
+ @Test
+ void startQueryRespectsTimeWindow() {
+ String group = "/svc/api/access-logs";
+ String stream = "node-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 2000, "INFO", "JOB-1", "in-window");
+
+ // window entirely before the event → nothing matches
+ long startSec = BASE_MS / 1000 - 1000;
+ long endSec = BASE_MS / 1000 - 100;
+ String queryId = service.startQuery(List.of(group), startSec, endSec, APP_QUERY, null, REGION);
+
+ assertTrue(service.getQueryResults(queryId).rows().isEmpty());
+ }
+
+ @Test
+ void startQueryFindsParamAcrossMultipleGroups() {
+ // The same params.id is logged from several service/engine groups.
+ String reportingSpark = "reporting/spark";
+ String reportingMysql = "reporting/mysql";
+ String dashboardMysql = "dashboard/mysql";
+ String invoiceSpark = "invoice/spark"; // matching event, but NOT queried — must be excluded
+ createGroupStream(service, reportingSpark, "s-1");
+ createGroupStream(service, reportingMysql, "s-1");
+ createGroupStream(service, dashboardMysql, "s-1");
+ createGroupStream(service, invoiceSpark, "s-1");
+
+ putRaw(service, reportingSpark, "s-1", BASE_MS + 2000, idLog("REQ-42", "spark-stage-done"));
+ putRaw(service, reportingMysql, "s-1", BASE_MS + 5000, idLog("REQ-42", "mysql-commit"));
+ putRaw(service, dashboardMysql, "s-1", BASE_MS + 3000, idLog("REQ-42", "dashboard-render"));
+ putRaw(service, reportingMysql, "s-1", BASE_MS + 1000, idLog("REQ-99", "unrelated-id")); // different id → filtered
+ putRaw(service, invoiceSpark, "s-1", BASE_MS + 6000, idLog("REQ-42", "invoice-export")); // matches, group not queried
+
+ String query = """
+ fields @timestamp, @message, params.id
+ | filter params.id = 'REQ-42'
+ | sort @timestamp desc
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ long endSec = startSec + 86400;
+ // Query spans three groups; the params.id filter finds REQ-42 wherever it was logged among them.
+ String queryId = service.startQuery(
+ List.of(reportingSpark, reportingMysql, dashboardMysql), startSec, endSec, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(3, state.rows().size(), "REQ-42 is found across all three queried groups");
+
+ // Every matched row carries the requested param, regardless of which group it came from.
+ for (LinkedHashMap<String, String> row : state.rows()) {
+ assertEquals("REQ-42", row.get("params.id"));
+ }
+
+ // Merged + globally sorted desc: mysql-commit(5000), dashboard-render(3000), spark-stage-done(2000).
+ assertTrue(state.rows().get(0).get("@message").contains("mysql-commit"));
+ assertTrue(state.rows().get(1).get("@message").contains("dashboard-render"));
+ assertTrue(state.rows().get(2).get("@message").contains("spark-stage-done"));
+
+ // A different params.id is filtered out; a matching REQ-42 in the un-queried invoice/spark is excluded.
+ for (LinkedHashMap<String, String> row : state.rows()) {
+ assertFalse(row.get("@message").contains("unrelated-id"));
+ assertFalse(row.get("@message").contains("invoice-export"));
+ }
+ }
+
+ @Test
+ void startQueryDeduplicatesRepeatedLogGroups() {
+ String group = "reporting/dedup";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "once");
+
+ // The same group passed twice must be scanned once. A non-dedup query is used so a double
+ // scan would surface as duplicate rows and an inflated recordsScanned.
+ String query = "fields @message | filter params.job_id = 'JOB-1'";
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group, group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size(), "a repeated group is scanned once, not duplicated");
+ assertEquals(1, state.recordsScanned(), "scan count is not inflated by the repeated group");
+ }
+
+ @Test
+ void startQueryUnknownLogGroupThrowsResourceNotFound() {
+ // The group is never created.
+ long startSec = BASE_MS / 1000 - 10;
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.startQuery(List.of("/app/missing"), startSec, startSec + 86400, APP_QUERY, null, REGION));
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ }
+
+ @Test
+ void filterValueContainingPipeIsNotSplit() {
+ String group = "connectors/webhook";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ putRaw(service, group, stream, BASE_MS + 1000, idLog("REQ|42", "piped"));
+ putRaw(service, group, stream, BASE_MS + 2000, idLog("REQ-99", "other"));
+
+ // The '|' inside the quoted value must not split the query; the filter matches the literal id.
+ String query = "fields @message, params.id | filter params.id = 'REQ|42'";
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size(), "the pipe-containing value matched exactly one event");
+ assertEquals("REQ|42", state.rows().get(0).get("params.id"));
+ }
+
+ @Test
+ void startQueryWithNoLogGroupThrowsInvalidParameter() {
+ long startSec = BASE_MS / 1000 - 10;
+ // No usable selector (empty list, or only blank names) is an invalid request, not an empty success.
+ AwsException empty = assertThrows(AwsException.class, () ->
+ service.startQuery(List.of(), startSec, startSec + 86400, APP_QUERY, null, REGION));
+ assertEquals("InvalidParameterException", empty.getErrorCode());
+
+ AwsException blank = assertThrows(AwsException.class, () ->
+ service.startQuery(List.of(" ", ""), startSec, startSec + 86400, APP_QUERY, null, REGION));
+ assertEquals("InvalidParameterException", blank.getErrorCode());
+ }
+
+ @Test
+ void filterValueContainingEqualsIsNotMisparsed() {
+ String group = "connectors/equals";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ putRaw(service, group, stream, BASE_MS + 1000, idLog("REQ==42", "eq"));
+ putRaw(service, group, stream, BASE_MS + 2000, idLog("REQ-1", "other"));
+
+ // '==' inside the quoted value must not be taken as the filter operator; the real '=' wins.
+ String query = "fields @message, params.id | filter params.id = 'REQ==42'";
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size(), "the value-embedded '==' did not break operator parsing");
+ assertEquals("REQ==42", state.rows().get(0).get("params.id"));
+ }
+
+ @Test
+ void queryResolvesNestedJsonObjectsAndDeepPaths() {
+ String group = "/app/build/publish-logs";
+ String stream = "publisher-1";
+ createGroupStream(service, group, stream);
+
+ // Structured events whose params carry a nested 'artifact_coordinates' JSON object.
+ putRaw(service, group, stream, BASE_MS + 1000,
+ artifactLog("JOB-7", "com.example.tools", "widget-core", "1.2.3"));
+ putRaw(service, group, stream, BASE_MS + 2000,
+ artifactLog("JOB-8", "com.example.other", "gizmo", "4.5.6"));
+
+ // Filter on a DEEP path; project a deep scalar and the whole nested object.
+ String query = """
+ fields @timestamp, params.artifact_coordinates.version, params.artifact_coordinates
+ | filter params.artifact_coordinates.group = 'com.example.tools'
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size(), "only the event whose nested 'group' matches survives the deep-path filter");
+
+ LinkedHashMap<String, String> row = state.rows().get(0);
+ // A deep dotted path resolves to the leaf scalar.
+ assertEquals("1.2.3", row.get("params.artifact_coordinates.version"));
+ // A path to a nested object resolves to its JSON serialization.
+ String coords = row.get("params.artifact_coordinates");
+ assertTrue(coords.contains("\"artifact\":\"widget-core\""), "nested object projected as JSON: " + coords);
+ assertTrue(coords.contains("\"version\":\"1.2.3\""), "nested object projected as JSON: " + coords);
+ }
+
+ @Test
+ void limitTruncatesResultsAfterSort() {
+ String group = "analytics/dashboard";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "one");
+ put(group, stream, BASE_MS + 2000, "INFO", "JOB-1", "two");
+ put(group, stream, BASE_MS + 3000, "INFO", "JOB-1", "three");
+ put(group, stream, BASE_MS + 4000, "INFO", "JOB-1", "four");
+
+ // 'limit 2' applies after sort, keeping only the two newest.
+ String query = """
+ fields @timestamp, @message
+ | filter params.job_id = 'JOB-1'
+ | sort @timestamp desc
+ | limit 2
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(2, state.rows().size(), "limit 2 keeps only the top two after sort");
+ assertTrue(state.rows().get(0).get("@message").contains("four"));
+ assertTrue(state.rows().get(1).get("@message").contains("three"));
+ }
+
+ @Test
+ void sortAscendingByJsonField() {
+ String group = "query-builder/explorer";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ putRaw(service, group, stream, BASE_MS + 1000, idLog("REQ-C", "third"));
+ putRaw(service, group, stream, BASE_MS + 2000, idLog("REQ-A", "first"));
+ putRaw(service, group, stream, BASE_MS + 3000, idLog("REQ-B", "second"));
+
+ // Ascending sort on a nested JSON field (lexicographic via the string comparator).
+ String query = """
+ fields @message, params.id
+ | sort params.id asc
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(3, state.rows().size());
+ assertEquals("REQ-A", state.rows().get(0).get("params.id"));
+ assertEquals("REQ-B", state.rows().get(1).get("params.id"));
+ assertEquals("REQ-C", state.rows().get(2).get("params.id"));
+ }
+
+ @Test
+ void sameMillisecondEventsSortByIngestionSequence() {
+ String group = "analytics/pipeline";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+
+ // Five events sharing ONE millisecond, ingested in a known order. Pre-fix the @timestamp
+ // comparator has no tie-break, so same-ms rows keep arbitrary hash-scan order; post-fix they
+ // are ordered by ingestion sequence. Five events => 120 permutations, so a pre-fix pass by luck
+ // is ~1/120.
+ long ts = BASE_MS + 7000;
+ putRaw(service, group, stream, ts, idLog("REQ-1", "first"));
+ putRaw(service, group, stream, ts, idLog("REQ-2", "second"));
+ putRaw(service, group, stream, ts, idLog("REQ-3", "third"));
+ putRaw(service, group, stream, ts, idLog("REQ-4", "fourth"));
+ putRaw(service, group, stream, ts, idLog("REQ-5", "fifth"));
+
+ String query = """
+ fields @message, params.id
+ | sort @timestamp asc
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(5, state.rows().size());
+ // Ascending @timestamp with a sequence tie-break => strict ingestion order.
+ assertEquals("REQ-1", state.rows().get(0).get("params.id"));
+ assertEquals("REQ-2", state.rows().get(1).get("params.id"));
+ assertEquals("REQ-3", state.rows().get(2).get("params.id"));
+ assertEquals("REQ-4", state.rows().get(3).get("params.id"));
+ assertEquals("REQ-5", state.rows().get(4).get("params.id"));
+ }
+
+ @Test
+ void sameMillisecondEventsSortDescendingReverseIngestion() {
+ String group = "metrics/collector";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+
+ // Same-ms events; descending sort must reverse the ingestion-order tie-break (newest-ingested
+ // first), consistent with reversing the whole @timestamp comparator.
+ long ts = BASE_MS + 8000;
+ putRaw(service, group, stream, ts, idLog("REQ-1", "first"));
+ putRaw(service, group, stream, ts, idLog("REQ-2", "second"));
+ putRaw(service, group, stream, ts, idLog("REQ-3", "third"));
+ putRaw(service, group, stream, ts, idLog("REQ-4", "fourth"));
+ putRaw(service, group, stream, ts, idLog("REQ-5", "fifth"));
+
+ String query = """
+ fields @message, params.id
+ | sort @timestamp desc
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(5, state.rows().size());
+ // Descending: reverse of ingestion order.
+ assertEquals("REQ-5", state.rows().get(0).get("params.id"));
+ assertEquals("REQ-4", state.rows().get(1).get("params.id"));
+ assertEquals("REQ-3", state.rows().get(2).get("params.id"));
+ assertEquals("REQ-2", state.rows().get(3).get("params.id"));
+ assertEquals("REQ-1", state.rows().get(4).get("params.id"));
+ }
+
+ @Test
+ void dedupWithoutSortKeepsNewestPerTupleByDefault() {
+ String group = "reporting/emitter";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+
+ // Two hosts, three events each at distinct timestamps. With NO explicit sort, AWS applies a
+ // default `sort @timestamp desc` before dedup, so the newest event per host survives. Ingestion
+ // order below is deliberately NOT newest-last, so a pre-fix run (dedup over raw hash-scan order)
+ // would keep an arbitrary — usually older — event and fail.
+ putRaw(service, group, stream, BASE_MS + 2000, hostLog("host-a", "a-old"));
+ putRaw(service, group, stream, BASE_MS + 6000, hostLog("host-a", "a-new"));
+ putRaw(service, group, stream, BASE_MS + 4000, hostLog("host-a", "a-mid"));
+ putRaw(service, group, stream, BASE_MS + 1000, hostLog("host-b", "b-old"));
+ putRaw(service, group, stream, BASE_MS + 5000, hostLog("host-b", "b-new"));
+ putRaw(service, group, stream, BASE_MS + 3000, hostLog("host-b", "b-mid"));
+
+ // dedup with no preceding sort => default @timestamp desc, keep newest per host.
+ String query = """
+ fields @message, params.host
+ | dedup params.host
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(2, state.rows().size(), "one surviving row per unique host");
+
+ // Final order also follows the default desc sort: host-a's newest (6000) before host-b's newest (5000).
+ // @message resolves to the raw JSON line, so match by substring (the file's convention).
+ assertTrue(state.rows().get(0).get("@message").contains("a-new"), "newest host-a event survives dedup");
+ assertEquals("host-a", state.rows().get(0).get("params.host"));
+ assertTrue(state.rows().get(1).get("@message").contains("b-new"), "newest host-b event survives dedup");
+ assertEquals("host-b", state.rows().get(1).get("params.host"));
+ }
+
+ @Test
+ void defaultProjectionReturnsTimestampAndMessage() {
+ String group = "metrics/kpi-center";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "hello");
+
+ // No 'fields' stage → the engine defaults to @timestamp, @message.
+ String query = "filter params.job_id = 'JOB-1'";
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size());
+ LinkedHashMap<String, String> row = state.rows().get(0);
+ assertTrue(row.containsKey("@timestamp"), "default projection includes @timestamp");
+ assertTrue(row.containsKey("@message"), "default projection includes @message");
+ assertNotNull(row.get("@ptr"));
+ assertTrue(row.get("@message").contains("hello"));
+ }
+
+ @Test
+ void missingFieldProjectsEmptyAndKeepsEventsOnInequality() {
+ String group = "alerts/notifications";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "present");
+
+ // 'params.absent' is not in the log: projecting it yields "", and '!=' keeps the event (null != 'x').
+ String query = """
+ fields @message, params.absent
+ | filter params.absent != 'x'
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size(), "an event lacking the field survives a '!=' filter on it");
+ assertEquals("", state.rows().get(0).get("params.absent"), "an absent field projects as an empty string");
+ }
+
+ @Test
+ void unsupportedCommandsAreIgnored() {
+ String group = "data-sources/connectors";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "kept");
+ put(group, stream, BASE_MS + 2000, "TRACE", "JOB-1", "dropped");
+
+ // 'parse' / 'stats' are unsupported: ignored with a warning, while the supported stages still run.
+ String query = """
+ fields @message
+ | filter level != 'TRACE'
+ | parse @message '*' as x
+ | stats count(*) by level
+ """;
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size(), "TRACE dropped by filter; parse/stats ignored, not applied");
+ assertTrue(state.rows().get(0).get("@message").contains("kept"));
+ }
+
+ @Test
+ void statisticsReportScannedAndMatched() {
+ String group = "data-studio/insights";
+ String stream = "s-1";
+ createGroupStream(service, group, stream);
+ put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "a");
+ put(group, stream, BASE_MS + 2000, "TRACE", "JOB-1", "b"); // dropped: level
+ put(group, stream, BASE_MS + 3000, "INFO", "JOB-2", "c"); // dropped: job_id
+ put(group, stream, BASE_MS + 4000, "INFO", "JOB-1", "d");
+
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, APP_QUERY, null, REGION);
+
+ CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(4, state.recordsScanned(), "recordsScanned counts every event in the window");
+ assertEquals(2, state.recordsMatched(), "recordsMatched counts only the rows returned after filtering");
+ assertEquals(2, state.rows().size());
+ }
+
+ @Test
+ void getQueryResultsUnknownIdThrowsResourceNotFound() {
+ AwsException ex = assertThrows(AwsException.class, () -> service.getQueryResults("does-not-exist"));
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ }
+
+ @Test
+ void stopCompletedQueryThrowsInvalidParameter() {
+ String group = "/app/batch/spark-logs";
+ String stream = "batch-1";
+ createGroupStream(service, group, stream);
+ // The default service has zero completion delay, so the query is Complete immediately.
+ put(group, stream, BASE_MS + 2000, "INFO", "JOB-1", "alpha");
+ long startSec = BASE_MS / 1000 - 10;
+ String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, APP_QUERY, null, REGION);
+ assertEquals("Complete", service.getQueryResults(queryId).status());
+
+ AwsException ex = assertThrows(AwsException.class, () -> service.stopQuery(queryId));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void stopUnknownQueryThrowsResourceNotFound() {
+ AwsException ex = assertThrows(AwsException.class, () -> service.stopQuery("does-not-exist"));
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ }
+
+ @Test
+ void asyncQueryReportsRunningThenCompleteAfterDelay() {
+ String group = "/app/stream/ingest-logs";
+ String stream = "shard-1";
+ AtomicLong now = new AtomicLong(BASE_MS);
+ CloudWatchLogsService async = newAsyncService(now, 1000L, group, stream);
+ String queryId = async.startQuery(List.of(group), BASE_MS / 1000 - 10, BASE_MS / 1000 + 86400, APP_QUERY, null, REGION);
+
+ // Within the delay window: Running, with no rows exposed yet.
+ assertEquals("Running", async.getQueryResults(queryId).status());
+ assertTrue(async.getQueryResults(queryId).rows().isEmpty());
+ // recordsMatched reports the full match count even while Running (rows masked, statistics not).
+ assertEquals(1, async.getQueryResults(queryId).recordsMatched());
+
+ // Advance the clock past the completion delay: Complete, rows exposed.
+ now.addAndGet(1000);
+ CloudWatchLogsService.QueryState complete = async.getQueryResults(queryId);
+ assertEquals("Complete", complete.status());
+ assertEquals(1, complete.rows().size());
+ }
+
+ @Test
+ void stopRunningQueryCancelsIt() {
+ String group = "/app/stream/replay-logs";
+ String stream = "shard-2";
+ AtomicLong now = new AtomicLong(BASE_MS);
+ CloudWatchLogsService async = newAsyncService(now, 1000L, group, stream);
+ String queryId = async.startQuery(List.of(group), BASE_MS / 1000 - 10, BASE_MS / 1000 + 86400, APP_QUERY, null, REGION);
+ assertEquals("Running", async.getQueryResults(queryId).status());
+
+ // Stopping a running query succeeds and cancels it.
+ assertTrue(async.stopQuery(queryId));
+ CloudWatchLogsService.QueryState cancelled = async.getQueryResults(queryId);
+ assertEquals("Cancelled", cancelled.status());
+ assertTrue(cancelled.rows().isEmpty());
+
+ // Stopping again (already ended) throws InvalidParameterException.
+ AwsException ex = assertThrows(AwsException.class, () -> async.stopQuery(queryId));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void negativeCompletionDelayClampsToImmediateComplete() {
+ String group = "/app/cron/scheduler-logs";
+ String stream = "tick-1";
+ AtomicLong now = new AtomicLong(BASE_MS);
+ CloudWatchLogsService async = newAsyncService(now, -5000L, group, stream);
+ String queryId = async.startQuery(List.of(group), BASE_MS / 1000 - 10, BASE_MS / 1000 + 86400, APP_QUERY, null, REGION);
+
+ // A negative delay must not leave the query stuck Running — it clamps to instant completion.
+ CloudWatchLogsService.QueryState state = async.getQueryResults(queryId);
+ assertEquals("Complete", state.status());
+ assertEquals(1, state.rows().size());
+ }
+
+ // ──────────────────────────── helpers ────────────────────────────
+
+ private CloudWatchLogsService newAsyncService(AtomicLong clockMs, long delayMs, String group, String stream) {
+ CloudWatchLogsService svc = new CloudWatchLogsService(
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ 10000, new RegionResolver(REGION, "000000000000"), delayMs, clockMs::get);
+ createGroupStream(svc, group, stream);
+ putRaw(svc, group, stream, BASE_MS + 2000, jobLog("INFO", "x", "JOB-1"));
+ return svc;
+ }
+
+ private void createGroupStream(CloudWatchLogsService svc, String group, String stream) {
+ svc.createLogGroup(group, null, null, REGION);
+ svc.createLogStream(group, stream, REGION);
+ }
+
+ /** Append one structured-JSON line ({@code level} / {@code message} / {@code params.job_id}) on the default service. */
+ private void put(String group, String stream, long timestampMs, String level, String jobId, String text) {
+ putRaw(service, group, stream, timestampMs, jobLog(level, text, jobId));
+ }
+
+ /** Append one event with a verbatim JSON message to (group, stream) on the given service. */
+ private void putRaw(CloudWatchLogsService svc, String group, String stream, long timestampMs, String message) {
+ Map<String, Object> event = new LinkedHashMap<>();
+ event.put("timestamp", timestampMs);
+ event.put("message", message);
+ svc.putLogEvents(group, stream, List.of(event), REGION);
+ }
+
+ private static String jobLog(String level, String text, String jobId) {
+ return String.format(
+ "{\"level\":\"%s\",\"message\":\"%s\",\"params\":{\"job_id\":\"%s\"}}",
+ level, text, jobId);
+ }
+
+ private static String idLog(String id, String text) {
+ return String.format(
+ "{\"level\":\"INFO\",\"message\":\"%s\",\"params\":{\"id\":\"%s\"}}",
+ text, id);
+ }
+
+ private static String hostLog(String host, String text) {
+ return String.format(
+ "{\"level\":\"INFO\",\"message\":\"%s\",\"params\":{\"host\":\"%s\"}}",
+ text, host);
+ }
+
+ private static String artifactLog(String jobId, String group, String artifact, String version) {
+ return String.format(
+ "{\"level\":\"INFO\",\"message\":\"published\",\"params\":{\"job_id\":\"%s\","
+ + "\"artifact_coordinates\":{\"group\":\"%s\",\"artifact\":\"%s\",\"version\":\"%s\"}}}",
+ jobId, group, artifact, version);
+ }
+}