Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudwatch): record alarm history and serve DescribeAlarmHistory (#6670)

Mario Toffia989f714c21eb
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchTest.java
index 66dc0e9d56..a82025bb52 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchTest.java
@@ -6,6 +6,7 @@ import software.amazon.awssdk.services.cloudwatch.model.*;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
+import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.*;
@@ -249,4 +250,50 @@ class CloudWatchTest {
assertThat(cloudWatchClient.listMetrics(request -> request.namespace(namespace)).metrics()).isEmpty();
}
+
+ @Test
+ @DisplayName("DescribeAlarmHistory lists state transitions newest first and pages")
+ void testDescribeAlarmHistory() {
+ String alarmName = "java-history-" + System.currentTimeMillis();
+ cloudWatchClient.putMetricAlarm(request -> request
+ .alarmName(alarmName)
+ .metricName("Depth")
+ .namespace("JavaTestHistory")
+ .statistic(Statistic.MAXIMUM)
+ .period(60)
+ .evaluationPeriods(1)
+ .threshold(1.0)
+ .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD)
+ .treatMissingData("ignore"));
+ try {
+ for (StateValue state : List.of(StateValue.OK, StateValue.ALARM, StateValue.OK)) {
+ cloudWatchClient.setAlarmState(request -> request
+ .alarmName(alarmName).stateValue(state).stateReason("manual"));
+ }
+
+ DescribeAlarmHistoryResponse history = cloudWatchClient.describeAlarmHistory(request -> request
+ .alarmName(alarmName)
+ .historyItemType(HistoryItemType.STATE_UPDATE));
+ assertThat(history.alarmHistoryItems())
+ .extracting(AlarmHistoryItem::historySummary)
+ .containsExactly("Alarm updated from ALARM to OK", "Alarm updated from OK to ALARM",
+ "Alarm updated from INSUFFICIENT_DATA to OK");
+ assertThat(history.alarmHistoryItems().get(0).alarmType()).isEqualTo(AlarmType.METRIC_ALARM);
+ assertThat(history.alarmHistoryItems().get(0).timestamp())
+ .isAfter(Instant.now().minus(5, ChronoUnit.MINUTES));
+
+ DescribeAlarmHistoryResponse page = cloudWatchClient.describeAlarmHistory(request -> request
+ .alarmName(alarmName).maxRecords(1));
+ assertThat(page.alarmHistoryItems()).hasSize(1);
+ assertThat(page.nextToken()).isNotBlank();
+
+ assertThatThrownBy(() -> cloudWatchClient.describeAlarmHistory(request -> request
+ .startDate(Instant.parse("2026-10-26T16:21:49.900Z"))
+ .endDate(Instant.parse("2026-10-26T16:21:49.500Z"))))
+ .isInstanceOf(InvalidParameterValueException.class)
+ .hasMessageContaining("must be before end date");
+ } finally {
+ cloudWatchClient.deleteAlarms(request -> request.alarmNames(alarmName));
+ }
+ }
}
diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md
index e8a8053fdf..3090fd943b 100644
--- a/docs/services/cloudwatch.md
+++ b/docs/services/cloudwatch.md
@@ -404,6 +404,7 @@ returns HTTP 404.
| `DescribeAlarms` | List alarms |
| `DeleteAlarms` | Delete alarms |
| `SetAlarmState` | Manually set alarm state |
+| `DescribeAlarmHistory` | List alarm state transitions and configuration changes (see [Alarm history](#alarm-history)) |
| `PutMetricStream` | Create or update a metric stream definition |
| `GetMetricStream` | Read a metric stream definition |
| `ListMetricStreams` | List metric streams |
@@ -460,6 +461,27 @@ metric does not retain the previous definition.
This is management-plane support: the alarm evaluator currently evaluates only single-metric
alarms, not metric-math expressions. `SetAlarmState` remains available for manual transitions.
+### Alarm history {#alarm-history}
+
+`DescribeAlarmHistory` lists two kinds of items, newest first unless `ScanBy` is
+`TimestampAscending`:
+
+- `StateUpdate` for every real state transition, whether it comes from `SetAlarmState`, the alarm
+ evaluator or a composite alarm's rule. Setting an alarm to the state it already has records
+ nothing. `HistoryData` carries the old and new state with their reasons and reason data.
+- `ConfigurationUpdate` when `PutMetricAlarm` or `PutCompositeAlarm` creates or updates an alarm,
+ and when `DeleteAlarms` deletes one. An update lists the previous value of each changed field
+ under `originalUpdatedFields`.
+
+History survives the deletion of its alarm and is kept for 30 days. Without `AlarmTypes` only
+metric alarm history is listed; request `CompositeAlarm` to include composite alarms. `Action`,
+`AlarmContributorStateUpdate` and `AlarmContributorAction` are accepted filters, but Floci never
+records those items, so they match nothing. `MaxRecords` defaults to 50, and a `NextToken` issued
+for the other `ScanBy` direction returns an empty page, as on AWS.
+
+The alarm snapshots in `ConfigurationUpdate` items use Floci's field names, such as `okActions`
+and `statistic`, where AWS uses its internal ones, such as `okactions` and `extendedStatistic`.
+
### Examples
```bash
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/AlarmSnsNotifier.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/AlarmSnsNotifier.java
index a13d837bdd..0de12fe787 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/AlarmSnsNotifier.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/AlarmSnsNotifier.java
@@ -24,7 +24,7 @@ import java.util.Map;
public class AlarmSnsNotifier {
private static final Logger LOG = Logger.getLogger(AlarmSnsNotifier.class);
- private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter
+ static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ROOT).withZone(ZoneOffset.UTC);
private final SnsService snsService;
private final ObjectMapper objectMapper;
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsException.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsException.java
index 1ea39ed4e0..cce01a2877 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsException.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsException.java
@@ -27,6 +27,10 @@ class CloudWatchMetricsException extends AwsException {
"The parameter " + parameter + " is required.", 400);
}
+ static CloudWatchMetricsException invalidParameterValue(String message) {
+ return new CloudWatchMetricsException("InvalidParameterValue", "InvalidParameterValueException", message, 400);
+ }
+
@Override
public String jsonType() {
return jsonType;
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java
index c56f8df244..1f345fa7b8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java
@@ -7,9 +7,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
@@ -24,6 +26,7 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
+import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -80,6 +83,7 @@ public class CloudWatchMetricsJsonHandler {
case "DescribeAlarms" -> handleDescribeAlarms(request, region);
case "DeleteAlarms" -> handleDeleteAlarms(request, region);
case "SetAlarmState" -> handleSetAlarmState(request, region);
+ case "DescribeAlarmHistory" -> handleDescribeAlarmHistory(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
case "TagResource" -> handleTagResource(request, region);
case "UntagResource" -> handleUntagResource(request, region);
@@ -406,6 +410,31 @@ public class CloudWatchMetricsJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
+ private Response handleDescribeAlarmHistory(JsonNode request, String region) {
+ List<String> types = new ArrayList<>();
+ request.path("AlarmTypes").forEach(value -> types.add(value.asText()));
+ PaginatedResult<AlarmHistoryItem> page = metricsService.describeAlarmHistory(
+ request.path("AlarmName").asText(null), types, request.path("HistoryItemType").asText(null),
+ parseInstantNode(request.path("StartDate")), parseInstantNode(request.path("EndDate")),
+ Pagination.parseMaxResults(request, "MaxRecords", "MalformedInput"),
+ request.path("NextToken").asText(null), request.path("ScanBy").asText(null), region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode items = response.putArray("AlarmHistoryItems");
+ for (AlarmHistoryItem item : page.items()) {
+ items.addObject()
+ .put("AlarmName", item.alarmName())
+ .put("AlarmType", item.alarmType())
+ .put("HistoryData", item.historyData())
+ .put("HistoryItemType", item.historyItemType())
+ .put("HistorySummary", item.historySummary())
+ .put("Timestamp", item.timestamp() / 1000.0);
+ }
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
private Response handleListTagsForResource(JsonNode request, String region) {
String arn = request.has("ResourceARN") ? request.path("ResourceARN").asText() : request.path("ResourceArn").asText();
if (arn.isEmpty()) arn = request.path("resourceArn").asText();
@@ -781,7 +810,9 @@ public class CloudWatchMetricsJsonHandler {
private Instant parseInstantNode(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) return null;
if (node.isNumber()) {
- return Instant.ofEpochSecond(node.asLong());
+ BigDecimal seconds = node.decimalValue();
+ return Instant.ofEpochSecond(seconds.longValue(),
+ seconds.remainder(BigDecimal.ONE).movePointRight(9).longValue());
}
return parseInstant(node.asText(null));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java
index 0d93ae4a6c..5d49388c6f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
@@ -66,6 +67,7 @@ public class CloudWatchMetricsQueryHandler {
case "DescribeAlarms" -> handleDescribeAlarms(params, region);
case "DeleteAlarms" -> handleDeleteAlarms(params, region);
case "SetAlarmState" -> handleSetAlarmState(params, region);
+ case "DescribeAlarmHistory" -> handleDescribeAlarmHistory(params, region);
case "ListTagsForResource" -> handleListTagsForResource(params, region);
case "TagResource" -> handleTagResource(params, region);
case "UntagResource" -> handleUntagResource(params, region);
@@ -319,6 +321,30 @@ public class CloudWatchMetricsQueryHandler {
return Response.ok(AwsQueryResponse.envelopeNoResult("SetAlarmState", null)).build();
}
+ private Response handleDescribeAlarmHistory(MultivaluedMap<String, String> params, String region) {
+ PaginatedResult<AlarmHistoryItem> page = metricsService.describeAlarmHistory(params.getFirst("AlarmName"),
+ alarmMembers(params, "AlarmTypes"), params.getFirst("HistoryItemType"),
+ parseInstant(params.getFirst("StartDate")), parseInstant(params.getFirst("EndDate")),
+ Pagination.parseMaxResults(params.getFirst("MaxRecords"), "MalformedInput"),
+ params.getFirst("NextToken"), params.getFirst("ScanBy"), region);
+ XmlBuilder xml = new XmlBuilder().start("AlarmHistoryItems");
+ for (AlarmHistoryItem item : page.items()) {
+ xml.start("member")
+ .elem("AlarmName", item.alarmName())
+ .elem("AlarmType", item.alarmType())
+ .elem("HistoryData", item.historyData())
+ .elem("HistoryItemType", item.historyItemType())
+ .elem("HistorySummary", item.historySummary())
+ .elem("Timestamp", Instant.ofEpochMilli(item.timestamp()).toString())
+ .end("member");
+ }
+ xml.end("AlarmHistoryItems");
+ if (page.nextToken() != null) {
+ xml.elem("NextToken", page.nextToken());
+ }
+ return Response.ok(AwsQueryResponse.envelope("DescribeAlarmHistory", AwsNamespaces.CW, xml.build())).build();
+ }
+
private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {
String arn = params.getFirst("ResourceARN");
Map<String, String> tags;
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java
index 7874fad726..4b4becea9f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java
@@ -1,15 +1,27 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.NullNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.storage.WriteProfile;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
@@ -18,7 +30,10 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.time.Duration;
import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
@@ -26,12 +41,16 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
@ApplicationScoped
public class CloudWatchMetricsService {
@@ -39,11 +58,25 @@ public class CloudWatchMetricsService {
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsService.class);
private static final List<String> ALARM_TYPES = List.of("CompositeAlarm", "MetricAlarm", "LogAlarm");
+ private static final List<String> HISTORY_ALARM_TYPES = List.of("MetricAlarm", "CompositeAlarm");
+ private static final List<String> HISTORY_ITEM_TYPES = List.of("AlarmContributorAction",
+ "AlarmContributorStateUpdate", "Action", "StateUpdate", "ConfigurationUpdate");
+ private static final List<String> SCAN_BY = List.of("TimestampAscending", "TimestampDescending");
+ private static final Duration HISTORY_RETENTION = Duration.ofDays(30);
+ /** The form of {@code java.util.Date#toString} in UTC, which AWS's date range error prints. */
+ private static final DateTimeFormatter HISTORY_DATE_FORMAT = DateTimeFormatter
+ .ofPattern("EEE MMM dd HH:mm:ss 'UTC' yyyy", Locale.ROOT).withZone(ZoneOffset.UTC);
+ private static final ObjectMapper MAPPER = new ObjectMapper()
+ .setSerializationInclusion(JsonInclude.Include.NON_NULL)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
private final StorageBackend<String, MetricDatum> metricStore;
private final StorageBackend<String, Alarm> alarmStore;
+ private final StorageBackend<String, AlarmHistoryItem> historyStore;
private final RegionResolver regionResolver;
private final AlarmSnsNotifier alarmSnsNotifier;
+ private long lastHistorySequence;
+ private Instant nextHistoryPrune = Instant.MIN;
public CloudWatchMetricsService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory, regionResolver, null);
@@ -58,6 +91,8 @@ public class CloudWatchMetricsService {
new TypeReference<Map<String, MetricDatum>>() {}, WriteProfile.APPEND_HEAVY);
this.alarmStore = storageFactory.create("cloudwatchmetrics", "cwalarms.json",
new TypeReference<Map<String, Alarm>>() {});
+ this.historyStore = storageFactory.create("cloudwatchmetrics", "cwalarmhistory.json",
+ new TypeReference<Map<String, AlarmHistoryItem>>() {}, WriteProfile.APPEND_HEAVY);
this.regionResolver = regionResolver;
this.alarmSnsNotifier = alarmSnsNotifier;
}
@@ -71,8 +106,16 @@ public class CloudWatchMetricsService {
CloudWatchMetricsService(StorageBackend<String, MetricDatum> metricStore,
StorageBackend<String, Alarm> alarmStore,
RegionResolver regionResolver, AlarmSnsNotifier alarmSnsNotifier) {
+ this(metricStore, alarmStore, new InMemoryStorage<>(), regionResolver, alarmSnsNotifier);
+ }
+
+ CloudWatchMetricsService(StorageBackend<String, MetricDatum> metricStore,
+ StorageBackend<String, Alarm> alarmStore,
+ StorageBackend<String, AlarmHistoryItem> historyStore,
+ RegionResolver regionResolver, AlarmSnsNotifier alarmSnsNotifier) {
this.metricStore = metricStore;
this.alarmStore = alarmStore;
+ this.historyStore = historyStore;
this.regionResolver = regionResolver;
this.alarmSnsNotifier = alarmSnsNotifier;
}
@@ -151,13 +194,16 @@ public class CloudWatchMetricsService {
*/
public void deleteMetricDataBefore(String namespace, Instant cutoff) {
long cutoffSeconds = cutoff.getEpochSecond();
- Predicate<MetricDatum> expired = d -> namespace.equals(d.getNamespace()) && d.getTimestamp() < cutoffSeconds;
- if (metricStore instanceof AccountAwareStorageBackend<MetricDatum> aware) {
+ deleteInEveryAccount(metricStore, d -> namespace.equals(d.getNamespace()) && d.getTimestamp() < cutoffSeconds);
+ }
+
+ private static <V> void deleteInEveryAccount(StorageBackend<String, V> store, Predicate<V> expired) {
+ if (store instanceof AccountAwareStorageBackend<V> aware) {
aware.deleteAllAccountsMatching(expired);
return;
}
- for (String key : List.copyOf(metricStore.keys())) {
- metricStore.get(key).filter(expired).ifPresent(ignored -> metricStore.delete(key));
+ for (String key : List.copyOf(store.keys())) {
+ store.get(key).filter(expired).ifPresent(ignored -> store.delete(key));
}
}
@@ -378,6 +424,7 @@ public class CloudWatchMetricsService {
throw SmithyValidationErrors.validationError(violation);
}
Alarm previous = alarmStore.get(region + "::" + name).orElse(null);
+ ObjectNode before = previous == null ? null : snapshot(previous);
if (previous != null) {
if (!previous.getClass().equals(alarm.getClass())) {
throw new AwsException("ValidationError", "An alarm of another type already has this name", 400);
@@ -394,9 +441,38 @@ public class CloudWatchMetricsService {
alarm.setRegion(region);
alarm.setAlarmConfigurationUpdatedTimestamp(Instant.now().getEpochSecond());
alarmStore.put(region + "::" + name, alarm);
+ ObjectNode after = snapshot(alarm);
+ ObjectNode data = MAPPER.createObjectNode().put("version", "1.0");
+ if (before == null) {
+ data.put("type", "Create").set("createdAlarm", after);
+ recordHistory(alarm, region, "ConfigurationUpdate", "Alarm \"" + name + "\" created", data);
+ } else {
+ data.put("type", "Update").set("updatedAlarm", after);
+ ObjectNode original = data.putObject("originalUpdatedFields");
+ Set<String> fields = new LinkedHashSet<>();
+ before.fieldNames().forEachRemaining(fields::add);
+ after.fieldNames().forEachRemaining(fields::add);
+ for (String field : fields) {
+ if (!Objects.equals(before.get(field), after.get(field))) {
+ original.set(field, before.has(field) ? before.get(field) : NullNode.getInstance());
+ }
+ }
+ recordHistory(alarm, region, "ConfigurationUpdate", "Alarm \"" + name + "\" updated", data);
+ }
LOG.infov("Put {0}: {1} in {2}", alarm.getClass().getSimpleName(), name, region);
}
+ /** The alarm as history items show it: AWS's timestamp strings, without state reasons, tags or Floci's bookkeeping. */
+ private static ObjectNode snapshot(Alarm alarm) {
+ ObjectNode node = MAPPER.valueToTree(alarm);
+ node.remove(List.of("region", "tags", "stateReason", "stateReasonData", "alarmType"));
+ node.put("alarmConfigurationUpdatedTimestamp", AlarmSnsNotifier.TIMESTAMP_FORMAT.format(
+ Instant.ofEpochSecond(alarm.getAlarmConfigurationUpdatedTimestamp())));
+ node.put("stateUpdatedTimestamp", AlarmSnsNotifier.TIMESTAMP_FORMAT.format(
+ Instant.ofEpochSecond(alarm.getStateUpdatedTimestamp())));
+ return node;
+ }
+
/** Metric alarms evaluated by the existing metric evaluator. */
public List<MetricAlarm> allAlarms() {
return alarmStore.scan(k -> true).stream().filter(MetricAlarm.class::isInstance)
@@ -493,11 +569,7 @@ public class CloudWatchMetricsService {
});
String state = triggered ? "ALARM" : "OK";
if (!state.equals(alarm.getStateValue())) {
- alarm.setStateValue(state);
- alarm.setStateReason("AlarmRule evaluated to " + state);
- alarm.setStateReasonData(null);
- alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
- alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
+ changeState(alarm, region, state, "AlarmRule evaluated to " + state, null);
changed.add(alarm.getAlarmName());
changed.add(alarm.getAlarmArn());
}
@@ -523,8 +595,12 @@ public class CloudWatchMetricsService {
}
Set<String> deletedNames = new HashSet<>();
for (String name : alarmNames) {
- if (alarmStore.get(region + "::" + name).isPresent()) {
+ Alarm existing = alarmStore.get(region + "::" + name).orElse(null);
+ if (existing != null) {
deletedNames.add(name);
+ ObjectNode data = MAPPER.createObjectNode().put("version", "1.0").put("type", "Delete");
+ data.set("deletedAlarm", snapshot(existing));
+ recordHistory(existing, region, "ConfigurationUpdate", "Alarm \"" + name + "\" deleted", data);
}
alarmStore.delete(region + "::" + name);
}
@@ -579,12 +655,7 @@ public class CloudWatchMetricsService {
.orElseThrow(() -> new AwsException("ResourceNotFound", "Alarm not found: " + alarmName, 404));
String oldState = alarm.getStateValue();
- alarm.setStateValue(stateValue);
- alarm.setStateReason(stateReason);
- alarm.setStateReasonData(stateReasonData);
- alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
-
- alarmStore.put(key, alarm);
+ changeState(alarm, region, stateValue, stateReason, stateReasonData);
evaluateComposites(region, Set.of(alarmName), null);
LOG.infov("SetAlarmState: {0} -> {1}", alarmName, stateValue);
if (alarmSnsNotifier != null && alarm instanceof MetricAlarm metricAlarm) {
@@ -596,6 +667,99 @@ public class CloudWatchMetricsService {
}
}
+ private void changeState(Alarm alarm, String region, String state, String reason, String reasonData) {
+ String oldState = alarm.getStateValue();
+ ObjectNode data = MAPPER.createObjectNode().put("version", "1.0");
+ data.set("oldState", stateNode(oldState, alarm.getStateReason(), alarm.getStateReasonData()));
+ data.set("newState", stateNode(state, reason, reasonData));
+ alarm.setStateValue(state);
+ alarm.setStateReason(reason);
+ alarm.setStateReasonData(reasonData);
+ alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
+ alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
+ if (!state.equals(oldState)) {
+ recordHistory(alarm, region, "StateUpdate", "Alarm updated from " + oldState + " to " + state, data);
+ }
+ }
+
+ private static ObjectNode stateNode(String value, String reason, String reasonData) {
+ ObjectNode node = MAPPER.createObjectNode().put("stateValue", value).put("stateReason", reason);
+ if (reasonData != null) {
+ JsonNode parsed;
+ try {
+ parsed = MAPPER.readTree(reasonData);
+ } catch (JsonProcessingException ignored) {
+ // SetAlarmState does not require JSON here, so text that is not JSON is kept as a string.
+ parsed = null;
+ }
+ node.set("stateReasonData", parsed == null || parsed.isMissingNode() ? TextNode.valueOf(reasonData) : parsed);
+ }
+ return node;
+ }
+
+ /** Called only under this service's monitor, which also guards the sequence and the prune deadline. */
+ private void recordHistory(Alarm alarm, String region, String type, String summary, ObjectNode data) {
+ Instant now = Instant.now();
+ if (!now.isBefore(nextHistoryPrune)) {
+ long cutoffMillis = now.minus(HISTORY_RETENTION).toEpochMilli();
+ deleteInEveryAccount(historyStore, item -> item.timestamp() < cutoffMillis);
+ nextHistoryPrune = now.plus(Duration.ofHours(1));
+ }
+ lastHistorySequence = Math.max(epochMicros(now), lastHistorySequence + 1);
+ historyStore.put(region + "::" + String.format("%020d", lastHistorySequence),
+ new AlarmHistoryItem(lastHistorySequence, alarm.getAlarmName(), alarm.getAlarmType(),
+ now.toEpochMilli(), type, summary, data.toString()));
+ }
+
+ private static long epochMicros(Instant instant) {
+ return instant.getEpochSecond() * 1_000_000 + instant.getNano() / 1_000;
+ }
+
+ public synchronized PaginatedResult<AlarmHistoryItem> describeAlarmHistory(String alarmName, List<String> alarmTypes,
+ String historyItemType, Instant startDate, Instant endDate, Integer maxRecords, String nextToken,
+ String scanBy, String region) {
+ List<String> violations = Stream.of(
+ alarmName == null ? null : SmithyValidationErrors.lengthOutOfRange("alarmName", alarmName, 1, 255),
+ alarmTypes == null || HISTORY_ALARM_TYPES.containsAll(alarmTypes) ? null
+ : SmithyValidationErrors.notAllInEnum(alarmTypes, "alarmTypes", HISTORY_ALARM_TYPES),
+ historyItemType == null || HISTORY_ITEM_TYPES.contains(historyItemType) ? null
+ : SmithyValidationErrors.notInEnum(historyItemType, "historyItemType", HISTORY_ITEM_TYPES),
+ maxRecords == null ? null : SmithyValidationErrors.outOfRange("maxRecords", maxRecords, 1, 100),
+ scanBy == null || SCAN_BY.contains(scanBy) ? null
+ : SmithyValidationErrors.notInEnum(scanBy, "scanBy", SCAN_BY))
+ .filter(Objects::nonNull).toList();
+ if (!violations.isEmpty()) {
+ throw SmithyValidationErrors.validationError(violations);
+ }
+ if (alarmName == null && historyItemType != null && historyItemType.startsWith("AlarmContributor")) {
+ throw new AwsException("ValidationError",
+ "Alarm name must be provided to query history for alarm contributors.", 400);
+ }
+ if (startDate != null && endDate != null && startDate.toEpochMilli() > endDate.toEpochMilli()) {
+ throw CloudWatchMetricsException.invalidParameterValue("Start date " + HISTORY_DATE_FORMAT.format(startDate)
+ + " must be before end date " + HISTORY_DATE_FORMAT.format(endDate));
+ }
+ boolean ascending = "TimestampAscending".equals(scanBy);
+ if (nextToken != null && Pagination.tokenStartsWith(nextToken,
+ (ascending ? "alarm-history-desc" : "alarm-history-asc") + ":")) {
+ return new PaginatedResult<>(List.of(), null);
+ }
+ List<String> types = alarmTypes == null || alarmTypes.isEmpty() ? List.of("MetricAlarm") : alarmTypes;
+ long retained = Instant.now().minus(HISTORY_RETENTION).toEpochMilli();
+ long start = startDate == null ? retained : Math.max(retained, startDate.toEpochMilli());
+ long end = endDate == null ? Long.MAX_VALUE : endDate.toEpochMilli();
+ List<AlarmHistoryItem> matching = historyStore.scan(k -> k.startsWith(region + "::")).stream()
+ .filter(item -> alarmName == null || alarmName.equals(item.alarmName()))
+ .filter(item -> types.contains(item.alarmType()))
+ .filter(item -> historyItemType == null || historyItemType.equals(item.historyItemType()))
+ .filter(item -> item.timestamp() >= start && item.timestamp() <= end)
+ .toList();
+ return Pagination.paginate(matching,
+ item -> String.format("%020d", ascending ? item.sequence() : Long.MAX_VALUE - item.sequence()),
+ maxRecords == null ? 50 : maxRecords, nextToken, ascending ? "alarm-history-asc" : "alarm-history-desc",
+ token -> new AwsException("InvalidNextToken", "Invalid NextToken : " + token, 400));
+ }
+
/**
* Resolves the alarm an ARN names, or reports that nothing does.
*
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/AlarmHistoryItem.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/AlarmHistoryItem.java
new file mode 100644
index 0000000000..1dea4e8fbd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/AlarmHistoryItem.java
@@ -0,0 +1,8 @@
+package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/** One DescribeAlarmHistory entry; {@code sequence} orders entries and {@code timestamp} is epoch milliseconds. */
+@RegisterForReflection
+public record AlarmHistoryItem(long sequence, String alarmName, String alarmType, long timestamp,
+ String historyItemType, String historySummary, String historyData) {}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterStorageReloadTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterStorageReloadTest.java
index a6baaa9da1..e2f39d9092 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterStorageReloadTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterStorageReloadTest.java
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
-import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
@@ -14,6 +13,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetri
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
+import io.github.hectorvent.floci.testing.StorageFactories;
import jakarta.enterprise.event.Event;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@@ -178,16 +178,10 @@ class CloudWatchLogsMetricFilterStorageReloadTest {
}
private Services open(String mode, String account) {
- EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
- when(config.defaultAccountId()).thenReturn(account);
- when(config.storage().persistentPath()).thenReturn(directory.toString());
- when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
+ EmulatorConfig config = StorageFactories.config(directory, account);
when(config.services().cloudwatchlogs().maxEventsPerQuery()).thenReturn(10_000);
when(config.services().cloudwatchlogs().maxStoredEvents()).thenReturn(10_000);
- ServiceConfigAccess access = mock(ServiceConfigAccess.class);
- when(access.storageMode(anyString())).thenReturn(mode);
- when(access.storageFlushInterval(anyString())).thenReturn(3_600_000L);
- return new Services(new StorageFactory(config, access), config, account);
+ return new Services(StorageFactories.open(config, mode), config, account);
}
private static class Services implements AutoCloseable {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java
new file mode 100644
index 0000000000..635b404f62
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java
@@ -0,0 +1,136 @@
+package io.github.hectorvent.floci.services.cloudwatch.metrics;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.net.URI;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.*;
+
+@QuarkusTest
+class CloudWatchAlarmHistoryIntegrationTest {
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String SCOPE =
+ "AWS4-HMAC-SHA256 Credential=test/20261026/us-east-1/monitoring/aws4_request";
+ private static final String RESULT = "DescribeAlarmHistoryResponse.DescribeAlarmHistoryResult.";
+
+ @TestHTTPResource
+ URI baseUri;
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void bothProtocolsListManualTransitionsNewestFirst(boolean json) throws Exception {
+ String name = "wire-history-" + Long.toString(System.nanoTime(), 36);
+ call(json, "PutMetricAlarm", Map.of("AlarmName", name, "MetricName", "Depth", "Namespace", "Floci/History",
+ "Statistic", "Maximum", "Period", 60, "EvaluationPeriods", 1, "Threshold", 1,
+ "ComparisonOperator", "GreaterThanOrEqualToThreshold", "TreatMissingData", "ignore"))
+ .then().statusCode(200);
+ for (String state : List.of("OK", "ALARM", "OK")) {
+ call(json, "SetAlarmState", Map.of("AlarmName", name, "StateValue", state, "StateReason", "manual"))
+ .then().statusCode(200);
+ }
+
+ Response history = call(json, "DescribeAlarmHistory", Map.of("AlarmName", name,
+ "HistoryItemType", "StateUpdate"));
+ history.then().statusCode(200);
+ assertEquals(List.of("Alarm updated from ALARM to OK", "Alarm updated from OK to ALARM",
+ "Alarm updated from INSUFFICIENT_DATA to OK"), json
+ ? history.jsonPath().getList("AlarmHistoryItems.HistorySummary")
+ : history.xmlPath().getList(RESULT + "AlarmHistoryItems.member.HistorySummary"));
+ String type = json ? history.jsonPath().getString("AlarmHistoryItems[0].AlarmType")
+ : history.xmlPath().getString(RESULT + "AlarmHistoryItems.member[0].AlarmType");
+ assertEquals("MetricAlarm", type);
+
+ Response first = call(json, "DescribeAlarmHistory", Map.of("AlarmName", name, "MaxRecords", 1));
+ first.then().statusCode(200);
+ String token = json ? first.jsonPath().getString("NextToken")
+ : first.xmlPath().getString(RESULT + "NextToken");
+ assertFalse(token == null || token.isEmpty());
+ Response second = call(json, "DescribeAlarmHistory", Map.of("AlarmName", name, "MaxRecords", 1,
+ "NextToken", token));
+ assertEquals("Alarm updated from OK to ALARM", json
+ ? second.jsonPath().getString("AlarmHistoryItems[0].HistorySummary")
+ : second.xmlPath().getString(RESULT + "AlarmHistoryItems.member.HistorySummary"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void errorsCarryEachProtocolsCode(boolean json) throws Exception {
+ Instant start = Instant.parse("2026-10-26T16:21:49.900Z");
+ Instant end = Instant.parse("2026-10-26T16:21:49.500Z");
+ Response reversed = call(json, "DescribeAlarmHistory", json
+ ? Map.of("StartDate", start.toEpochMilli() / 1000.0, "EndDate", end.toEpochMilli() / 1000.0)
+ : Map.of("StartDate", start.toString(), "EndDate", end.toString()));
+ reversed.then().statusCode(400);
+ assertEquals(json ? "InvalidParameterValueException" : "InvalidParameterValue", errorCode(json, reversed));
+ assertEquals("Start date Mon Oct 26 16:21:49 UTC 2026 must be before end date Mon Oct 26 16:21:49 UTC 2026",
+ errorMessage(json, reversed));
+
+ Response malformed = call(json, "DescribeAlarmHistory", Map.of("MaxRecords", "abc"));
+ malformed.then().statusCode(400);
+ assertEquals("MalformedInput", errorCode(json, malformed));
+
+ Response token = call(json, "DescribeAlarmHistory", Map.of("NextToken", "bogus"));
+ token.then().statusCode(400);
+ assertEquals("InvalidNextToken", errorCode(json, token));
+ assertEquals("Invalid NextToken : bogus", errorMessage(json, token));
+
+ Response scan = call(json, "DescribeAlarmHistory", Map.of("ScanBy", "Bogus"));
+ scan.then().statusCode(400);
+ assertEquals("1 validation error detected: Value 'Bogus' at 'scanBy' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [TimestampAscending, TimestampDescending]",
+ errorMessage(json, scan));
+ }
+
+ private String errorCode(boolean json, Response response) {
+ return json ? response.jsonPath().getString("__type") : response.xmlPath().getString("ErrorResponse.Error.Code");
+ }
+
+ private String errorMessage(boolean json, Response response) {
+ return json ? response.jsonPath().getString("message") : response.xmlPath().getString("ErrorResponse.Error.Message");
+ }
+
+ private Response call(boolean json, String operation, Map<String, ?> body)
+ throws JsonProcessingException {
+ if ("PutMetricAlarm".equals(operation)) {
+ String name = body.get("AlarmName").toString();
+ cleanup.register(() -> given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0")
+ .header("Authorization", SCOPE)
+ .header("X-Amz-Target", "GraniteServiceVersion20100801.DeleteAlarms")
+ .body(MAPPER.valueToTree(Map.of("AlarmNames", List.of(name))).toString())
+ .post("/").then().statusCode(200));
+ }
+ if (json) {
+ return given().contentType("application/x-amz-json-1.0").header("Authorization", SCOPE)
+ .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation)
+ .body(MAPPER.writeValueAsString(body)).post("/");
+ }
+ Map<String, Object> form = new LinkedHashMap<>();
+ form.put("Action", operation);
+ form.putAll(body);
+ return given().contentType("application/x-www-form-urlencoded").header("Authorization", SCOPE)
+ .formParams(form).post("/");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmHistoryStorageReloadTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmHistoryStorageReloadTest.java
new file mode 100644
index 0000000000..97ce6d8264
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmHistoryStorageReloadTest.java
@@ -0,0 +1,63 @@
+package io.github.hectorvent.floci.services.cloudwatch.metrics;
+
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
+import io.github.hectorvent.floci.testing.StorageFactories;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class CloudWatchAlarmHistoryStorageReloadTest {
+ private static final String ACCOUNT = "111111111111";
+ private static final String REGION = "eu-west-1";
+
+ @TempDir Path directory;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"persistent", "hybrid", "wal"})
+ void historyOfADeletedAlarmSurvivesReloadAndKeepsAppendingAndPaging(String mode) {
+ StorageFactory first = StorageFactories.open(directory, mode, ACCOUNT);
+ MetricAlarm alarm = new MetricAlarm();
+ alarm.setAlarmName("reloaded");
+ List<AlarmHistoryItem> before;
+ try {
+ CloudWatchMetricsService service = new CloudWatchMetricsService(first, new RegionResolver(REGION, ACCOUNT));
+ service.putMetricAlarm(alarm, REGION);
+ service.setAlarmState("reloaded", "ALARM", "breached", "{\"x\":1}", REGION);
+ service.deleteAlarms(List.of("reloaded"), REGION);
+ before = service.describeAlarmHistory("reloaded", null, null, null, null, null, null, null, REGION).items();
+ } finally {
+ first.shutdownAll();
+ }
+ assertEquals(3, before.size());
+
+ StorageFactory second = StorageFactories.open(directory, mode, ACCOUNT);
+ List<AlarmHistoryItem> pages = new ArrayList<>();
+ try {
+ CloudWatchMetricsService service = new CloudWatchMetricsService(second, new RegionResolver(REGION, ACCOUNT));
+ service.putMetricAlarm(alarm, REGION);
+ String token = null;
+ do {
+ PaginatedResult<AlarmHistoryItem> page = service.describeAlarmHistory(
+ "reloaded", null, null, null, null, 2, token, null, REGION);
+ pages.addAll(page.items());
+ token = page.nextToken();
+ } while (token != null);
+ } finally {
+ second.shutdownAll();
+ }
+
+ assertEquals(4, pages.size());
+ assertEquals("Alarm \"reloaded\" created", pages.getFirst().historySummary());
+ assertEquals(before, pages.subList(1, 4));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java
index 06122379e4..05c43681fa 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java
@@ -1,13 +1,21 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
+import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+import java.time.Duration;
+import java.time.Instant;
import java.util.List;
import java.util.Map;
@@ -42,4 +50,66 @@ class CloudWatchAlarmQueryHandlerTest {
assertEquals(List.of("missing-action"), alarm.getInsufficientDataActions());
assertEquals(Map.of("team", "metrics"), alarm.getTags());
}
+
+ @Test
+ void describeAlarmHistoryRendersXmlItemsAndPages() throws Exception {
+ String region = "us-east-1";
+ CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
+ CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null);
+ MultivaluedMap<String, String> put = new MultivaluedHashMap<>();
+ put.putSingle("AlarmName", "query-history");
+ handler.handle("PutMetricAlarm", put, region);
+ for (String state : List.of("OK", "ALARM")) {
+ MultivaluedMap<String, String> set = new MultivaluedHashMap<>();
+ set.putSingle("AlarmName", "query-history");
+ set.putSingle("StateValue", state);
+ set.putSingle("StateReason", "manual");
+ handler.handle("SetAlarmState", set, region);
+ }
+ MultivaluedMap<String, String> request = new MultivaluedHashMap<>();
+ request.putSingle("AlarmName", "query-history");
+ request.putSingle("AlarmTypes.member.1", "MetricAlarm");
+ request.putSingle("HistoryItemType", "StateUpdate");
+ request.putSingle("MaxRecords", "1");
+
+ Document first = XmlParser.parseDocument((String) handler.handle("DescribeAlarmHistory", request, region)
+ .getEntity());
+ assertEquals(AwsNamespaces.CW, first.getDocumentElement().getNamespaceURI());
+ assertEquals("DescribeAlarmHistoryResponse", first.getDocumentElement().getLocalName());
+ assertEquals(1, elements(first, "AlarmHistoryItems").getLength());
+ assertEquals(1, elements(first, "member").getLength());
+ assertEquals("query-history", text(first, "AlarmName"));
+ assertEquals("MetricAlarm", text(first, "AlarmType"));
+ assertEquals("StateUpdate", text(first, "HistoryItemType"));
+ assertEquals("Alarm updated from OK to ALARM", text(first, "HistorySummary"));
+ assertTrue(text(first, "HistoryData").startsWith("{\"version\":\"1.0\""));
+ Instant timestamp = Instant.parse(text(first, "Timestamp"));
+ assertTrue(Duration.between(timestamp, Instant.now()).abs().toSeconds() < 60);
+ String token = text(first, "NextToken");
+ assertFalse(token.isEmpty());
+
+ request.putSingle("NextToken", token);
+ Document last = XmlParser.parseDocument((String) handler.handle("DescribeAlarmHistory", request, region)
+ .getEntity());
+ assertEquals("Alarm updated from INSUFFICIENT_DATA to OK", text(last, "HistorySummary"));
+ assertEquals(0, elements(last, "NextToken").getLength());
+
+ MultivaluedMap<String, String> reversed = new MultivaluedHashMap<>();
+ reversed.putSingle("StartDate", "2026-10-26T16:23:10Z");
+ reversed.putSingle("EndDate", "2026-10-26T16:22:10Z");
+ AwsException error = assertThrows(AwsException.class,
+ () -> handler.handle("DescribeAlarmHistory", reversed, region));
+ assertEquals("InvalidParameterValue", error.getErrorCode());
+ assertEquals("Start date Mon Oct 26 16:23:10 UTC 2026 must be before end date Mon Oct 26 16:22:10 UTC 2026",
+ error.getMessage());
+ }
+
+ private static NodeList elements(Document document, String name) {
+ return document.getElementsByTagNameNS(AwsNamespaces.CW, name);
+ }
+
+ private static String text(Document document, String name) {
+ return elements(document, name).item(0).getTextContent();
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java
index b2565d226b..594486a72f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java
@@ -456,4 +456,63 @@ class CloudWatchMetricsJsonHandlerTest {
assertTrue(body.get("MetricDataResults").get(0).get("Values").size() > 0,
"an explicit JSON null Unit must not filter every datapoint out");
}
+
+ @Test
+ void describeAlarmHistoryReturnsAwsShapedItemsAndPages() {
+ handler.handle("PutMetricAlarm", MAPPER.createObjectNode().put("AlarmName", "json-history"), REGION);
+ for (String state : List.of("OK", "ALARM", "OK")) {
+ handler.handle("SetAlarmState", MAPPER.createObjectNode().put("AlarmName", "json-history")
+ .put("StateValue", state).put("StateReason", "manual"), REGION);
+ }
+ ObjectNode request = MAPPER.createObjectNode().put("AlarmName", "json-history")
+ .put("HistoryItemType", "StateUpdate").put("MaxRecords", 2);
+ request.putArray("AlarmTypes").add("MetricAlarm");
+
+ Response response = handler.handle("DescribeAlarmHistory", request, REGION);
+ assertEquals(200, response.getStatus());
+ ObjectNode body = (ObjectNode) response.getEntity();
+ JsonNode items = body.get("AlarmHistoryItems");
+ assertEquals(2, items.size());
+ JsonNode newest = items.get(0);
+ List<String> fields = new ArrayList<>();
+ newest.fieldNames().forEachRemaining(fields::add);
+ assertEquals(List.of("AlarmName", "AlarmType", "HistoryData", "HistoryItemType", "HistorySummary", "Timestamp"),
+ fields);
+ assertEquals("json-history", newest.get("AlarmName").asText());
+ assertEquals("MetricAlarm", newest.get("AlarmType").asText());
+ assertEquals("StateUpdate", newest.get("HistoryItemType").asText());
+ assertEquals("Alarm updated from ALARM to OK", newest.get("HistorySummary").asText());
+ assertTrue(newest.get("HistoryData").asText().startsWith("{\"version\":\"1.0\",\"oldState\""));
+ assertTrue(newest.get("Timestamp").isDouble());
+ assertTrue(Math.abs(newest.get("Timestamp").asDouble() - Instant.now().getEpochSecond()) < 60);
+ assertTrue(body.get("NextToken").isTextual());
+
+ request.put("NextToken", body.get("NextToken").asText());
+ ObjectNode last = (ObjectNode) handler.handle("DescribeAlarmHistory", request, REGION).getEntity();
+ assertEquals("Alarm updated from INSUFFICIENT_DATA to OK",
+ last.get("AlarmHistoryItems").get(0).get("HistorySummary").asText());
+ assertFalse(last.has("NextToken"));
+
+ ObjectNode future = MAPPER.createObjectNode().put("AlarmName", "json-history")
+ .put("StartDate", sdkTimestamp(Instant.now().plusSeconds(3600)));
+ assertEquals(0, ((ObjectNode) handler.handle("DescribeAlarmHistory", future, REGION).getEntity())
+ .get("AlarmHistoryItems").size());
+
+ ObjectNode distant = MAPPER.createObjectNode().put("AlarmName", "json-history")
+ .put("HistoryItemType", "StateUpdate").put("EndDate", 253402300799L);
+ assertEquals(3, ((ObjectNode) handler.handle("DescribeAlarmHistory", distant, REGION).getEntity())
+ .get("AlarmHistoryItems").size(), "9999-12-31 is after every item");
+ }
+
+ @Test
+ void describeAlarmHistoryRejectsAStartDateAfterTheEndDate() {
+ ObjectNode request = MAPPER.createObjectNode()
+ .put("StartDate", sdkTimestamp(Instant.parse("2026-10-26T16:23:10Z")))
+ .put("EndDate", sdkTimestamp(Instant.parse("2026-10-26T16:22:10Z")));
+ AwsException e = assertThrows(AwsException.class,
+ () -> handler.handle("DescribeAlarmHistory", request, REGION));
+ assertEquals("InvalidParameterValueException", e.jsonType());
+ assertEquals("Start date Mon Oct 26 16:23:10 UTC 2026 must be before end date Mon Oct 26 16:22:10 UTC 2026",
+ e.getMessage());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java
index f2fd940f7c..6b484f264e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java
@@ -1,9 +1,13 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
@@ -13,7 +17,9 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
+import java.time.Duration;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -24,6 +30,7 @@ class CloudWatchMetricsServiceTest {
private static final String REGION = "us-east-1";
private static final String NAMESPACE = "MyApp/Metrics";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudWatchMetricsService service;
@@ -400,6 +407,299 @@ class CloudWatchMetricsServiceTest {
assertEquals("Threshold breached", updated.getStateReason());
}
+ // ──────────────────────────── Alarm history ────────────────────────────
+
+ @Test
+ void stateTransitionsAreRecordedNewestFirst() {
+ putAlarm("history");
+ service.setAlarmState("history", "OK", "initial", null, REGION);
+ service.setAlarmState("history", "ALARM", "breached", "{\"value\":3}", REGION);
+ service.setAlarmState("history", "OK", "recovered", null, REGION);
+
+ List<AlarmHistoryItem> items = history("history", null, "StateUpdate", null, null, null, null);
+ assertEquals(List.of("Alarm updated from ALARM to OK", "Alarm updated from OK to ALARM",
+ "Alarm updated from INSUFFICIENT_DATA to OK"), summaries(items));
+ assertEquals("MetricAlarm", items.getFirst().alarmType());
+ assertEquals("history", items.getFirst().alarmName());
+ assertEquals("{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"OK\",\"stateReason\":\"initial\"},"
+ + "\"newState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"breached\",\"stateReasonData\":{\"value\":3}}}",
+ items.get(1).historyData());
+ assertEquals("{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"breached\","
+ + "\"stateReasonData\":{\"value\":3}},\"newState\":{\"stateValue\":\"OK\",\"stateReason\":\"recovered\"}}",
+ items.getFirst().historyData());
+ assertTrue(items.get(0).timestamp() >= items.get(1).timestamp());
+ }
+
+ @Test
+ void settingTheCurrentStateRecordsNothingButUpdatesTheReason() {
+ putAlarm("steady");
+ service.setAlarmState("steady", "OK", "first", "not json", REGION);
+ service.setAlarmState("steady", "OK", "again", null, REGION);
+
+ List<AlarmHistoryItem> items = history("steady", null, "StateUpdate", null, null, null, null);
+ assertEquals(1, items.size());
+ assertEquals("{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"INSUFFICIENT_DATA\",\"stateReason\":\"Unchecked\"},"
+ + "\"newState\":{\"stateValue\":\"OK\",\"stateReason\":\"first\",\"stateReasonData\":\"not json\"}}",
+ items.getFirst().historyData());
+ assertEquals("again", service.describeAlarms(List.of("steady"), null, REGION).getFirst().getStateReason());
+ }
+
+ @Test
+ void configurationChangesAreRecordedAndSurviveDeletion() throws Exception {
+ MetricAlarm original = new MetricAlarm();
+ original.setAlarmName("config");
+ original.setAlarmDescription("original");
+ original.setThreshold(1.0);
+ original.setTags(new HashMap<>(Map.of("team", "metrics")));
+ service.putMetricAlarm(original, REGION);
+ String created = AlarmSnsNotifier.TIMESTAMP_FORMAT.format(
+ Instant.ofEpochSecond(original.getAlarmConfigurationUpdatedTimestamp()));
+ MetricAlarm updated = new MetricAlarm();
+ updated.setAlarmName("config");
+ updated.setAlarmDescription("updated");
+ updated.setThreshold(2.0);
+ updated.setUnit("Count");
+ service.putMetricAlarm(updated, REGION);
+ service.deleteAlarms(List.of("config", "never-existed"), REGION);
+
+ assertTrue(service.describeAlarms(List.of("config"), null, REGION).isEmpty());
+ List<AlarmHistoryItem> items = history("config", null, "ConfigurationUpdate", null, null, null, null);
+ assertEquals(List.of("Alarm \"config\" deleted", "Alarm \"config\" updated", "Alarm \"config\" created"),
+ summaries(items));
+ assertTrue(history("never-existed", null, null, null, null, null, null).isEmpty());
+
+ JsonNode create = MAPPER.readTree(items.get(2).historyData());
+ assertEquals("1.0", create.path("version").asText());
+ assertEquals("Create", create.path("type").asText());
+ JsonNode createdAlarm = create.path("createdAlarm");
+ assertEquals("original", createdAlarm.path("alarmDescription").asText());
+ assertEquals(original.getAlarmArn(), createdAlarm.path("alarmArn").asText());
+ assertEquals("INSUFFICIENT_DATA", createdAlarm.path("stateValue").asText());
+ assertEquals(created, createdAlarm.path("alarmConfigurationUpdatedTimestamp").asText());
+ assertTrue(created.endsWith("+0000"));
+ for (String hidden : List.of("region", "tags", "stateReason", "stateReasonData", "alarmType", "unit")) {
+ assertFalse(createdAlarm.has(hidden), hidden);
+ }
+
+ JsonNode update = MAPPER.readTree(items.get(1).historyData());
+ assertEquals("Update", update.path("type").asText());
+ assertEquals(2.0, update.path("updatedAlarm").path("threshold").asDouble());
+ JsonNode originalFields = update.path("originalUpdatedFields");
+ assertEquals("original", originalFields.path("alarmDescription").asText());
+ assertEquals(1.0, originalFields.path("threshold").asDouble());
+ assertTrue(originalFields.path("unit").isNull());
+ assertFalse(originalFields.has("alarmName"));
+ assertFalse(originalFields.has("stateValue"));
+
+ JsonNode delete = MAPPER.readTree(items.getFirst().historyData());
+ assertEquals("Delete", delete.path("type").asText());
+ assertEquals("updated", delete.path("deletedAlarm").path("alarmDescription").asText());
+ }
+
+ @Test
+ void historyFiltersByItemTypeAndScansInEitherDirection() {
+ putAlarm("filtered");
+ service.setAlarmState("filtered", "OK", "initial", null, REGION);
+ service.setAlarmState("filtered", "ALARM", "breached", null, REGION);
+
+ List<String> newestFirst = List.of("Alarm updated from OK to ALARM",
+ "Alarm updated from INSUFFICIENT_DATA to OK", "Alarm \"filtered\" created");
+ assertEquals(newestFirst, summaries(history("filtered", null, null, null, null, null, null)));
+ assertEquals(newestFirst, summaries(history("filtered", List.of("MetricAlarm"), null, null, null, null,
+ "TimestampDescending")));
+ assertEquals(newestFirst.reversed(), summaries(history("filtered", null, null, null, null, null,
+ "TimestampAscending")));
+ assertEquals(List.of("Alarm \"filtered\" created"),
+ summaries(history("filtered", null, "ConfigurationUpdate", null, null, null, null)));
+ for (String neverRecorded : List.of("Action", "AlarmContributorStateUpdate", "AlarmContributorAction")) {
+ assertTrue(history("filtered", null, neverRecorded, null, null, null, null).isEmpty());
+ }
+ assertTrue(history("filtered", List.of("CompositeAlarm"), null, null, null, null, null).isEmpty());
+ assertTrue(service.describeAlarmHistory("filtered", null, null, null, null, null, null, null, "eu-west-1")
+ .items().isEmpty());
+ }
+
+ @Test
+ void historyPagesFollowNextTokenInBothDirections() {
+ putAlarm("paged");
+ for (int i = 0; i < 55; i++) {
+ service.setAlarmState("paged", i % 2 == 0 ? "ALARM" : "OK", "toggle " + i, null, REGION);
+ }
+ PaginatedResult<AlarmHistoryItem> first = service.describeAlarmHistory("paged", null, null, null, null,
+ null, null, null, REGION);
+ assertEquals(50, first.items().size());
+ assertNotNull(first.nextToken());
+
+ for (String scanBy : List.of("TimestampDescending", "TimestampAscending")) {
+ List<AlarmHistoryItem> collected = new ArrayList<>();
+ String token = null;
+ do {
+ PaginatedResult<AlarmHistoryItem> page = service.describeAlarmHistory("paged", null, null, null, null,
+ 7, token, scanBy, REGION);
+ assertTrue(page.items().size() <= 7);
+ collected.addAll(page.items());
+ token = page.nextToken();
+ } while (token != null);
+ List<AlarmHistoryItem> all = history("paged", null, null, null, null, 100, scanBy);
+ assertEquals(56, all.size());
+ assertEquals(all, collected);
+ }
+ assertEquals("Alarm \"paged\" created", history("paged", null, null, null, null, 1, "TimestampAscending")
+ .getFirst().historySummary());
+ }
+
+ @Test
+ void foreignOrInvalidTokensAreHandledLikeAws() {
+ putAlarm("tokens");
+ service.setAlarmState("tokens", "OK", "initial", null, REGION);
+ String descending = service.describeAlarmHistory("tokens", null, null, null, null, 1, null,
+ null, REGION).nextToken();
+ String ascending = service.describeAlarmHistory("tokens", null, null, null, null, 1, null,
+ "TimestampAscending", REGION).nextToken();
+
+ PaginatedResult<AlarmHistoryItem> crossed = service.describeAlarmHistory("tokens", null, null, null, null,
+ 1, descending, "TimestampAscending", REGION);
+ assertTrue(crossed.items().isEmpty());
+ assertNull(crossed.nextToken());
+ assertTrue(service.describeAlarmHistory("tokens", null, null, null, null, 1, ascending, null, REGION)
+ .items().isEmpty());
+
+ AwsException error = assertThrows(AwsException.class, () -> service.describeAlarmHistory("tokens", null,
+ null, null, null, null, "bogus", null, REGION));
+ assertEquals("InvalidNextToken", error.getErrorCode());
+ assertEquals("InvalidNextToken", error.jsonType());
+ assertEquals("Invalid NextToken : bogus", error.getMessage());
+ assertEquals(400, error.getHttpStatus());
+ }
+
+ @Test
+ void historyRequestsAreValidatedWithSmithyMessages() {
+ String prefix = "1 validation error detected: ";
+ assertHistoryRejected(prefix + "Value '0' at 'maxRecords' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 1", null, null, null, 0, null);
+ assertHistoryRejected(prefix + "Value '101' at 'maxRecords' failed to satisfy constraint: "
+ + "Member must have value less than or equal to 100", null, null, null, 101, null);
+ assertHistoryRejected(prefix + "Value 'Bogus' at 'historyItemType' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [AlarmContributorAction, AlarmContributorStateUpdate, Action, "
+ + "StateUpdate, ConfigurationUpdate]", null, null, "Bogus", null, null);
+ assertHistoryRejected(prefix + "Value 'Bogus' at 'scanBy' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [TimestampAscending, TimestampDescending]",
+ null, null, null, null, "Bogus");
+ assertHistoryRejected(prefix + "Value '[Bogus]' at 'alarmTypes' failed to satisfy constraint: "
+ + "Member must satisfy constraint: [Member must satisfy enum value set: [MetricAlarm, CompositeAlarm]]",
+ null, List.of("Bogus"), null, null, null);
+ assertHistoryRejected(prefix + "Value '[LogAlarm]' at 'alarmTypes' failed to satisfy constraint: "
+ + "Member must satisfy constraint: [Member must satisfy enum value set: [MetricAlarm, CompositeAlarm]]",
+ null, List.of("LogAlarm"), null, null, null);
+ assertHistoryRejected(prefix + "Value '' at 'alarmName' failed to satisfy constraint: "
+ + "Member must have length greater than or equal to 1", "", null, null, null, null);
+ assertHistoryRejected("2 validation errors detected: Value '' at 'alarmName' failed to satisfy constraint: "
+ + "Member must have length greater than or equal to 1; Value 'Bogus' at 'scanBy' failed to satisfy "
+ + "constraint: Member must satisfy enum value set: [TimestampAscending, TimestampDescending]",
+ "", null, null, null, "Bogus");
+ assertHistoryRejected("Alarm name must be provided to query history for alarm contributors.",
+ null, null, "AlarmContributorStateUpdate", null, null);
+ assertHistoryRejected("Alarm name must be provided to query history for alarm contributors.",
+ null, null, "AlarmContributorAction", null, null);
+ assertTrue(history("unknown", null, "AlarmContributorStateUpdate", null, null, null, null).isEmpty());
+ }
+
+ private void assertHistoryRejected(String message, String name, List<String> types, String itemType,
+ Integer max, String scanBy) {
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.describeAlarmHistory(name, types, itemType, null, null, max, null, scanBy, REGION));
+ assertEquals("ValidationError", error.getErrorCode());
+ assertEquals(400, error.getHttpStatus());
+ assertEquals(message, error.getMessage());
+ }
+
+ @Test
+ void startDateAfterEndDateIsAnInvalidParameterValue() {
+ AwsException error = assertThrows(AwsException.class, () -> history(null, null, null,
+ Instant.parse("2026-10-26T16:23:10Z"), Instant.parse("2026-10-26T16:22:10Z"), null, null));
+ assertEquals("InvalidParameterValue", error.getErrorCode());
+ assertEquals("InvalidParameterValueException", error.jsonType());
+ assertEquals(400, error.getHttpStatus());
+ assertEquals("Start date Mon Oct 26 16:23:10 UTC 2026 must be before end date Mon Oct 26 16:22:10 UTC 2026",
+ error.getMessage());
+ assertTrue(history(null, null, null, Instant.parse("2026-10-26T16:26:55.549900Z"),
+ Instant.parse("2026-10-26T16:26:55.549100Z"), null, null).isEmpty(), "AWS compares whole milliseconds");
+ }
+
+ @Test
+ void datesFilterRecordedTimestampsAndExpiredHistoryIsDropped() {
+ InMemoryStorage<String, AlarmHistoryItem> store = new InMemoryStorage<>();
+ Instant now = Instant.now();
+ String expiredKey = null;
+ for (int daysAgo : List.of(40, 3, 2, 1)) {
+ Instant at = now.minus(Duration.ofDays(daysAgo));
+ long sequence = at.getEpochSecond() * 1_000_000 + at.getNano() / 1_000;
+ String key = REGION + "::" + String.format("%020d", sequence);
+ store.put(key, new AlarmHistoryItem(sequence, "dated",
+ "MetricAlarm", at.toEpochMilli(), "StateUpdate", daysAgo + " days ago", "{}"));
+ if (daysAgo == 40) {
+ expiredKey = key;
+ }
+ }
+ service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), store,
+ new RegionResolver(REGION, "000000000000"), null);
+
+ assertEquals(List.of("1 days ago", "2 days ago", "3 days ago"),
+ summaries(history("dated", null, null, null, null, null, null)));
+ assertEquals(4, store.keys().size(), "a read hides expired history without deleting it");
+ assertTrue(store.keys().contains(expiredKey));
+ assertEquals(List.of("2 days ago"), summaries(history("dated", null, null,
+ now.minus(Duration.ofDays(2)).minusSeconds(60), now.minus(Duration.ofDays(1)).minusSeconds(60),
+ null, null)));
+ assertEquals(List.of("1 days ago"), summaries(history("dated", null, null,
+ now.minus(Duration.ofDays(1)).minusSeconds(60), null, null, null)));
+ assertEquals(List.of("2 days ago", "3 days ago"), summaries(history("dated", null, null,
+ null, now.minus(Duration.ofDays(2)).plusSeconds(60), null, null)));
+
+ putAlarm("pruner");
+ assertFalse(store.keys().contains(expiredKey), "a write prunes expired history");
+ assertEquals(4, store.keys().size());
+
+ store.put(expiredKey, new AlarmHistoryItem(0, "dated", "MetricAlarm",
+ now.minus(Duration.ofDays(40)).toEpochMilli(), "StateUpdate", "40 days ago", "{}"));
+ putAlarm("within-the-hour");
+ assertTrue(store.keys().contains(expiredKey), "pruning runs at most once an hour");
+ assertEquals(List.of("1 days ago", "2 days ago", "3 days ago"),
+ summaries(history("dated", null, null, null, null, null, null)));
+ }
+
+ @Test
+ void aWriteInOneAccountPrunesExpiredHistoryOfEveryAccount() {
+ InMemoryStorage<String, AlarmHistoryItem> raw = new InMemoryStorage<>();
+ String foreignKey = "111111111111/" + REGION + "::00000000000000000001";
+ raw.put(foreignKey, new AlarmHistoryItem(1, "foreign", "MetricAlarm",
+ Instant.now().minus(Duration.ofDays(40)).toEpochMilli(), "StateUpdate", "expired", "{}"));
+ service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new AccountAwareStorageBackend<>(raw, null, "000000000000"),
+ new RegionResolver(REGION, "000000000000"), null);
+
+ putAlarm("writer");
+
+ assertFalse(raw.keys().contains(foreignKey));
+ assertEquals(1, raw.keys().size());
+ }
+
+ private MetricAlarm putAlarm(String name) {
+ MetricAlarm alarm = new MetricAlarm();
+ alarm.setAlarmName(name);
+ service.putMetricAlarm(alarm, REGION);
+ return alarm;
+ }
+
+ private List<AlarmHistoryItem> history(String name, List<String> types, String itemType,
+ Instant start, Instant end, Integer max, String scanBy) {
+ return service.describeAlarmHistory(name, types, itemType, start, end, max, null, scanBy, REGION).items();
+ }
+
+ private static List<String> summaries(List<AlarmHistoryItem> items) {
+ return items.stream().map(AlarmHistoryItem::historySummary).toList();
+ }
+
@Test
void setAlarmStateOnNonexistentAlarmThrowsResourceNotFound() {
AwsException ex = assertThrows(AwsException.class,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java
index 7f50afc26a..9d03922a23 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java
@@ -1,11 +1,13 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import io.github.hectorvent.floci.testing.ThreadStates;
@@ -292,6 +294,39 @@ class CompositeAlarmServiceTest {
() -> CompositeAlarmRule.parse(null)).getMessage());
}
+ @Test
+ void compositeHistoryIsListedOnlyForTheCompositeAlarmType() {
+ put("aggregate", "TRUE");
+ assertTrue(service.describeAlarmHistory("aggregate", null, null, null, null, null, null, null, REGION)
+ .items().isEmpty());
+ List<AlarmHistoryItem> items = service.describeAlarmHistory("aggregate", List.of("CompositeAlarm"), null,
+ null, null, null, null, null, REGION).items();
+ assertEquals(List.of("Alarm updated from INSUFFICIENT_DATA to ALARM", "Alarm \"aggregate\" created"),
+ items.stream().map(AlarmHistoryItem::historySummary).toList());
+ assertEquals(List.of("CompositeAlarm", "CompositeAlarm"), items.stream().map(AlarmHistoryItem::alarmType).toList());
+ assertEquals(List.of("Alarm \"aggregate\" created", "Alarm updated from INSUFFICIENT_DATA to ALARM"),
+ service.describeAlarmHistory("aggregate", List.of("CompositeAlarm"), null, null, null, null, null,
+ "TimestampAscending", REGION).items().stream().map(AlarmHistoryItem::historySummary).toList());
+ }
+
+ @Test
+ void childTransitionsRecordCompositeStateUpdates() throws Exception {
+ MetricAlarm metric = new MetricAlarm();
+ metric.setAlarmName("child");
+ service.putMetricAlarm(metric, REGION);
+ put("parent", "ALARM(child)");
+ service.setAlarmState("child", "ALARM", "breached", null, REGION);
+
+ List<AlarmHistoryItem> items = service.describeAlarmHistory(null, List.of("MetricAlarm", "CompositeAlarm"),
+ "StateUpdate", null, null, null, null, null, REGION).items();
+ assertEquals(List.of("parent:Alarm updated from OK to ALARM", "child:Alarm updated from INSUFFICIENT_DATA to ALARM",
+ "parent:Alarm updated from INSUFFICIENT_DATA to OK"),
+ items.stream().map(item -> item.alarmName() + ":" + item.historySummary()).toList());
+ JsonNode data = new ObjectMapper().readTree(items.getFirst().historyData());
+ assertEquals("AlarmRule evaluated to ALARM", data.path("newState").path("stateReason").asText());
+ assertEquals("AlarmRule evaluated to OK", data.path("oldState").path("stateReason").asText());
+ }
+
private CompositeAlarm put(String name, String rule) {
CompositeAlarm alarm = new CompositeAlarm();
alarm.setAlarmName(name);
diff --git a/src/test/java/io/github/hectorvent/floci/services/identitystore/IdentityStorePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/identitystore/IdentityStorePersistenceTest.java
index f357b849e0..1984bd6083 100644
--- a/src/test/java/io/github/hectorvent/floci/services/identitystore/IdentityStorePersistenceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/identitystore/IdentityStorePersistenceTest.java
@@ -2,12 +2,11 @@ package io.github.hectorvent.floci.services.identitystore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
-import io.github.hectorvent.floci.config.EmulatorConfig;
-import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.identitystore.model.Group;
import io.github.hectorvent.floci.services.identitystore.model.Membership;
import io.github.hectorvent.floci.services.identitystore.model.User;
+import io.github.hectorvent.floci.testing.StorageFactories;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@@ -25,10 +24,6 @@ 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.assertTrue;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
class IdentityStorePersistenceTest {
private static final String STORE = "d-1234567890";
@@ -36,17 +31,6 @@ class IdentityStorePersistenceTest {
private final ObjectMapper mapper = new ObjectMapper();
- private StorageFactory newFactory(Path dir, String mode) {
- EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
- when(config.defaultAccountId()).thenReturn(GLOBAL_PARTITION);
- when(config.storage().persistentPath()).thenReturn(dir.toString());
- when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
- ServiceConfigAccess access = mock(ServiceConfigAccess.class);
- when(access.storageMode(anyString())).thenReturn(mode);
- when(access.storageFlushInterval(anyString())).thenReturn(3_600_000L);
- return new StorageFactory(config, access);
- }
-
private ObjectNode idRequest(String idField, String id) {
ObjectNode request = mapper.createObjectNode();
request.put("IdentityStoreId", STORE);
@@ -114,13 +98,13 @@ class IdentityStorePersistenceTest {
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void usersGroupsAndMembershipsSurviveRestart(String mode, @TempDir Path dir) {
- StorageFactory firstFactory = newFactory(dir, mode);
+ StorageFactory firstFactory = StorageFactories.open(dir, mode, GLOBAL_PARTITION);
IdentityStoreService first = new IdentityStoreService(firstFactory, mapper);
Seeded seeded = seed(first);
firstFactory.shutdownAll();
- StorageFactory reopenedFactory = newFactory(dir, mode);
+ StorageFactory reopenedFactory = StorageFactories.open(dir, mode, GLOBAL_PARTITION);
IdentityStoreService reopened = new IdentityStoreService(reopenedFactory, mapper);
assertReloaded(reopened, seeded);
reopenedFactory.shutdownAll();
@@ -129,7 +113,7 @@ class IdentityStorePersistenceTest {
@Test
void usersGroupsAndMembershipsSurviveWalReplayAfterCrash(@TempDir Path dirA, @TempDir Path dirB)
throws IOException {
- StorageFactory crashedFactory = newFactory(dirA, "wal");
+ StorageFactory crashedFactory = StorageFactories.open(dirA, "wal", GLOBAL_PARTITION);
StorageFactory recoveredFactory = null;
try {
IdentityStoreService crashed = new IdentityStoreService(crashedFactory, mapper);
@@ -152,7 +136,7 @@ class IdentityStorePersistenceTest {
}
}
- recoveredFactory = newFactory(dirB, "wal");
+ recoveredFactory = StorageFactories.open(dirB, "wal", GLOBAL_PARTITION);
IdentityStoreService recovered = new IdentityStoreService(recoveredFactory, mapper);
assertReloaded(recovered, seeded);
} finally {
diff --git a/src/test/java/io/github/hectorvent/floci/testing/StorageFactories.java b/src/test/java/io/github/hectorvent/floci/testing/StorageFactories.java
new file mode 100644
index 0000000000..61bfdee174
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/StorageFactories.java
@@ -0,0 +1,46 @@
+package io.github.hectorvent.floci.testing;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+
+import java.nio.file.Path;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Real {@link StorageFactory} instances over a test directory, for tests that shut one down and open
+ * another on the same directory to see what a storage mode keeps. The WAL compaction and flush intervals
+ * are an hour, so neither timer fires during a test.
+ */
+public final class StorageFactories {
+
+ private static final long AN_HOUR_MS = 3_600_000L;
+
+ private StorageFactories() {
+ }
+
+ /** A factory whose every store uses {@code mode} under {@code directory}, scoped to {@code account}. */
+ public static StorageFactory open(Path directory, String mode, String account) {
+ return open(config(directory, account), mode);
+ }
+
+ /** The deep-stubbed config {@link #open(Path, String, String)} uses, for a test that stubs more of it. */
+ public static EmulatorConfig config(Path directory, String account) {
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.defaultAccountId()).thenReturn(account);
+ when(config.storage().persistentPath()).thenReturn(directory.toString());
+ when(config.storage().wal().compactionIntervalMs()).thenReturn(AN_HOUR_MS);
+ return config;
+ }
+
+ public static StorageFactory open(EmulatorConfig config, String mode) {
+ ServiceConfigAccess access = mock(ServiceConfigAccess.class);
+ when(access.storageMode(anyString())).thenReturn(mode);
+ when(access.storageFlushInterval(anyString())).thenReturn(AN_HOUR_MS);
+ return new StorageFactory(config, access);
+ }
+}