feat(rum): add CloudWatch RUM app-monitor service (#1797)

* feat(rum): add CloudWatch RUM app-monitor service

Adds a minimal CloudWatch RUM service (restJson1) covering the app-monitor
lifecycle — CreateAppMonitor, GetAppMonitor, UpdateAppMonitor, DeleteAppMonitor,
ListAppMonitors — backed by an in-memory store.

Previously restJson1 RUM requests (e.g. POST /appmonitor) fell through to the S3
path-style catch-all (@Path("/{bucket}")) and returned an XML error that
restJson1 SDKs (and the CDK AwsCustomResource used for RUM AppMonitor custom
resources) cannot parse. Literal /appmonitor and /appmonitors paths take JAX-RS
precedence over S3's /{bucket} template (the same mechanism eks/mq use), so the
routes win with no extra routing wiring.

Verified with aws-cli 2.33.18 against a dev-mode emulator: CreateAppMonitor
returns an Id, GetAppMonitor/ListAppMonitors round-trip, DeleteAppMonitor then
GetAppMonitor returns ResourceNotFoundException.

* fix(rum): make monitor updates atomic

* fix(rum): align app monitor lifecycle with AWS

* chore: retry flaky Node compatibility check

* fix(rum): address app-monitor review feedback

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>
This commit is contained in:
Alex Bannaandabanna authored and GitHub committed 2026-08-01 15:28:54 -05:00
1 parent 04873bfd09
commit aadc93e306
16 files changed
+1544 -4

No files matched your search

@@ -240,6 +240,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>cloudwatch</artifactId>
</dependency>
<!-- CloudWatch RUM client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>rum</artifactId>
</dependency>
<!-- Secrets Manager client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
@@ -24,6 +24,7 @@ import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.opensearch.OpenSearchClient;
import software.amazon.awssdk.services.neptune.NeptuneClient;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rum.RumClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.services.s3control.S3ControlClient;
@@ -663,6 +664,14 @@ public final class TestFixtures {
.build();
}
public static RumClient rumClient() {
return RumClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build();
}
public static NeptuneClient neptuneClient() {
return NeptuneClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,111 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.rum.RumClient;
import software.amazon.awssdk.services.rum.model.AppMonitorSummary;
import software.amazon.awssdk.services.rum.model.CreateAppMonitorResponse;
import software.amazon.awssdk.services.rum.model.GetAppMonitorResponse;
import software.amazon.awssdk.services.rum.model.ListAppMonitorsResponse;
import software.amazon.awssdk.services.rum.model.ResourceNotFoundException;
import software.amazon.awssdk.services.rum.model.StateEnum;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("CloudWatch RUM")
class RumTest {
@Test
void appMonitorLifecycleUsesAwsSdkWireShapes() throws Exception {
Set<String> cleanupNames = new LinkedHashSet<>();
String prefix = TestFixtures.uniqueName("rum");
String firstName = prefix + "-a";
String secondName = prefix + "-b";
try (RumClient rum = TestFixtures.rumClient();
AutoCloseable deleteMonitors = () -> {
for (String name : cleanupNames) {
rum.deleteAppMonitor(request -> request.name(name));
}
}) {
cleanupNames.add(firstName);
CreateAppMonitorResponse first = rum.createAppMonitor(request -> request
.name(firstName)
.domain("first.example.com")
.platform("Android")
.tags(Map.of("env1", "test")));
cleanupNames.add(secondName);
CreateAppMonitorResponse second = rum.createAppMonitor(request -> request
.name(secondName)
.domain("second.example.com"));
assertThat(first.id()).hasSize(36);
assertThat(second.id()).hasSize(36);
GetAppMonitorResponse created = rum.getAppMonitor(request -> request.name(firstName));
assertThat(created.appMonitor().id()).isEqualTo(first.id());
assertThat(created.appMonitor().name()).isEqualTo(firstName);
assertThat(created.appMonitor().domain()).isEqualTo("first.example.com");
assertThat(created.appMonitor().state()).isEqualTo(StateEnum.CREATED);
assertThat(created.appMonitor().platformAsString()).isEqualTo("Android");
assertThat(created.appMonitor().tags()).containsEntry("env1", "test");
assertThat(created.appMonitor().created()).hasSize(19);
assertThat(created.appMonitor().lastModified()).hasSize(19);
String createdAt = created.appMonitor().created();
rum.updateAppMonitor(request -> request
.name(firstName)
.domainList(List.of("updated.example.com", "localhost"))
.cwLogEnabled(true));
GetAppMonitorResponse updated = rum.getAppMonitor(request -> request.name(firstName));
assertThat(updated.appMonitor().id()).isEqualTo(first.id());
assertThat(updated.appMonitor().name()).isEqualTo(firstName);
assertThat(updated.appMonitor().domain()).isNull();
assertThat(updated.appMonitor().domainList())
.containsExactly("updated.example.com", "localhost");
assertThat(updated.appMonitor().dataStorage().cwLog().cwLogEnabled()).isTrue();
assertThat(updated.appMonitor().state()).isEqualTo(StateEnum.CREATED);
assertThat(updated.appMonitor().platformAsString()).isEqualTo("Android");
assertThat(updated.appMonitor().tags()).containsEntry("env1", "test");
assertThat(updated.appMonitor().created()).isEqualTo(createdAt);
assertThat(updated.appMonitor().lastModified()).hasSize(19);
ListAppMonitorsResponse firstPage =
rum.listAppMonitors(request -> request.maxResults(1));
assertThat(firstPage.appMonitorSummaries()).hasSize(1);
assertSummary(firstPage.appMonitorSummaries().get(0),
firstName, first.id(), "Android");
assertThat(firstPage.nextToken()).isNotBlank();
ListAppMonitorsResponse secondPage = rum.listAppMonitors(request -> request
.maxResults(1)
.nextToken(firstPage.nextToken()));
assertThat(secondPage.appMonitorSummaries()).hasSize(1);
assertSummary(secondPage.appMonitorSummaries().get(0),
secondName, second.id(), "Web");
assertThat(secondPage.nextToken()).isNull();
rum.deleteAppMonitor(request -> request.name(firstName));
cleanupNames.remove(firstName);
assertThatThrownBy(() -> rum.getAppMonitor(request -> request.name(firstName)))
.isInstanceOf(ResourceNotFoundException.class);
}
}
private static void assertSummary(
AppMonitorSummary summary, String name, String id, String platform) {
assertThat(summary.name()).isEqualTo(name);
assertThat(summary.id()).isEqualTo(id);
assertThat(summary.created()).hasSize(19);
assertThat(summary.lastModified()).hasSize(19);
assertThat(summary.state()).isEqualTo(StateEnum.CREATED);
assertThat(summary.platformAsString()).isEqualTo(platform);
}
}
+3 -2
View File
@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve
## Supported Services
Floci emulates 68 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
Floci emulates 69 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
| Service | Protocol |
|---|---|
@@ -55,6 +55,7 @@ Floci emulates 68 AWS services. See the [Services Overview](services/index.md) f
| EventBridge Pipes | REST JSON |
| EventBridge Scheduler | REST JSON |
| CloudWatch Logs & Metrics | JSON 1.1 / Query |
| CloudWatch RUM | REST JSON |
| AppConfig + AppConfigData | REST JSON |
| Bedrock Runtime | REST JSON |
| EKS | REST JSON |
@@ -111,7 +112,7 @@ docker compose up -d
aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
```
All 68 AWS services are immediately available at `http://localhost:4566`.
All 69 AWS services are immediately available at `http://localhost:4566`.
[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }
[View services →](services/index.md){ .md-button }
+2 -1
View File
@@ -1,6 +1,6 @@
# Services Overview
Floci emulates 68 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
Floci emulates 69 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.
@@ -33,6 +33,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 7 |
| [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 17 |
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 11 |
| [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 8 |
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 7 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 14 |
+59
View File
@@ -0,0 +1,59 @@
# CloudWatch RUM
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566`
Floci implements the CloudWatch RUM app-monitor management lifecycle for local SDK, CLI, and custom-resource workflows. App monitors are isolated by account and region and use the configured Floci storage mode.
## Supported Operations
| Operation | Method and path | Description |
|---|---|---|
| `CreateAppMonitor` | `POST /appmonitor` | Create an app monitor |
| `GetAppMonitor` | `GET /appmonitor/{name}` | Return an app monitor and its configuration |
| `UpdateAppMonitor` | `PATCH /appmonitor/{name}` | Update the supplied configuration fields |
| `DeleteAppMonitor` | `DELETE /appmonitor/{name}` | Delete an app monitor |
| `ListAppMonitors` | `POST /appmonitors` | List app-monitor summaries with pagination |
`ListAppMonitors` returns monitors in name order. Its default page size is 50 and its maximum page size is 100.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_RUM_ENABLED` | `true` | Enable or disable CloudWatch RUM |
| `FLOCI_STORAGE_SERVICES_RUM_MODE` | *(inherits global)* | Optional RUM storage-mode override |
| `FLOCI_STORAGE_SERVICES_RUM_FLUSH_INTERVAL_MS` | `5000` | Hybrid storage flush interval in milliseconds |
Unless the RUM-specific override is set, app-monitor state follows the global `FLOCI_STORAGE_MODE` setting. Persistent, hybrid, and write-ahead-log modes restore monitors after restart.
## Example
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
aws rum create-app-monitor \
--name local-app \
--domain example.com \
--tags env1=test
aws rum get-app-monitor --name local-app
aws rum list-app-monitors
aws rum update-app-monitor \
--name local-app \
--domain-list updated.example.com localhost \
--cw-log-enabled
aws rum delete-app-monitor --name local-app
```
## Current Scope
- App-monitor configuration, domains, platforms, create-time tags, state, timestamps, and pagination are modeled.
- `CwLogEnabled` is retained as control-plane configuration; Floci does not create a CloudWatch Logs group or copy RUM telemetry.
- Event and data-plane APIs are not implemented: `PutRumEvents` and `GetAppMonitorData`.
- Tag-management APIs are not implemented: `TagResource`, `UntagResource`, and `ListTagsForResource`.
- Resource-policy APIs are not implemented: `PutResourcePolicy`, `GetResourcePolicy`, and `DeleteResourcePolicy`.
- Metric-definition APIs are not implemented: `BatchCreateRumMetricDefinitions`, `BatchDeleteRumMetricDefinitions`, `BatchGetRumMetricDefinitions`, and `UpdateRumMetricDefinition`.
- Metric-destination APIs are not implemented: `PutRumMetricsDestination`, `DeleteRumMetricsDestination`, and `ListRumMetricsDestinations`.
+1
View File
@@ -104,6 +104,7 @@ nav:
- EventBridge Pipes: services/pipes.md
- EventBridge Scheduler: services/scheduler.md
- CloudWatch: services/cloudwatch.md
- CloudWatch RUM: services/rum.md
- ACM: services/acm.md
- ECS: services/ecs.md
- ECR: services/ecr.md
@@ -280,6 +280,7 @@ public interface EmulatorConfig {
TaggingStorageConfig tagging();
ElasticBeanstalkStorageConfig elasticbeanstalk();
CloudTrailStorageConfig cloudtrail();
RumStorageConfig rum();
}
interface SsmStorageConfig {
@@ -488,6 +489,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface RumStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface CodeDeployStorageConfig {
Optional<String> mode();
@@ -585,6 +593,7 @@ public interface EmulatorConfig {
S3VectorsServiceConfig s3vectors();
IotServiceConfig iot();
IotDataServiceConfig iotdata();
RumServiceConfig rum();
}
interface IotServiceConfig {
@@ -613,6 +622,11 @@ public interface EmulatorConfig {
boolean enabled();
}
interface RumServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface LightsailServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.route53.Route53Controller;
import io.github.hectorvent.floci.services.ses.SesController;
import io.github.hectorvent.floci.services.appsync.AppSyncController;
import io.github.hectorvent.floci.services.rdsdata.RdsDataController;
import io.github.hectorvent.floci.services.rum.RumController;
import io.github.hectorvent.floci.services.s3vectors.S3VectorsController;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -393,7 +394,12 @@ public class ResolvedServiceCatalog {
descriptor("iotdata", "iotdata", config.services().iotdata().enabled(), true,
"iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("iotdata"), Set.of(), Set.of(IotDataController.class))
Set.of(), Set.of("iotdata"), Set.of(), Set.of(IotDataController.class)),
descriptor("rum", "rum", config.services().rum().enabled(), true,
"rum", storageMode(config.storage().services().rum().mode(), config.storage().mode()),
config.storage().services().rum().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("rum"), Set.of(), Set.of(RumController.class))
));
}
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.services.rum;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.services.rum.model.AppMonitor;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* CloudWatch RUM (Smithy restJson1) — minimal app-monitor lifecycle.
*
* <p>Exists so the CDK RUM AppMonitor custom resource ({@code Custom::AWS} / AwsCustomResource) —
* which calls {@code rum:createAppMonitor}/{@code updateAppMonitor}/{@code deleteAppMonitor} — gets a
* JSON response. Without a {@code rum} service these requests fell through to the S3 catch-all
* ({@code @Path("/{bucket}")}) and returned an XML error, which the restJson1 SDK could not parse.
*
* <p>The literal {@code /appmonitor} paths take JAX-RS precedence over S3's {@code /{bucket}} and
* {@code /{bucket}/{key}} template routes, so these routes win with no extra routing wiring.
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class RumController {
private final RumService service;
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
@Inject
public RumController(RumService service, ObjectMapper objectMapper, RegionResolver regionResolver) {
this.service = service;
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
}
private JsonNode parse(String body) {
if (body == null || body.isBlank()) {
return objectMapper.createObjectNode();
}
try {
JsonNode request = objectMapper.readTree(body);
if (request == null || !request.isObject()) {
throw new AwsException("ValidationException", "Request body must be a JSON object.", 400);
}
return request;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("ValidationException", "Request body is not valid JSON.", 400);
}
}
@POST
@Path("/appmonitor")
public Response createAppMonitor(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
AppMonitor monitor = service.createAppMonitor(regionResolver.resolveRegion(headers), request);
ObjectNode response = objectMapper.createObjectNode();
response.put("Id", monitor.getId());
return Response.ok(response).build();
}
@GET
@Path("/appmonitor/{name}")
public Response getAppMonitor(@Context HttpHeaders headers, @PathParam("name") String name) {
AppMonitor monitor = service.getAppMonitor(regionResolver.resolveRegion(headers), name);
ObjectNode response = objectMapper.createObjectNode();
response.set("AppMonitor", objectMapper.valueToTree(monitor));
return Response.ok(response).build();
}
@PATCH
@Path("/appmonitor/{name}")
public Response updateAppMonitor(
@Context HttpHeaders headers, @PathParam("name") String name, String body) {
JsonNode request = parse(body);
service.updateAppMonitor(regionResolver.resolveRegion(headers), name, request);
return Response.ok().build();
}
@DELETE
@Path("/appmonitor/{name}")
public Response deleteAppMonitor(@Context HttpHeaders headers, @PathParam("name") String name) {
service.deleteAppMonitor(regionResolver.resolveRegion(headers), name);
return Response.ok().build();
}
@POST
@Path("/appmonitors")
@Consumes(MediaType.WILDCARD)
public Response listAppMonitors(
@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
RumService.Page page = service.listAppMonitors(
regionResolver.resolveRegion(headers), maxResults, nextToken);
ObjectNode response = objectMapper.createObjectNode();
var summaries = response.putArray("AppMonitorSummaries");
for (AppMonitor monitor : page.monitors()) {
ObjectNode summary = objectMapper.createObjectNode();
summary.put("Created", monitor.getCreated());
summary.put("Id", monitor.getId());
summary.put("LastModified", monitor.getLastModified());
summary.put("Name", monitor.getName());
summary.put("Platform", monitor.getPlatform());
summary.put("State", monitor.getState());
summaries.add(summary);
}
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
}
@@ -0,0 +1,472 @@
package io.github.hectorvent.floci.services.rum;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.rum.model.AppMonitor;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
/** CloudWatch RUM app-monitor lifecycle backed by the configured Floci storage mode. */
@ApplicationScoped
public class RumService {
private static final int DEFAULT_MAX_RESULTS = 50;
private static final int MAX_RESULTS = 100;
private static final String TOKEN_PREFIX = "rum:v1:";
private static final DateTimeFormatter TIMESTAMP_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC);
private static final Pattern NAME_PATTERN = Pattern.compile("(?!\\.)[.\\-_#A-Za-z0-9]+");
private static final Pattern DOMAIN_PATTERN = Pattern.compile(
"(localhost)$|^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}"
+ "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|"
+ "(?=^[a-zA-Z0-9.\\*-]{4,253}$)(?!.*\\.-)(?!.*-\\.)(?!.*\\.\\.)"
+ "(?!.*[^.]{64,})^(\\*\\.)?(?![-.\\*])[^\\*]{1,}\\."
+ "(\\*|(?!.*--)(?=.*[a-zA-Z])[^\\*]{1,}[^\\*-])$");
private static final Pattern TAG_KEY_PATTERN = Pattern.compile("(?!aws:)[a-zA-Z+-=._:/]+");
private static final Pattern S3_URI_PATTERN = Pattern.compile(
"s3://[a-z0-9][-.a-z0-9]{1,62}(?:/[-!_*'().a-z0-9A-Z]+(?:/[-!_*'().a-z0-9A-Z]+)*)?/?");
private static final Set<String> TELEMETRIES = Set.of("errors", "performance", "http");
private static final Set<String> ENABLED_DISABLED = Set.of("ENABLED", "DISABLED");
private static final Set<String> PLATFORMS = Set.of("Web", "Android", "iOS");
private final StorageBackend<String, AppMonitor> monitorStore;
@Inject
public RumService(StorageFactory storageFactory) {
this(storageFactory.create(
"rum",
"rum-app-monitors.json",
new TypeReference<Map<String, AppMonitor>>() {
}));
}
RumService(StorageBackend<String, AppMonitor> monitorStore) {
this.monitorStore = monitorStore;
}
public synchronized AppMonitor createAppMonitor(String region, JsonNode request) {
requireObject(request, "Request body");
String name = requireText(request, "Name");
validateName(name);
DomainSelection domains = readDomains(request);
JsonNode configuration = readConfiguration(request);
JsonNode customEvents = readCustomEvents(request);
JsonNode deobfuscation = readDeobfuscationConfiguration(request);
boolean cwLogEnabled = request.has("CwLogEnabled")
? requireBoolean(request, "CwLogEnabled")
: false;
Map<String, String> tags = readTags(request);
String platform = readPlatform(request);
String key = storageKey(region, name);
if (monitorStore.get(key).isPresent()) {
throw resourceConflict(name);
}
String now = timestamp();
AppMonitor monitor = new AppMonitor(
UUID.randomUUID().toString(),
name,
domains.domain(),
domains.domainList(),
"CREATED",
platform,
now,
now,
tags,
configuration,
dataStorage(cwLogEnabled),
customEvents,
deobfuscation);
monitorStore.put(key, monitor);
return monitor;
}
public AppMonitor getAppMonitor(String region, String name) {
validateName(name);
return monitorStore.get(storageKey(region, name)).orElseThrow(() -> resourceNotFound(name));
}
public synchronized void updateAppMonitor(String region, String name, JsonNode request) {
validateName(name);
requireObject(request, "Request body");
String key = storageKey(region, name);
AppMonitor current = monitorStore.get(key).orElseThrow(() -> resourceNotFound(name));
boolean domainChanged = request.has("Domain") || request.has("DomainList");
DomainSelection domains = domainChanged
? readDomains(request)
: new DomainSelection(current.getDomain(), current.getDomainList());
JsonNode configuration = request.has("AppMonitorConfiguration")
? mergeObjects(current.getAppMonitorConfiguration(), readConfiguration(request))
: current.getAppMonitorConfiguration();
JsonNode customEvents = request.has("CustomEvents")
? mergeObjects(current.getCustomEvents(), readCustomEvents(request))
: current.getCustomEvents();
JsonNode deobfuscation = request.has("DeobfuscationConfiguration")
? mergeObjects(current.getDeobfuscationConfiguration(), readDeobfuscationConfiguration(request))
: current.getDeobfuscationConfiguration();
JsonNode storage = request.has("CwLogEnabled")
? dataStorage(requireBoolean(request, "CwLogEnabled"))
: current.getDataStorage();
boolean changed = domainChanged
|| request.has("AppMonitorConfiguration")
|| request.has("CustomEvents")
|| request.has("DeobfuscationConfiguration")
|| request.has("CwLogEnabled");
if (!changed) {
return;
}
AppMonitor updated = new AppMonitor(
current.getId(),
current.getName(),
domains.domain(),
domains.domainList(),
current.getState(),
current.getPlatform(),
current.getCreated(),
timestamp(),
current.getTags(),
configuration,
storage,
customEvents,
deobfuscation);
monitorStore.put(key, updated);
}
public synchronized void deleteAppMonitor(String region, String name) {
validateName(name);
String key = storageKey(region, name);
if (monitorStore.get(key).isEmpty()) {
throw resourceNotFound(name);
}
monitorStore.delete(key);
}
public Page listAppMonitors(String region, String maxResultsValue, String nextToken) {
int maxResults = parseMaxResults(maxResultsValue);
List<AppMonitor> monitors = monitorStore.scan(key -> key.startsWith(region + "::"));
monitors.sort(Comparator.comparing(AppMonitor::getName));
int offset = decodeOffset(nextToken, monitors.size());
int end = Math.min(offset + maxResults, monitors.size());
String responseToken = end < monitors.size() ? encodeOffset(end) : null;
return new Page(monitors.subList(offset, end), responseToken);
}
private static String storageKey(String region, String name) {
return region + "::" + name;
}
private static String timestamp() {
return TIMESTAMP_FORMATTER.format(Instant.now());
}
private static DomainSelection readDomains(JsonNode request) {
boolean hasDomain = request.has("Domain");
boolean hasDomainList = request.has("DomainList");
if (hasDomain == hasDomainList) {
throw validation("Specify exactly one of Domain or DomainList.");
}
if (hasDomain) {
String domain = requireText(request, "Domain");
validateDomain(domain, "Domain");
return new DomainSelection(domain, null);
}
JsonNode node = request.get("DomainList");
if (node == null || !node.isArray() || node.size() < 1 || node.size() > 5) {
throw validation("DomainList must contain between 1 and 5 domains.");
}
List<String> domains = new ArrayList<>(node.size());
for (int i = 0; i < node.size(); i++) {
JsonNode domainNode = node.get(i);
if (!domainNode.isTextual()) {
throw validation("DomainList members must be strings.");
}
String domain = domainNode.textValue();
validateDomain(domain, "DomainList");
domains.add(domain);
}
return new DomainSelection(null, domains);
}
private static void validateName(String name) {
if (name == null || name.length() < 1 || name.length() > 255 || !NAME_PATTERN.matcher(name).matches()) {
throw validation("Name must match (?!\\.)[.\\-_#A-Za-z0-9]+ and contain at most 255 characters.");
}
}
private static void validateDomain(String domain, String field) {
if (domain == null || domain.length() < 1 || domain.length() > 253
|| !DOMAIN_PATTERN.matcher(domain).matches()) {
throw validation(field + " contains an invalid domain.");
}
}
private static JsonNode readConfiguration(JsonNode request) {
JsonNode configuration = optionalObject(request, "AppMonitorConfiguration");
if (configuration == null) {
return null;
}
requireOptionalBoolean(configuration, "AllowCookies");
requireOptionalBoolean(configuration, "EnableXRay");
requireOptionalText(configuration, "GuestRoleArn");
requireOptionalText(configuration, "IdentityPoolId");
if (configuration.has("SessionSampleRate")) {
JsonNode rate = configuration.get("SessionSampleRate");
if (!rate.isNumber() || rate.doubleValue() < 0 || rate.doubleValue() > 1) {
throw validation("SessionSampleRate must be between 0 and 1.");
}
}
if (configuration.has("ExcludedPages") && configuration.has("IncludedPages")) {
throw validation("ExcludedPages and IncludedPages cannot both be specified.");
}
validateStringArray(configuration, "ExcludedPages", 50, null);
validateStringArray(configuration, "IncludedPages", 50, null);
validateStringArray(configuration, "FavoritePages", 50, null);
validateStringArray(configuration, "Telemetries", Integer.MAX_VALUE, TELEMETRIES);
return configuration.deepCopy();
}
private static JsonNode readCustomEvents(JsonNode request) {
JsonNode customEvents = optionalObject(request, "CustomEvents");
if (customEvents == null) {
return null;
}
if (customEvents.has("Status")) {
String status = requireText(customEvents, "Status");
if (!ENABLED_DISABLED.contains(status)) {
throw validation("CustomEvents.Status must be ENABLED or DISABLED.");
}
}
return customEvents.deepCopy();
}
private static JsonNode readDeobfuscationConfiguration(JsonNode request) {
JsonNode configuration = optionalObject(request, "DeobfuscationConfiguration");
if (configuration == null) {
return null;
}
if (configuration.has("JavaScriptSourceMaps")) {
JsonNode sourceMaps = configuration.get("JavaScriptSourceMaps");
requireObject(sourceMaps, "JavaScriptSourceMaps");
String status = requireText(sourceMaps, "Status");
if (!ENABLED_DISABLED.contains(status)) {
throw validation("JavaScriptSourceMaps.Status must be ENABLED or DISABLED.");
}
if (sourceMaps.has("S3Uri")) {
String s3Uri = requireText(sourceMaps, "S3Uri");
if (s3Uri.length() > 1024 || !S3_URI_PATTERN.matcher(s3Uri).matches()) {
throw validation("JavaScriptSourceMaps.S3Uri is invalid.");
}
} else if ("ENABLED".equals(status)) {
throw validation("JavaScriptSourceMaps.S3Uri is required when Status is ENABLED.");
}
}
return configuration.deepCopy();
}
private static String readPlatform(JsonNode request) {
if (!request.has("Platform")) {
return "Web";
}
String platform = requireText(request, "Platform");
if (!PLATFORMS.contains(platform)) {
throw validation("Platform must be Web, Android, or iOS.");
}
return platform;
}
private static JsonNode mergeObjects(JsonNode current, JsonNode update) {
ObjectNode merged = current != null && current.isObject()
? (ObjectNode) current.deepCopy()
: JsonNodeFactory.instance.objectNode();
update.fields().forEachRemaining(entry -> {
JsonNode existingValue = merged.get(entry.getKey());
JsonNode updateValue = entry.getValue();
if (existingValue != null && existingValue.isObject() && updateValue.isObject()) {
merged.set(entry.getKey(), mergeObjects(existingValue, updateValue));
} else {
merged.set(entry.getKey(), updateValue.deepCopy());
}
});
return merged;
}
private static Map<String, String> readTags(JsonNode request) {
if (!request.has("Tags")) {
return null;
}
JsonNode tagsNode = request.get("Tags");
if (tagsNode == null || !tagsNode.isObject() || tagsNode.size() > 50) {
throw validation("Tags must be an object with at most 50 entries.");
}
Map<String, String> tags = new LinkedHashMap<>();
tagsNode.fields().forEachRemaining(entry -> {
String key = entry.getKey();
JsonNode valueNode = entry.getValue();
if (key.length() < 1 || key.length() > 128 || !TAG_KEY_PATTERN.matcher(key).matches()
|| !valueNode.isTextual() || valueNode.textValue().length() > 256) {
throw validation("Tags contains an invalid key or value.");
}
tags.put(key, valueNode.textValue());
});
return tags;
}
private static ObjectNode dataStorage(boolean enabled) {
ObjectNode cwLog = JsonNodeFactory.instance.objectNode();
cwLog.put("CwLogEnabled", enabled);
ObjectNode dataStorage = JsonNodeFactory.instance.objectNode();
dataStorage.set("CwLog", cwLog);
return dataStorage;
}
private static JsonNode optionalObject(JsonNode parent, String field) {
if (!parent.has(field)) {
return null;
}
JsonNode value = parent.get(field);
requireObject(value, field);
return value;
}
private static void requireObject(JsonNode value, String field) {
if (value == null || !value.isObject()) {
throw validation(field + " must be a JSON object.");
}
}
private static String requireText(JsonNode parent, String field) {
JsonNode value = parent.get(field);
if (value == null || !value.isTextual()) {
throw validation(field + " must be a string.");
}
return value.textValue();
}
private static boolean requireBoolean(JsonNode parent, String field) {
JsonNode value = parent.get(field);
if (value == null || !value.isBoolean()) {
throw validation(field + " must be a boolean.");
}
return value.booleanValue();
}
private static void requireOptionalBoolean(JsonNode parent, String field) {
if (parent.has(field)) {
requireBoolean(parent, field);
}
}
private static void requireOptionalText(JsonNode parent, String field) {
if (parent.has(field)) {
requireText(parent, field);
}
}
private static void validateStringArray(JsonNode parent, String field, int maxSize, Set<String> values) {
if (!parent.has(field)) {
return;
}
JsonNode array = parent.get(field);
if (!array.isArray() || array.size() > maxSize) {
throw validation(field + " must be an array with at most " + maxSize + " entries.");
}
for (JsonNode value : array) {
if (!value.isTextual() || (values != null && !values.contains(value.textValue()))) {
throw validation(field + " contains an invalid value.");
}
}
}
private static int parseMaxResults(String value) {
if (value == null) {
return DEFAULT_MAX_RESULTS;
}
try {
int parsed = Integer.parseInt(value);
if (parsed < 1 || parsed > MAX_RESULTS) {
throw validation("maxResults must be between 1 and 100.");
}
return parsed;
} catch (NumberFormatException e) {
throw validation("maxResults must be an integer between 1 and 100.");
}
}
private static int decodeOffset(String token, int resultSize) {
if (token == null) {
return 0;
}
try {
String decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
if (!decoded.startsWith(TOKEN_PREFIX)) {
throw validation("nextToken is invalid.");
}
int offset = Integer.parseInt(decoded.substring(TOKEN_PREFIX.length()));
if (offset < 1 || offset >= resultSize) {
throw validation("nextToken is invalid.");
}
return offset;
} catch (IllegalArgumentException e) {
throw validation("nextToken is invalid.");
}
}
private static String encodeOffset(int offset) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString((TOKEN_PREFIX + offset).getBytes(StandardCharsets.UTF_8));
}
private static AwsException resourceConflict(String name) {
return new AwsException(
"ConflictException",
"App monitor " + name + " already exists.",
409,
Map.of("resourceName", name, "resourceType", "AppMonitor"));
}
private static AwsException resourceNotFound(String name) {
return new AwsException(
"ResourceNotFoundException",
"App monitor " + name + " does not exist.",
404,
Map.of("resourceName", name, "resourceType", "AppMonitor"));
}
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
public record Page(List<AppMonitor> monitors, String nextToken) {
public Page {
monitors = List.copyOf(monitors);
}
}
private record DomainSelection(String domain, List<String> domainList) {
}
}
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.rum.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
/** A CloudWatch RUM app monitor. Serialized with AWS's UpperCamelCase member names. */
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class AppMonitor {
private String id;
private String name;
private String domain;
private List<String> domainList;
private String state;
private String platform;
private String created;
private String lastModified;
private Map<String, String> tags;
private JsonNode appMonitorConfiguration;
private JsonNode dataStorage;
private JsonNode customEvents;
private JsonNode deobfuscationConfiguration;
public AppMonitor() {
}
public AppMonitor(
String id,
String name,
String domain,
List<String> domainList,
String state,
String platform,
String created,
String lastModified,
Map<String, String> tags,
JsonNode appMonitorConfiguration,
JsonNode dataStorage,
JsonNode customEvents,
JsonNode deobfuscationConfiguration) {
this.id = id;
this.name = name;
this.domain = domain;
setDomainList(domainList);
this.state = state;
this.platform = platform;
this.created = created;
this.lastModified = lastModified;
setTags(tags);
setAppMonitorConfiguration(appMonitorConfiguration);
setDataStorage(dataStorage);
setCustomEvents(customEvents);
setDeobfuscationConfiguration(deobfuscationConfiguration);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public List<String> getDomainList() {
return domainList;
}
public void setDomainList(List<String> domainList) {
this.domainList = domainList == null ? null : List.copyOf(domainList);
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getLastModified() {
return lastModified;
}
public void setLastModified(String lastModified) {
this.lastModified = lastModified;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? null : Map.copyOf(tags);
}
public JsonNode getAppMonitorConfiguration() {
return copy(appMonitorConfiguration);
}
public void setAppMonitorConfiguration(JsonNode appMonitorConfiguration) {
this.appMonitorConfiguration = copy(appMonitorConfiguration);
}
public JsonNode getDataStorage() {
return copy(dataStorage);
}
public void setDataStorage(JsonNode dataStorage) {
this.dataStorage = copy(dataStorage);
}
public JsonNode getCustomEvents() {
return copy(customEvents);
}
public void setCustomEvents(JsonNode customEvents) {
this.customEvents = copy(customEvents);
}
public JsonNode getDeobfuscationConfiguration() {
return copy(deobfuscationConfiguration);
}
public void setDeobfuscationConfiguration(JsonNode deobfuscationConfiguration) {
this.deobfuscationConfiguration = copy(deobfuscationConfiguration);
}
private static JsonNode copy(JsonNode value) {
return value == null ? null : value.deepCopy();
}
}
+4
View File
@@ -136,6 +136,8 @@ floci:
# mode: memory
appsync:
flush-interval-ms: 5000
rum:
flush-interval-ms: 5000
dns:
# Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server.
@@ -439,3 +441,5 @@ floci:
port: 1883
iotdata:
enabled: true
rum:
enabled: true
@@ -0,0 +1,341 @@
package io.github.hectorvent.floci.services.rum;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Verifies the AWS restJson1 app-monitor lifecycle and isolation behavior. */
@QuarkusTest
class RumControllerIntegrationTest {
private static final String EAST = "us-east-1";
private static final String WEST = "us-west-2";
private static final String TIMESTAMP_PATTERN = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void appMonitorCreateUpdateGetListDeleteLifecycle() {
String authorization = auth("000000000101", EAST);
String name = "lifecycle-monitor";
String id = create(authorization, """
{
"Name":"lifecycle-monitor",
"Domain":"localhost",
"AppMonitorConfiguration":{"AllowCookies":true,"SessionSampleRate":0.5},
"CwLogEnabled":true,
"CustomEvents":{"Status":"ENABLED"},
"DeobfuscationConfiguration":{"JavaScriptSourceMaps":{"Status":"ENABLED","S3Uri":"s3://source-maps/maps"}},
"Platform":"Android",
"Tags":{"Owner":"floci"}
}
""");
Response created = given()
.contentType("application/json")
.header("Authorization", authorization)
.when()
.get("/appmonitor/" + name)
.then()
.statusCode(200)
.body("AppMonitor.Id", equalTo(id))
.body("AppMonitor.Name", equalTo(name))
.body("AppMonitor.Domain", equalTo("localhost"))
.body("AppMonitor.State", equalTo("CREATED"))
.body("AppMonitor.Platform", equalTo("Android"))
.body("AppMonitor.AppMonitorConfiguration.AllowCookies", equalTo(true))
.body("AppMonitor.DataStorage.CwLog.CwLogEnabled", equalTo(true))
.body("AppMonitor.CustomEvents.Status", equalTo("ENABLED"))
.body("AppMonitor.Tags.Owner", equalTo("floci"))
.extract().response();
String createdTimestamp = created.path("AppMonitor.Created");
String initialModified = created.path("AppMonitor.LastModified");
assertTrue(createdTimestamp.matches(TIMESTAMP_PATTERN));
assertTrue(initialModified.matches(TIMESTAMP_PATTERN));
String updateBody = given()
.contentType("application/json")
.header("Authorization", authorization)
.body("""
{
"DomainList":["updated.example.com","localhost"],
"AppMonitorConfiguration":{"EnableXRay":true},
"CwLogEnabled":false,
"CustomEvents":{"Status":"DISABLED"},
"DeobfuscationConfiguration":{"JavaScriptSourceMaps":{"Status":"DISABLED"}}
}
""")
.when()
.patch("/appmonitor/" + name)
.then()
.statusCode(200)
.extract().asString();
assertTrue(updateBody.isEmpty());
given()
.contentType("application/json")
.header("Authorization", authorization)
.when()
.get("/appmonitor/" + name)
.then()
.statusCode(200)
.body("AppMonitor.Id", equalTo(id))
.body("AppMonitor.Created", equalTo(createdTimestamp))
.body("AppMonitor.DomainList[0]", equalTo("updated.example.com"))
.body("AppMonitor.DomainList[1]", equalTo("localhost"))
.body("AppMonitor.AppMonitorConfiguration.EnableXRay", equalTo(true))
.body("AppMonitor.AppMonitorConfiguration.AllowCookies", equalTo(true))
.body("AppMonitor.AppMonitorConfiguration.SessionSampleRate", equalTo(0.5f))
.body("AppMonitor.DataStorage.CwLog.CwLogEnabled", equalTo(false))
.body("AppMonitor.CustomEvents.Status", equalTo("DISABLED"))
.body("AppMonitor.DeobfuscationConfiguration.JavaScriptSourceMaps.Status", equalTo("DISABLED"))
.body("AppMonitor.DeobfuscationConfiguration.JavaScriptSourceMaps.S3Uri", equalTo("s3://source-maps/maps"))
.body("AppMonitor.Tags.Owner", equalTo("floci"));
List<Map<String, Object>> summaries = list(authorization, null, null)
.path("AppMonitorSummaries");
assertEquals(1, summaries.size());
assertEquals(
Set.of("Created", "Id", "LastModified", "Name", "Platform", "State"),
summaries.getFirst().keySet());
assertEquals(name, summaries.getFirst().get("Name"));
assertEquals("Android", summaries.getFirst().get("Platform"));
assertEquals(createdTimestamp, summaries.getFirst().get("Created"));
assertTrue(((String) summaries.getFirst().get("LastModified")).matches(TIMESTAMP_PATTERN));
String deleteBody = given()
.contentType("application/json")
.header("Authorization", authorization)
.when()
.delete("/appmonitor/" + name)
.then()
.statusCode(200)
.extract().asString();
assertTrue(deleteBody.isEmpty());
given()
.contentType("application/json")
.header("Authorization", authorization)
.when()
.get("/appmonitor/" + name)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"))
.body("resourceName", equalTo(name))
.body("resourceType", equalTo("AppMonitor"));
}
@Test
void appMonitorsAreIsolatedByAccount() {
String firstAuth = auth("000000000102", EAST);
String secondAuth = auth("000000000103", EAST);
String firstId = create(firstAuth, "{\"Name\":\"shared-monitor\",\"Domain\":\"first.example.com\"}");
String secondId = create(secondAuth, "{\"Name\":\"shared-monitor\",\"Domain\":\"second.example.com\"}");
assertNotEquals(firstId, secondId);
get(firstAuth, "shared-monitor").then().body("AppMonitor.Domain", equalTo("first.example.com"));
get(secondAuth, "shared-monitor").then().body("AppMonitor.Domain", equalTo("second.example.com"));
assertEquals(1, ((List<?>) list(firstAuth, null, null).path("AppMonitorSummaries")).size());
assertEquals(1, ((List<?>) list(secondAuth, null, null).path("AppMonitorSummaries")).size());
}
@Test
void appMonitorsAreIsolatedByRegion() {
String eastAuth = auth("000000000104", EAST);
String westAuth = auth("000000000104", WEST);
String eastId = create(eastAuth, "{\"Name\":\"regional-monitor\",\"Domain\":\"east.example.com\"}");
String westId = create(westAuth, "{\"Name\":\"regional-monitor\",\"Domain\":\"west.example.com\"}");
assertNotEquals(eastId, westId);
get(eastAuth, "regional-monitor").then().body("AppMonitor.Domain", equalTo("east.example.com"));
get(westAuth, "regional-monitor").then().body("AppMonitor.Domain", equalTo("west.example.com"));
}
@Test
void listAppMonitorsSupportsDeterministicPaginationAndDefaultPageSize() {
String authorization = auth("000000000105", EAST);
for (int i = 50; i >= 0; i--) {
create(authorization, "{\"Name\":\"page-monitor-%02d\",\"Domain\":\"example.com\"}".formatted(i));
}
Response first = list(authorization, null, null);
List<String> firstNames = first.path("AppMonitorSummaries.Name");
String nextToken = first.path("NextToken");
assertEquals(50, firstNames.size());
assertEquals("page-monitor-00", firstNames.getFirst());
assertEquals("page-monitor-49", firstNames.getLast());
assertNotNull(nextToken);
Response second = list(authorization, "50", nextToken);
List<String> secondNames = second.path("AppMonitorSummaries.Name");
assertEquals(List.of("page-monitor-50"), secondNames);
assertNull(second.path("NextToken"));
List<String> allNames = new ArrayList<>(firstNames);
allNames.addAll(secondNames);
assertEquals(51, new HashSet<>(allNames).size());
}
@Test
void listAppMonitorsRejectsInvalidPaginationInputs() {
String authorization = auth("000000000106", EAST);
for (String maxResults : List.of("0", "101", "abc")) {
given()
.header("Authorization", authorization)
.queryParam("maxResults", maxResults)
.when()
.post("/appmonitors")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
given()
.header("Authorization", authorization)
.queryParam("nextToken", "not-a-token")
.when()
.post("/appmonitors")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void duplicateCreateReturnsConflictAndPreservesTheExistingMonitor() {
String authorization = auth("000000000107", EAST);
String id = create(authorization, "{\"Name\":\"duplicate-monitor\",\"Domain\":\"first.example.com\"}");
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"Name\":\"duplicate-monitor\",\"Domain\":\"second.example.com\"}")
.when()
.post("/appmonitor")
.then()
.statusCode(409)
.body("__type", equalTo("ConflictException"))
.body("resourceName", equalTo("duplicate-monitor"))
.body("resourceType", equalTo("AppMonitor"));
get(authorization, "duplicate-monitor")
.then()
.body("AppMonitor.Id", equalTo(id))
.body("AppMonitor.Domain", equalTo("first.example.com"));
}
@Test
void requestsRejectInvalidShapesAndExplicitBlankDomains() {
String authorization = auth("000000000108", EAST);
create(authorization, "{\"Name\":\"validation-monitor\",\"Domain\":\"example.com\"}");
for (String body : List.of("[]", "null", "{\"Domain\":\" \"}", "{\"Domain\":null}")) {
given()
.contentType("application/json")
.header("Authorization", authorization)
.body(body)
.when()
.patch("/appmonitor/validation-monitor")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
String noOpBody = given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{}")
.when()
.patch("/appmonitor/validation-monitor")
.then()
.statusCode(200)
.extract().asString();
assertTrue(noOpBody.isEmpty());
assertFalse(noOpBody.contains("{}"));
}
@Test
void createAppMonitorDefaultsPlatformAndRejectsInvalidValues() {
String authorization = auth("000000000109", EAST);
create(authorization, "{\"Name\":\"web-monitor\",\"Domain\":\"example.com\"}");
get(authorization, "web-monitor")
.then()
.statusCode(200)
.body("AppMonitor.Platform", equalTo("Web"));
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"Name\":\"invalid-platform\",\"Domain\":\"example.com\",\"Platform\":\"Desktop\"}")
.when()
.post("/appmonitor")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
private static String auth(String accountId, String region) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260205/" + region + "/rum/aws4_request";
}
private static String create(String authorization, String body) {
return given()
.contentType("application/json")
.header("Authorization", authorization)
.body(body)
.when()
.post("/appmonitor")
.then()
.statusCode(200)
.body("Id", notNullValue())
.extract().path("Id");
}
private static Response get(String authorization, String name) {
return given()
.contentType("application/json")
.header("Authorization", authorization)
.when()
.get("/appmonitor/" + name);
}
private static Response list(String authorization, String maxResults, String nextToken) {
var request = given()
.header("Authorization", authorization);
if (maxResults != null) {
request.queryParam("maxResults", maxResults);
}
if (nextToken != null) {
request.queryParam("nextToken", nextToken);
}
return request
.when()
.post("/appmonitors")
.then()
.statusCode(200)
.extract().response();
}
}
@@ -0,0 +1,213 @@
package io.github.hectorvent.floci.services.rum;
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.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.services.rum.model.AppMonitor;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RumServiceTest {
private static final String REGION = "us-east-1";
private final ObjectMapper objectMapper = new ObjectMapper();
private final RumService service = new RumService(new InMemoryStorage<>());
@Test
void updateAppMonitorAtomicallyReplacesTheStoredSnapshot() throws Exception {
AppMonitor original = service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"old.example.com","CwLogEnabled":false}
"""));
service.updateAppMonitor(REGION, "monitor", request("""
{
"Domain":"new.example.com",
"AppMonitorConfiguration":{"AllowCookies":true,"SessionSampleRate":0.5},
"CwLogEnabled":true,
"CustomEvents":{"Status":"ENABLED"}
}
"""));
AppMonitor updated = service.getAppMonitor(REGION, "monitor");
assertNotSame(original, updated);
assertEquals("old.example.com", original.getDomain());
assertEquals("new.example.com", updated.getDomain());
assertEquals(original.getId(), updated.getId());
assertEquals(original.getName(), updated.getName());
assertEquals(original.getState(), updated.getState());
assertEquals("Web", updated.getPlatform());
assertEquals(original.getCreated(), updated.getCreated());
assertEquals(19, updated.getLastModified().length());
assertTrue(updated.getAppMonitorConfiguration().path("AllowCookies").booleanValue());
assertTrue(updated.getDataStorage().path("CwLog").path("CwLogEnabled").booleanValue());
assertEquals("ENABLED", updated.getCustomEvents().path("Status").textValue());
}
@Test
void emptyUpdateLeavesTheStoredSnapshotUnchanged() throws Exception {
AppMonitor original = service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"old.example.com"}
"""));
service.updateAppMonitor(REGION, "monitor", request("{}"));
assertEquals(original, service.getAppMonitor(REGION, "monitor"));
}
@Test
void updateAppMonitorRejectsBlankDomain() throws Exception {
service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"old.example.com"}
"""));
AwsException error = assertThrows(
AwsException.class,
() -> service.updateAppMonitor(REGION, "monitor", request("{\"Domain\":\" \"}")));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void updateAppMonitorRejectsMissingMonitor() throws Exception {
AwsException error = assertThrows(
AwsException.class,
() -> service.updateAppMonitor(REGION, "missing", request("{\"Domain\":\"new.example.com\"}")));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
assertEquals("missing", error.getExtendedData().get("resourceName"));
}
@Test
void createAppMonitorRejectsDuplicateWithoutChangingOriginal() throws Exception {
AppMonitor original = service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"old.example.com"}
"""));
AwsException error = assertThrows(
AwsException.class,
() -> service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"new.example.com"}
""")));
assertEquals("ConflictException", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals("old.example.com", service.getAppMonitor(REGION, "monitor").getDomain());
assertEquals(original.getId(), service.getAppMonitor(REGION, "monitor").getId());
}
@Test
void listAppMonitorsPaginatesInNameOrder() throws Exception {
for (String name : List.of("monitor-c", "monitor-a", "monitor-b")) {
service.createAppMonitor(REGION, request("""
{"Name":"%s","Domain":"example.com"}
""".formatted(name)));
}
RumService.Page first = service.listAppMonitors(REGION, "2", null);
RumService.Page second = service.listAppMonitors(REGION, "2", first.nextToken());
assertEquals(List.of("monitor-a", "monitor-b"),
first.monitors().stream().map(AppMonitor::getName).toList());
assertEquals(List.of("monitor-c"), second.monitors().stream().map(AppMonitor::getName).toList());
assertFalse(first.nextToken().isBlank());
assertEquals(null, second.nextToken());
}
@Test
void listAppMonitorsRejectsInvalidLimitsAndTokens() {
for (String limit : List.of("0", "101", "not-a-number")) {
AwsException error = assertThrows(
AwsException.class, () -> service.listAppMonitors(REGION, limit, null));
assertEquals("ValidationException", error.getErrorCode());
}
AwsException tokenError = assertThrows(
AwsException.class, () -> service.listAppMonitors(REGION, null, "not-a-token"));
assertEquals("ValidationException", tokenError.getErrorCode());
}
@Test
void createAppMonitorSupportsDomainListAndDefaultsLoggingOff() throws Exception {
AppMonitor monitor = service.createAppMonitor(REGION, request("""
{"Name":"monitor","DomainList":["example.com","localhost"]}
"""));
assertEquals(List.of("example.com", "localhost"), monitor.getDomainList());
assertEquals(null, monitor.getDomain());
assertFalse(monitor.getDataStorage().path("CwLog").path("CwLogEnabled").booleanValue());
assertEquals(19, monitor.getCreated().length());
assertEquals(19, monitor.getLastModified().length());
assertEquals("Web", monitor.getPlatform());
}
@Test
void createAppMonitorAcceptsDigitInTagKey() throws Exception {
AppMonitor monitor = service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"example.com","Tags":{"env1":"test"}}
"""));
assertEquals("test", monitor.getTags().get("env1"));
}
@Test
void createAppMonitorRejectsAwsReservedTagKey() throws Exception {
AwsException error = assertThrows(
AwsException.class,
() -> service.createAppMonitor(REGION, request("""
{"Name":"monitor","Domain":"example.com","Tags":{"aws:team":"test"}}
""")));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void appMonitorConfigurationCanBeReloadedFromPersistentStorage(@TempDir Path tempDir) throws Exception {
Path file = tempDir.resolve("rum.json");
var firstStore = new PersistentStorage<String, AppMonitor>(
file, new TypeReference<Map<String, AppMonitor>>() {
});
firstStore.load();
RumService firstService = new RumService(firstStore);
AppMonitor created = firstService.createAppMonitor(REGION, request("""
{
"Name":"persistent-monitor",
"Domain":"example.com",
"AppMonitorConfiguration":{"AllowCookies":true},
"CwLogEnabled":true,
"Tags":{"Owner":"floci"}
}
"""));
var reloadedStore = new PersistentStorage<String, AppMonitor>(
file, new TypeReference<Map<String, AppMonitor>>() {
});
reloadedStore.load();
AppMonitor reloaded = new RumService(reloadedStore).getAppMonitor(REGION, "persistent-monitor");
assertEquals(created.getId(), reloaded.getId());
assertEquals(created.getCreated(), reloaded.getCreated());
assertEquals("Web", reloaded.getPlatform());
assertEquals("example.com", reloaded.getDomain());
assertTrue(reloaded.getAppMonitorConfiguration().path("AllowCookies").booleanValue());
assertTrue(reloaded.getDataStorage().path("CwLog").path("CwLogEnabled").booleanValue());
assertEquals("floci", reloaded.getTags().get("Owner"));
}
private JsonNode request(String json) throws Exception {
return objectMapper.readTree(json);
}
}
+4
View File
@@ -61,6 +61,8 @@ floci:
cloudfront:
appsync:
flush-interval-ms: 60000
rum:
flush-interval-ms: 60000
auth:
validate-signatures: false
@@ -285,3 +287,5 @@ floci:
port: 1883
iotdata:
enabled: true
rum:
enabled: true