Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambdaweb): publish the Web Function metrics (#5976)
TATSUNO “Taz” Yasuhiro6e5b1569fe16
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex f4d133ab8b..505358ef1d 100644--- a/docs/services/lambda-web-functions.md+++ b/docs/services/lambda-web-functions.md@@ -41,7 +41,7 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`.-- **Not implemented yet:** SigV4a on `MultiRegion` endpoints, the check that a policy's principal exists, the automatic deletion of revisions past 50, the metadata API, the metrics, and serving a `MultiRegion` or `PerRegion` endpoint in its other regions.+- **Not implemented yet:** SigV4a on `MultiRegion` endpoints, the check that a policy's principal exists, the automatic deletion of revisions past 50, the metadata API, and serving a `MultiRegion` or `PerRegion` endpoint in its other regions.### `aws lambda-web deploy`@@ -116,6 +116,20 @@ The platform writes the `platform.*` events of the [system log schema](https://dCPU time and memory come from the container's cgroup, read at each report. Floci cannot read them once the container has stopped, so the CPU time since the last reading is lost when the process exits on its own, an init that fails because the process exited reports neither, and `spinDownReport` has no CPU time. AWS reports the memory of its whole environment, so its numbers are higher.+## Metrics++Floci publishes the [Web Function metrics](https://docs.aws.amazon.com/lambda/latest/dg/web-functions-monitoring-metrics.html) to CloudWatch in the function's account and region:++| Namespace | Metrics | Dimensions | Datapoints |+| --- | --- | --- | --- |+| `AWS/Lambda/Web` | `ExecutedRequests` | `FunctionName`, `EndpointName` | 1 for each request that reached an environment, also one answered with `Runtime.OriginRequestError` or `Runtime.RequestTimeout` |+| `AWS/Lambda/Web` | `HTTPResponseStatusClass4XX`, `HTTPResponseStatusClass5XX` | `FunctionName`, `EndpointName` | 1 for each answer in the class, also the platform pages. The `400`, `404` and `505` pages are not counted, as on AWS. An answer cut after its head counts under the status it began with |+| `AWS/Lambda/Web` | `EnvironmentActiveTime`, `EnvironmentCPUTime`, `EnvironmentMaxMemoryUsage`, `EnvironmentConcurrentRequests`, `ResponseBytes` | `FunctionName` | One per environment at `initReport`, also when the init fails, and one with each `invokeSummary`, for the time since the previous one |+| `AWS/Lambda/Web/Usage` | `ExecutedRequests`, `EndpointActiveEnvironments` | `FunctionName`, `EndpointName`, `ExecutionRegion` | One for each request that reached an environment. `EndpointActiveEnvironments` is the number of environments of the endpoint, those that are starting included |+| `AWS/Lambda/Web/Usage` | `EndpointRequestThrottles`, `EndpointActiveEnvironmentThrottles` | `FunctionName`, `EndpointName`, `ExecutionRegion` | 1 for each `429` of the `rateLimit` or of `maxEnvironments` |++The account quotas are not applied, so `AccountRequestThrottles` and `AccountActiveVCPUArm64Throttles` never appear. CPU time and memory have the gaps of the platform events. The datapoints are stored on their own thread, and when 10,000 writes are waiting new ones are dropped with a warning in Floci's log.+## CloudFormation`AWS::Lambda::WebFunction`, `AWS::Lambda::WebFunctionRevision` and `AWS::Lambda::WebFunctionEndpoint` provision through the resource registry. `Ref` of each is its ARN. Every property of a revision is createOnly, so a changed revision mints a new one and the displaced revision is deleted once the update commits. An endpoint keeps its identity while its function, name, type and regions stay the same. A changed type or region list under the same name is refused the way CloudFormation refuses to replace a custom-named resource. `Fn::GetAtt` on `RegionalEndpoints` is not supported yet.diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricDatum.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricDatum.javaindex afabdc673c..53166829ca 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricDatum.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricDatum.java@@ -23,6 +23,21 @@ public class MetricDatum {public MetricDatum() {}+ /**+ * One value as a service publishes it. Only {@code putMetricData} turns a {@code timestamp} of 0+ * into the time it is stored.+ */+ public static MetricDatum of(String metricName, String unit, double value, List<Dimension> dimensions,+ long timestamp) {+ MetricDatum datum = new MetricDatum();+ datum.setMetricName(metricName);+ datum.setUnit(unit);+ datum.setValue(value);+ datum.setDimensions(dimensions);+ datum.setTimestamp(timestamp);+ return datum;+ }+public String getNamespace() { return namespace; }public void setNamespace(String namespace) { this.namespace = namespace; }diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlane.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlane.javaindex 95e002343b..a93581b81a 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlane.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlane.java@@ -73,6 +73,7 @@ public class LambdaWebDataPlane {private final LambdaWebService service;private final LambdaWebEnvironmentManager environments;private final LambdaWebIamAuth iamAuth;+ private final LambdaWebMetrics metrics;private final ServiceConfigAccess serviceConfigAccess;private final Vertx vertx;private final HttpClient client;@@ -80,10 +81,12 @@ public class LambdaWebDataPlane {@Injectpublic LambdaWebDataPlane(LambdaWebService service, LambdaWebEnvironmentManager environments,- LambdaWebIamAuth iamAuth, ServiceConfigAccess serviceConfigAccess, Vertx vertx) {+ LambdaWebIamAuth iamAuth, LambdaWebMetrics metrics,+ ServiceConfigAccess serviceConfigAccess, Vertx vertx) {this.service = service;this.environments = environments;this.iamAuth = iamAuth;+ this.metrics = metrics;this.serviceConfigAccess = serviceConfigAccess;this.vertx = vertx;this.client = vertx.createHttpClient(new HttpClientOptions()@@ -120,6 +123,7 @@ public class LambdaWebDataPlane {WebFunctionTarget target = located.get();Integer rateLimit = target.endpoint().throttleConfig == null ? null : target.endpoint().throttleConfig.rateLimit;if (Integer.valueOf(0).equals(rateLimit)) {+ metrics.answered(target, LambdaWebErrorPages.ENDPOINT_DISABLED.status());page(request, LambdaWebErrorPages.ENDPOINT_DISABLED, requestId, false);return;}@@ -138,9 +142,11 @@ public class LambdaWebDataPlane {request.resume();if (allowed.failed()) {LOG.errorv(allowed.cause(), "Could not check the caller of {0}", host);+ metrics.answered(target, 502);internalError(request, requestId);return;}+ metrics.answered(target, LambdaWebErrorPages.FORBIDDEN.status());page(request, LambdaWebErrorPages.FORBIDDEN, requestId, false);});}@@ -149,12 +155,14 @@ public class LambdaWebDataPlane {Integer rateLimit = target.endpoint().throttleConfig == null ? null : target.endpoint().throttleConfig.rateLimit;if (rateLimit != null && !rateLimiter.tryAcquire(endpointKey(target), rateLimit)) {request.resume();+ metrics.throttled(target, LambdaWebMetrics.REQUEST_THROTTLES);page(request, LambdaWebErrorPages.ENDPOINT_REQUEST_THROTTLE, requestId, false);return;}WebFunctionRevision revision = LambdaWebService.pickRevision(target);if (revision == null) {request.resume();+ metrics.answered(target, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR.status());page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);return;}@@ -186,14 +194,17 @@ public class LambdaWebDataPlane {.onFailure(error -> {request.resume();if (error instanceof StartFailure failure) {+ metrics.answered(target, failure.page().status());page(request, failure.page(), requestId, false);return;}if (error instanceof Throttled) {+ metrics.throttled(target, LambdaWebMetrics.ACTIVE_ENVIRONMENT_THROTTLES);page(request, LambdaWebErrorPages.ENDPOINT_MAX_ENV_THROTTLE, requestId, false);return;}LOG.errorv(error, "Could not start an environment for {0}", host);+ metrics.answered(target, 502);internalError(request, requestId);});}@@ -206,7 +217,7 @@ public class LambdaWebDataPlane {private void forward(HttpServerRequest request, String host, WebFunctionTarget target,WebFunctionRevision revision, Environment environment, String requestId, boolean firstTry) {long started = System.nanoTime();- Exchange exchange = new Exchange(request, environment, requestId, target.endpoint().endpointName, started);+ Exchange exchange = new Exchange(request, environment, requestId, target, started);boolean hasBody = hasRequestBody(request);AtomicBoolean bodyIn = new AtomicBoolean(!hasBody);AtomicBoolean expired = new AtomicBoolean();@@ -224,11 +235,11 @@ public class LambdaWebDataPlane {if (exchange.finish()) {upstream.reset();if (request.response().headWritten()) {- request.response().close();exchange.relayed(LambdaWebErrorPages.REQUEST_TIMEOUT.errorType());+ request.response().close();} else {- page(request, LambdaWebErrorPages.REQUEST_TIMEOUT, requestId, false);exchange.replaced(LambdaWebErrorPages.REQUEST_TIMEOUT);+ page(request, LambdaWebErrorPages.REQUEST_TIMEOUT, requestId, false);}}};@@ -252,8 +263,8 @@ public class LambdaWebDataPlane {environment.containerId(), requestId, error.toString());if (request.response().headWritten()) {if (exchange.finish()) {- request.response().close();exchange.relayed(null);+ request.response().close();}return;}@@ -289,8 +300,8 @@ public class LambdaWebDataPlane {return;}request.resume();- page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);exchange.replaced(LambdaWebErrorPages.ORIGIN_REQUEST_ERROR);+ page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);});}@@ -306,58 +317,64 @@ public class LambdaWebDataPlane {if (response.getHeader("Content-Length") == null && hasBody(request.method(), response.statusCode())) {out.setChunked(true);}- response.pipeTo(out).onComplete(piped -> {+ response.pipe().endOnSuccess(false).to(out).onComplete(piped -> {if (!exchange.finish()) {return;}if (piped.succeeded()) {exchange.relayed(null);+ out.end();return;}if (out.headWritten()) {- out.close();exchange.relayed(null);+ out.close();} else {- page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);exchange.replaced(LambdaWebErrorPages.ORIGIN_REQUEST_ERROR);+ page(request, LambdaWebErrorPages.ORIGIN_REQUEST_ERROR, requestId, false);}});}/*** One request against one environment. The first finisher releases the reservation and the deadline, and reports- * the request in {@code platform.requestComplete}.+ * the request in {@code platform.requestComplete} and the request metrics. Every answer is reported before its+ * last bytes go out, so a client that has the answer finds its metrics queued.*/private final class Exchange {private final HttpServerRequest request;private final Environment environment;private final String requestId;+ private final WebFunctionTarget target;private final String endpointName;private final long started;private final AtomicBoolean finished = new AtomicBoolean();private long deadline = -1;- Exchange(HttpServerRequest request, Environment environment, String requestId, String endpointName,+ Exchange(HttpServerRequest request, Environment environment, String requestId, WebFunctionTarget target,long started) {this.request = request;this.environment = environment;this.requestId = requestId;- this.endpointName = endpointName;+ this.target = target;+ this.endpointName = target.endpoint().endpointName;this.started = started;environment.exchangeOpened();}- /** The answer of the app, cut when {@code errorType} is set. */+ /** The answer of the app, cut when {@code errorType} is set. A cut answer counts under its first status. */void relayed(String errorType) {HttpServerResponse response = request.response();environment.requestComplete(requestId, endpointName, response.getStatusCode(), errorType,System.nanoTime() - started, response.bytesWritten());+ metrics.executed(target, response.getStatusCode(), environments.environmentCount(endpointKey(target)));}/** A page in place of the app's answer. AWS counts none of its bytes. */void replaced(LambdaWebErrorPages.Page page) {environment.requestComplete(requestId, endpointName, page.status(), page.errorType(),System.nanoTime() - started, 0);+ metrics.executed(target, page.status(), environments.environmentCount(endpointKey(target)));}boolean finish() {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.javaindex 22ef1ff2de..5ed5f4478c 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java@@ -107,6 +107,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {private static final int INIT_ERROR_MAX_BYTES = 64;/** Longer than the data plane waits to see an exit, so a request the exit failed is counted. */private static final Duration EXCHANGES_WAIT = Duration.ofSeconds(2);+ private static final Duration METRICS_WAIT = Duration.ofSeconds(5);/*** One container of an endpoint's pool. It joins the pool before it starts, so requests that@@ -265,6 +266,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {private final LaunchedContainerAwsEnv awsEnv;private final LambdaExecutionRoleCredentials executionRoleCredentials;private final LambdaWebLogs logs;+ private final LambdaWebMetrics metrics;private final byte[] runtime;/** The environments of each endpoint in each region. A list is only touched inside a map operation on its key. */private final ConcurrentHashMap<String, List<Environment>> pools = new ConcurrentHashMap<>();@@ -280,7 +282,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {@StreamingDocker DockerClient streamingDocker, ImageResolver imageResolver,EcrRegistryManager ecrRegistryManager, S3Service s3Service,ZipExtractor zipExtractor, LaunchedContainerAwsEnv awsEnv,- LambdaExecutionRoleCredentials executionRoleCredentials, LambdaWebLogs logs) {+ LambdaExecutionRoleCredentials executionRoleCredentials, LambdaWebLogs logs,+ LambdaWebMetrics metrics) {this.config = config;this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;@@ -292,6 +295,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {this.awsEnv = awsEnv;this.executionRoleCredentials = executionRoleCredentials;this.logs = logs;+ this.metrics = metrics;this.runtime = runtimeScript();long period = Math.max(1, Math.min(30, config.services().lambda().containerIdleTimeoutSeconds() / 2 + 1));reaper.scheduleWithFixedDelay(this::reapIdle, period, period, TimeUnit.SECONDS);@@ -370,6 +374,16 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {return new Pick(started, true, retired);}+ /** The live environments of the endpoint, also those that are starting. */+ int environmentCount(String endpointKey) {+ AtomicInteger count = new AtomicInteger();+ pools.computeIfPresent(endpointKey, (key, pool) -> {+ count.set((int) pool.stream().filter(Environment::isAlive).count());+ return pool;+ });+ return count.get();+ }+private static boolean isIdle(Environment environment, long idleNanos) {return environment.isAlive() && environment.isReady() && environment.inFlight.get() == 0&& System.nanoTime() - environment.lastUsed.get() >= idleNanos;@@ -476,6 +490,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {@Overridepublic void stopManagedContainers() {allEnvironments().forEach(this::discard);+ metrics.awaitPublished(METRICS_WAIT);}/** The live environment that writes {@code logStream}, the one a response names. */@@ -569,7 +584,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {environment.logs = logs.open(accountId, region, revision.serviceConfig.logGroup, environment.logStream,revision.serviceConfig.systemLogLevel);platform = new LambdaWebPlatformLog(environment.logs, region, fn.functionName, revision.revisionId,- revision.buildConfig.runtime, revision.serviceConfig.applicationLogLevel);+ revision.buildConfig.runtime, revision.serviceConfig.applicationLogLevel,+ metrics.environment(accountId, region, fn.functionName));environment.platformLog = platform;ContainerInfo info = lifecycleManager.startCreated(containerId, spec);platform.initStart();diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetrics.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetrics.javanew file mode 100644index 0000000000..6dee2600be--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetrics.java@@ -0,0 +1,191 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService.WebFunctionTarget;+import jakarta.annotation.PreDestroy;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Duration;+import java.time.Instant;+import java.util.ArrayList;+import java.util.List;+import java.util.UUID;+import java.util.concurrent.ArrayBlockingQueue;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Future;+import java.util.concurrent.RejectedExecutionException;+import java.util.concurrent.ThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;+import java.util.stream.Stream;++/**+ * The CloudWatch metrics of Web Functions: one datapoint per request when it is answered, and one+ * per environment when it starts, each minute and when it ends. Floci serves an endpoint in its+ * home region only, so both namespaces go there.+ */+@ApplicationScoped+public class LambdaWebMetrics {++ static final String NAMESPACE = "AWS/Lambda/Web";+ static final String USAGE_NAMESPACE = "AWS/Lambda/Web/Usage";+ static final String REQUEST_THROTTLES = "EndpointRequestThrottles";+ static final String ACTIVE_ENVIRONMENT_THROTTLES = "EndpointActiveEnvironmentThrottles";+ static final int MAX_QUEUED = 10_000;+ private static final Logger LOG = Logger.getLogger(LambdaWebMetrics.class);++ /** One datapoint of each environment metric, for the time since the previous one. */+ interface EnvironmentMetrics {+ void publish(long activeMillis, long cpuMillis, long maxMemoryMb, int concurrentRequests, long responseBytes);+ }++ private record Datapoint(String namespace, MetricDatum datum) {+ }++ private final CloudWatchMetricsService cloudWatch;+ /**+ * A persistent store writes to disk on each datapoint, which must not happen on the event loop.+ * The datapoints of one request or one window are one write. Once {@code maxQueued} writes wait,+ * new ones are dropped.+ */+ private final ThreadPoolExecutor publisher;+ /** The writes run one at a time in order, so once the last one is done all are. */+ private Future<?> lastWrite = CompletableFuture.completedFuture(null);+ private boolean dropping;++ @Inject+ public LambdaWebMetrics(CloudWatchMetricsService cloudWatch) {+ this(cloudWatch, MAX_QUEUED);+ }++ LambdaWebMetrics(CloudWatchMetricsService cloudWatch, int maxQueued) {+ this.cloudWatch = cloudWatch;+ this.publisher = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(maxQueued),+ task -> {+ Thread thread = new Thread(task, "lambda-web-metrics");+ thread.setDaemon(true);+ return thread;+ });+ }++ /** A request that reached an environment, with the status the caller got. */+ void executed(WebFunctionTarget target, int status, int activeEnvironments) {+ long now = Instant.now().getEpochSecond();+ List<Dimension> request = requestDimensions(target);+ List<Dimension> usage = usageDimensions(target);+ List<Datapoint> datapoints = new ArrayList<>();+ datapoints.add(new Datapoint(NAMESPACE, MetricDatum.of("ExecutedRequests", "Count", 1, request, now)));+ datapoints.add(new Datapoint(USAGE_NAMESPACE, MetricDatum.of("ExecutedRequests", "Count", 1, usage, now)));+ datapoints.add(new Datapoint(USAGE_NAMESPACE,+ MetricDatum.of("EndpointActiveEnvironments", "Count", activeEnvironments, usage, now)));+ statusClass(datapoints, status, request, now);+ publish(target.accountId(), target.region(), datapoints);+ }++ /** A request the platform answered without an environment. */+ void answered(WebFunctionTarget target, int status) {+ List<Datapoint> datapoints = new ArrayList<>();+ statusClass(datapoints, status, requestDimensions(target), Instant.now().getEpochSecond());+ publish(target.accountId(), target.region(), datapoints);+ }++ /** A request refused with 429. {@code metric} names the limit it hit. */+ void throttled(WebFunctionTarget target, String metric) {+ long now = Instant.now().getEpochSecond();+ List<Datapoint> datapoints = new ArrayList<>();+ datapoints.add(new Datapoint(USAGE_NAMESPACE,+ MetricDatum.of(metric, "Count", 1, usageDimensions(target), now)));+ statusClass(datapoints, 429, requestDimensions(target), now);+ publish(target.accountId(), target.region(), datapoints);+ }++ EnvironmentMetrics environment(String accountId, String region, String functionName) {+ List<Dimension> dimensions = List.of(new Dimension("FunctionName", functionName));+ return (activeMillis, cpuMillis, maxMemoryMb, concurrentRequests, responseBytes) -> {+ long now = Instant.now().getEpochSecond();+ publish(accountId, region, Stream.of(+ MetricDatum.of("EnvironmentActiveTime", "Milliseconds", activeMillis, dimensions, now),+ MetricDatum.of("EnvironmentCPUTime", "Milliseconds", cpuMillis, dimensions, now),+ MetricDatum.of("EnvironmentMaxMemoryUsage", "Megabytes", maxMemoryMb, dimensions, now),+ MetricDatum.of("EnvironmentConcurrentRequests", "Count", concurrentRequests, dimensions, now),+ MetricDatum.of("ResponseBytes", "Bytes", responseBytes, dimensions, now))+ .map(datum -> new Datapoint(NAMESPACE, datum)).toList());+ };+ }++ /** Waits until what is queued is stored, so the last flush of the store at shutdown has it. */+ void awaitPublished(Duration limit) {+ Future<?> last;+ synchronized (this) {+ last = lastWrite;+ }+ try {+ last.get(limit.toMillis(), TimeUnit.MILLISECONDS);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ } catch (ExecutionException | TimeoutException e) {+ LOG.warnv(e, "Lambda Web metrics still waiting to be stored may be lost");+ }+ }++ @PreDestroy+ void shutdown() {+ publisher.shutdown();+ }++ /** The status classes have no datapoint of 0. */+ private static void statusClass(List<Datapoint> datapoints, int status, List<Dimension> dimensions, long now) {+ if (400 <= status && status <= 499) {+ datapoints.add(new Datapoint(NAMESPACE,+ MetricDatum.of("HTTPResponseStatusClass4XX", "Count", 1, dimensions, now)));+ } else if (500 <= status && status <= 599) {+ datapoints.add(new Datapoint(NAMESPACE,+ MetricDatum.of("HTTPResponseStatusClass5XX", "Count", 1, dimensions, now)));+ }+ }++ private static List<Dimension> requestDimensions(WebFunctionTarget target) {+ return List.of(new Dimension("FunctionName", target.function().functionName),+ new Dimension("EndpointName", target.endpoint().endpointName));+ }++ private static List<Dimension> usageDimensions(WebFunctionTarget target) {+ return List.of(new Dimension("FunctionName", target.function().functionName),+ new Dimension("EndpointName", target.endpoint().endpointName),+ new Dimension("ExecutionRegion", target.region()));+ }++ private synchronized void publish(String accountId, String region, List<Datapoint> datapoints) {+ if (datapoints.isEmpty()) {+ return;+ }+ try {+ lastWrite = publisher.submit(() -> {+ for (Datapoint datapoint : datapoints) {+ store(accountId, region, datapoint);+ }+ });+ dropping = false;+ } catch (RejectedExecutionException rejected) {+ if (!publisher.isShutdown() && !dropping) {+ dropping = true;+ LOG.warnv("Dropping Lambda Web metrics while {0} writes wait", publisher.getQueue().size());+ }+ }+ }++ private void store(String accountId, String region, Datapoint datapoint) {+ try {+ cloudWatch.publishMetricForAccount(accountId, datapoint.namespace(), datapoint.datum(), region,+ UUID.randomUUID().toString());+ } catch (RuntimeException e) {+ LOG.warnv(e, "Could not publish {0} {1} in {2}", datapoint.namespace(), datapoint.datum().getMetricName(),+ region);+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLog.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLog.javaindex ec452e6fc7..64a92c8274 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLog.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLog.java@@ -6,15 +6,17 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import java.math.BigDecimal;import java.math.RoundingMode;+import java.time.Duration;import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;import java.util.UUID;/**- * The {@code platform.*} events of one environment. AWS reports the CPU time and the peak memory of- * the whole environment, which Floci reads from the container's cgroup. A reading that fails keeps- * the last one, so CPU time after the last reading is lost when the process exits on its own.+ * The {@code platform.*} events and the environment metrics of one environment. AWS reports the CPU+ * time and the peak memory of the whole environment, which Floci reads from the container's cgroup. A+ * reading that fails keeps the last one, so CPU time after the last reading is lost when the process+ * exits on its own.*/final class LambdaWebPlatformLog {@@ -35,12 +37,14 @@ final class LambdaWebPlatformLog {private final String revisionId;private final String runtime;private final String applicationLogLevel;+ private final LambdaWebMetrics.EnvironmentMetrics environmentMetrics;private final String instanceId = UUID.randomUUID().toString();private long initStarted;private long invokeStarted;private Instant windowStart;private int windowRequests;private int windowConcurrency;+ private long windowBytes;private int totalRequests;private int totalConcurrency;private long cpuMicros;@@ -51,13 +55,15 @@ final class LambdaWebPlatformLog {private boolean ended;LambdaWebPlatformLog(LambdaWebLogs.Sink sink, String region, String functionName, String revisionId,- String runtime, String applicationLogLevel) {+ String runtime, String applicationLogLevel,+ LambdaWebMetrics.EnvironmentMetrics environmentMetrics) {this.sink = sink;this.region = region;this.functionName = functionName;this.revisionId = revisionId;this.runtime = runtime;this.applicationLogLevel = applicationLogLevel;+ this.environmentMetrics = environmentMetrics;}synchronized void initStart() {@@ -76,14 +82,16 @@ final class LambdaWebPlatformLog {/** {@code errorType} is null when the app listens. */synchronized void initReport(String errorType, Usage usage) {read(usage);+ long initNanos = System.nanoTime() - initStarted;ObjectNode record = status(errorType);record.put("instanceId", instanceId);record.put("initializationType", INIT_TYPE);ObjectNode metrics = record.putObject("metrics");- metrics.put("totalDurationMs", wholeMillis(System.nanoTime() - initStarted));+ metrics.put("totalDurationMs", wholeMillis(initNanos));metrics.put("totalCpuTimeMs", wholeMillis(cpuMicros * 1000));metrics.put("maxMemoryUsageMb", peakMemoryMb);sink.platform(Instant.now(), errorType == null ? "INFO" : "WARN", "platform.initReport", record);+ environmentMetrics.publish(millis(initNanos), millis(cpuMicros * 1000), peakMemoryMb, 0, 0);}/** A failure AWS writes in the shape of console output, with the time as Node prints it, and drops at FATAL. */@@ -129,6 +137,7 @@ final class LambdaWebPlatformLog {long durationNanos, long responseBytes) {windowRequests++;totalRequests++;+ windowBytes += responseBytes;ObjectNode record = JSON.createObjectNode();record.put("requestId", requestId);record.put("endpointName", endpointName);@@ -159,8 +168,11 @@ final class LambdaWebPlatformLog {metrics.put("cpuTimeMs", wholeMillis((cpuMicros - cpuAtWindowStart) * 1000));metrics.put("maxMemoryUsageMb", peakMemoryMb);sink.platform(now, "INFO", "platform.invokeSummary", record);+ environmentMetrics.publish(Duration.between(windowStart, now).toMillis(),+ millis((cpuMicros - cpuAtWindowStart) * 1000), peakMemoryMb, windowConcurrency, windowBytes);windowStart = now;windowRequests = 0;+ windowBytes = 0;windowConcurrency = inFlight;cpuAtWindowStart = cpuMicros;}@@ -218,8 +230,12 @@ final class LambdaWebPlatformLog {return record;}+ private static long millis(long nanos) {+ return Math.round(nanos / 1_000_000.0);+ }+/** AWS writes these durations in whole milliseconds with three decimals. */private static BigDecimal wholeMillis(long nanos) {- return BigDecimal.valueOf(Math.round(nanos / 1_000_000.0)).setScale(3);+ return BigDecimal.valueOf(millis(nanos)).setScale(3);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.javaindex ff49d17364..055adb7edd 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java@@ -4672,12 +4672,9 @@ public class RdsService implements Resettable, ResourceProvider {private void publishZeroCapacity(String accountId, String region, Dimension dimension, Instant at) {for (String metricName : List.of("ServerlessDatabaseCapacity", "ACUUtilization", "CPUUtilization")) {- MetricDatum datum = new MetricDatum();- datum.setMetricName(metricName);- datum.setUnit("ServerlessDatabaseCapacity".equals(metricName) ? "Count" : "Percent");- datum.setDimensions(List.of(dimension));- datum.setTimestamp(at.getEpochSecond());- datum.setValue(0.0);+ MetricDatum datum = MetricDatum.of(metricName,+ "ServerlessDatabaseCapacity".equals(metricName) ? "Count" : "Percent", 0.0, List.of(dimension),+ at.getEpochSecond());metricsService.publishMetricForAccount(accountId, "AWS/RDS", datum, region,"rds-auto-pause:" + dimension.name() + "=" + dimension.value() + ":" + metricName + ":" + at);}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.javaindex d912eca4d4..5bd6cbc13f 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java@@ -294,14 +294,10 @@ public class SesEventPublisher {dimensions.add(new Dimension(cfg.getDimensionName(), value));}}- MetricDatum datum = new MetricDatum();- datum.setNamespace(SES_METRIC_NAMESPACE);- datum.setMetricName(SesEventPayload.cloudWatchMetricName(eventType));- datum.setValue(1.0);- datum.setUnit("Count");- datum.setDimensions(dimensions);- // Leave timestamp unset: CloudWatchMetricsService.putMetricData defaults a zero- // timestamp to Instant.now().getEpochSecond() (epoch seconds, not milliseconds).+ // A zero timestamp: CloudWatchMetricsService.putMetricData defaults it to+ // Instant.now().getEpochSecond() (epoch seconds, not milliseconds).+ MetricDatum datum = MetricDatum.of(SesEventPayload.cloudWatchMetricName(eventType), "Count", 1.0,+ dimensions, 0);try {cloudWatchMetricsService.putMetricData(SES_METRIC_NAMESPACE, List.of(datum),defaultRegion);diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.javaindex 5546cb22ca..902ecdb933 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java@@ -116,6 +116,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {@InjectLambdaWebEnvironmentManager environments;+ @Inject+ LambdaWebMetrics metrics;+private String functionName;@BeforeAll@@ -333,6 +336,13 @@ class LambdaWebDataPlaneDockerIntegrationTest {assertTrue(response.contains("\r\nlambda-web-error-type: Platform.EndpointMaxEnvThrottle\r\n"), response);assertTrue(response.contains("<p>Request rate exceeded. Please try again later.</p>"), response);}+ Map<String, String> usage = Map.of("FunctionName", functionName, "EndpointName", "dev",+ "ExecutionRegion", "us-east-1");+ metrics.awaitPublished(Duration.ofSeconds(5));+ assertEquals(3, LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE,+ "EndpointActiveEnvironmentThrottles", usage, "Sum"));+ assertEquals(2, LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE, "EndpointActiveEnvironments",+ usage, "Maximum"));// Requests one after another rotate over the two environments.Set<String> logStreams = new HashSet<>();@@ -381,6 +391,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {for (String response : limited) {assertTrue(response.contains("\r\nlambda-web-error-type: Platform.EndpointRequestThrottle\r\n"), response);}+ metrics.awaitPublished(Duration.ofSeconds(5));+ assertEquals(limited.size(), LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE,+ "EndpointRequestThrottles", usage, "Sum"));}private static List<String> parallel(int count, Callable<String> call) throws Exception {@@ -476,8 +489,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {assertEquals(2, crashReport.getInt("record.metrics.totalRequests"));assertEquals("success", platformEvent(crash, "platform.spinDownReport").getString("record.status"));- String stopped = given().header("Host", domain).when().get("/").then().statusCode(200)- .extract().header("lambda-web-logstream");+ Response echoed = given().header("Host", domain).when().get("/");+ echoed.then().statusCode(200);+ String stopped = echoed.header("lambda-web-logstream");environments.discard(environments.environmentOf(stopped));List<String> stop = awaitLogEvents(group, stopped, events -> types(events).contains("platform.spinDownReport"));assertEquals(List.of("platform.initStart", "platform.initReport", "platform.invokeStart",@@ -489,6 +503,30 @@ class LambdaWebDataPlaneDockerIntegrationTest {assertEquals(1, stopReport.getInt("record.metrics.totalRequests"));assertEquals(1, platformEvent(stop, "platform.invokeSummary").getInt("record.metrics.requests"));assertEquals("success", platformEvent(stop, "platform.spinDownReport").getString("record.status"));++ // Each environment has a datapoint at init and one when it ends, with the body bytes of its requests.+ Map<String, String> function = Map.of("FunctionName", functionName);+ Map<String, String> endpoint = Map.of("FunctionName", functionName, "EndpointName", "dev");+ Map<String, String> usage = Map.of("FunctionName", functionName, "EndpointName", "dev",+ "ExecutionRegion", "us-east-1");+ metrics.awaitPublished(Duration.ofSeconds(5));+ assertEquals(4, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "EnvironmentActiveTime", function,+ "SampleCount"));+ assertEquals(11 + echoed.asByteArray().length, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE,+ "ResponseBytes", function, "Sum"));+ assertEquals(1, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "EnvironmentConcurrentRequests",+ function, "Maximum"));+ assertTrue(LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "EnvironmentMaxMemoryUsage", function,+ "Maximum") > 0);+ assertEquals(3, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "ExecutedRequests", endpoint, "Sum"));+ assertEquals(1, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "HTTPResponseStatusClass5XX",+ endpoint, "Sum"));+ assertEquals(0, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "HTTPResponseStatusClass4XX",+ endpoint, "Sum"));+ assertEquals(3, LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE, "ExecutedRequests", usage,+ "Sum"));+ assertEquals(3, LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE, "EndpointActiveEnvironments",+ usage, "SampleCount"));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.javaindex 3dddfc80b6..079cf36023 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.java@@ -12,6 +12,7 @@ import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.nio.charset.StandardCharsets;+import java.time.Duration;import java.util.Map;import static io.restassured.RestAssured.given;@@ -34,6 +35,9 @@ class LambdaWebDataPlaneIntegrationTest {@InjectS3Service s3Service;+ @Inject+ LambdaWebMetrics metrics;+@Testvoid anUnknownEndpointDomainIsNotFound() {Response response = given().header("Host", UNKNOWN_HOST).when().get("/some/path?q=1");@@ -133,6 +137,34 @@ class LambdaWebDataPlaneIntegrationTest {given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);}+ @Test+ void aPageWithoutAnEnvironmentCountsOnlyItsStatusClass() {+ String functionName = "dp-metrics-" + Long.toString(System.nanoTime(), 36);+ String domain = createFunction(functionName, "IamAuth");+ given().header("Host", domain).when().get("/").then().statusCode(403);+ given().header("Host", domain).when().get("/").then().statusCode(403);+ given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 0}}")+ .when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")+ .then().statusCode(202);+ given().header("Host", domain).when().get("/").then().statusCode(503);++ Map<String, String> endpoint = Map.of("FunctionName", functionName, "EndpointName", "dev");+ Map<String, String> usage = Map.of("FunctionName", functionName, "EndpointName", "dev",+ "ExecutionRegion", "us-east-1");+ metrics.awaitPublished(Duration.ofSeconds(5));+ assertEquals(2, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "HTTPResponseStatusClass4XX",+ endpoint, "Sum"));+ assertEquals(1, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "HTTPResponseStatusClass5XX",+ endpoint, "Sum"));+ assertEquals(0, LambdaWebMetricStatistics.of(LambdaWebMetrics.NAMESPACE, "ExecutedRequests", endpoint, "Sum"));+ assertEquals(0, LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE, "ExecutedRequests", usage,+ "Sum"));+ assertEquals(0, LambdaWebMetricStatistics.of(LambdaWebMetrics.USAGE_NAMESPACE, "EndpointActiveEnvironments",+ usage, "SampleCount"));++ given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);+ }+@Testvoid httpOneDotZeroIsRefused() throws IOException {String response = raw("GET / HTTP/1.0\r\nHost: " + UNKNOWN_HOST + "\r\n\r\n");diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetricStatistics.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetricStatistics.javanew file mode 100644index 0000000000..02ba0c4f60--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetricStatistics.java@@ -0,0 +1,40 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.restassured.path.json.JsonPath;++import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;++import static io.restassured.RestAssured.given;++/** Reads Web Function metrics back with GetMetricStatistics, as a client does. */+final class LambdaWebMetricStatistics {++ private LambdaWebMetricStatistics() {+ }++ /** {@code Sum} and {@code SampleCount} add up over the periods, {@code Maximum} is the largest. */+ static double of(String namespace, String metric, Map<String, String> dimensions, String statistic) {+ RestAssuredJsonUtils.configureAwsContentTypes();+ Instant now = Instant.now();+ String filter = dimensions.entrySet().stream()+ .map(each -> "{\"Name\":\"" + each.getKey() + "\",\"Value\":\"" + each.getValue() + "\"}")+ .collect(Collectors.joining(","));+ JsonPath result = given().contentType("application/x-amz-json-1.0")+ .header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics")+ .body("{\"Namespace\":\"" + namespace + "\",\"MetricName\":\"" + metric + "\",\"Dimensions\":[" + filter+ + "],\"StartTime\":" + now.minusSeconds(600).getEpochSecond() + ",\"EndTime\":"+ + now.plusSeconds(60).getEpochSecond() + ",\"Period\":60,\"Statistics\":[\"" + statistic + "\"]}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath();+ List<Float> values = result.getList("Datapoints." + statistic, Float.class);+ if ("Maximum".equals(statistic)) {+ return values.stream().mapToDouble(Float::doubleValue).max().orElse(0);+ }+ return values.stream().mapToDouble(Float::doubleValue).sum();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetricsTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetricsTest.javanew file mode 100644index 0000000000..3944469aed--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebMetricsTest.java@@ -0,0 +1,155 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService.WebFunctionTarget;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import java.time.Duration;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.TimeUnit;+import java.util.stream.Collectors;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;++@ExtendWith(MockitoExtension.class)+class LambdaWebMetricsTest {++ private static final String ACCOUNT = "111122223333";+ private static final String REGION = "eu-west-1";++ @Mock+ CloudWatchMetricsService cloudWatch;++ private LambdaWebMetrics metrics;+ private WebFunctionTarget target;++ @BeforeEach+ void start() {+ metrics = new LambdaWebMetrics(cloudWatch);+ WebFunction function = new WebFunction();+ function.functionName = "web";+ WebFunctionEndpoint endpoint = new WebFunctionEndpoint();+ endpoint.endpointName = "dev";+ target = new WebFunctionTarget(ACCOUNT, REGION, function, endpoint);+ }++ @AfterEach+ void stop() {+ metrics.shutdown();+ }++ @Test+ void anExecutedRequestCountsInBothNamespacesWithItsStatusClass() {+ metrics.executed(target, 404, 3);++ assertEquals(List.of(+ "AWS/Lambda/Web ExecutedRequests FunctionName=web,EndpointName=dev 1.0 Count",+ "AWS/Lambda/Web HTTPResponseStatusClass4XX FunctionName=web,EndpointName=dev 1.0 Count",+ "AWS/Lambda/Web/Usage EndpointActiveEnvironments FunctionName=web,EndpointName=dev,ExecutionRegion=eu-west-1"+ + " 3.0 Count",+ "AWS/Lambda/Web/Usage ExecutedRequests FunctionName=web,EndpointName=dev,ExecutionRegion=eu-west-1"+ + " 1.0 Count"),+ published(4));+ }++ @Test+ void aSuccessHasNoStatusClassAndAPlatformAnswerOnlyItsStatusClass() {+ metrics.executed(target, 302, 1);+ metrics.answered(target, 503);++ assertEquals(List.of(+ "AWS/Lambda/Web ExecutedRequests FunctionName=web,EndpointName=dev 1.0 Count",+ "AWS/Lambda/Web HTTPResponseStatusClass5XX FunctionName=web,EndpointName=dev 1.0 Count",+ "AWS/Lambda/Web/Usage EndpointActiveEnvironments FunctionName=web,EndpointName=dev,ExecutionRegion=eu-west-1"+ + " 1.0 Count",+ "AWS/Lambda/Web/Usage ExecutedRequests FunctionName=web,EndpointName=dev,ExecutionRegion=eu-west-1"+ + " 1.0 Count"),+ published(4));+ }++ @Test+ void aThrottledRequestCountsTheLimitItHitAndA4xx() {+ metrics.throttled(target, LambdaWebMetrics.ACTIVE_ENVIRONMENT_THROTTLES);++ assertEquals(List.of(+ "AWS/Lambda/Web HTTPResponseStatusClass4XX FunctionName=web,EndpointName=dev 1.0 Count",+ "AWS/Lambda/Web/Usage EndpointActiveEnvironmentThrottles"+ + " FunctionName=web,EndpointName=dev,ExecutionRegion=eu-west-1 1.0 Count"),+ published(2));+ }++ @Test+ void anEnvironmentPublishesEachMetricByFunctionName() {+ metrics.environment(ACCOUNT, REGION, "web").publish(244, 178, 142, 2, 37);++ assertEquals(List.of(+ "AWS/Lambda/Web EnvironmentActiveTime FunctionName=web 244.0 Milliseconds",+ "AWS/Lambda/Web EnvironmentCPUTime FunctionName=web 178.0 Milliseconds",+ "AWS/Lambda/Web EnvironmentConcurrentRequests FunctionName=web 2.0 Count",+ "AWS/Lambda/Web EnvironmentMaxMemoryUsage FunctionName=web 142.0 Megabytes",+ "AWS/Lambda/Web ResponseBytes FunctionName=web 37.0 Bytes"),+ published(5));+ }++ @Test+ void writesPastTheQueueLimitAreDroppedAndTheRestAreStoredBeforeTheWaitEnds() throws InterruptedException {+ metrics.shutdown();+ metrics = new LambdaWebMetrics(cloudWatch, 2);+ CountDownLatch writing = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ doAnswer(invocation -> {+ writing.countDown();+ release.await(5, TimeUnit.SECONDS);+ return null;+ }).doNothing().when(cloudWatch).publishMetricForAccount(eq(ACCOUNT), anyString(), any(MetricDatum.class),+ eq(REGION), anyString());++ metrics.answered(target, 500);+ assertTrue(writing.await(5, TimeUnit.SECONDS));+ for (int i = 0; i < 4; i++) {+ metrics.answered(target, 500);+ }+ // The wait starts while the queue is still full.+ CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS).execute(release::countDown);+ metrics.awaitPublished(Duration.ofSeconds(5));++ verify(cloudWatch, times(3)).publishMetricForAccount(eq(ACCOUNT), anyString(), any(MetricDatum.class),+ eq(REGION), anyString());+ }++ private List<String> published(int count) {+ ArgumentCaptor<String> namespaces = ArgumentCaptor.forClass(String.class);+ ArgumentCaptor<MetricDatum> datums = ArgumentCaptor.forClass(MetricDatum.class);+ metrics.awaitPublished(Duration.ofSeconds(5));+ verify(cloudWatch, times(count)).publishMetricForAccount(eq(ACCOUNT), namespaces.capture(),+ datums.capture(), eq(REGION), anyString());+ List<String> published = new ArrayList<>();+ for (int i = 0; i < count; i++) {+ MetricDatum datum = datums.getAllValues().get(i);+ published.add(namespaces.getAllValues().get(i) + " " + datum.getMetricName() + " "+ + datum.getDimensions().stream().map(each -> each.name() + "=" + each.value())+ .collect(Collectors.joining(",")) + " " + datum.getValue() + " " + datum.getUnit());+ }+ published.sort(null);+ return published;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLogTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLogTest.javaindex 4add17135a..cda7bc141e 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLogTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPlatformLogTest.java@@ -11,6 +11,7 @@ import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import java.time.Instant;+import java.util.ArrayList;import java.util.List;import java.util.Map;@@ -30,6 +31,7 @@ class LambdaWebPlatformLogTest {CloudWatchLogsService cloudWatchLogs;private LambdaWebLogs logs;+ private final List<List<Long>> datapoints = new ArrayList<>();@BeforeEachvoid start() {@@ -54,7 +56,7 @@ class LambdaWebPlatformLogTest {void aRequestIsReportedWithItsDurationInMillisecondsToThreeDecimals() {LambdaWebPlatformLog platform = new LambdaWebPlatformLog(logs.open("111122223333", "eu-west-1", GROUP, STREAM, "DEBUG"), "eu-west-1", "web", "rev-abcde",- "nodejs24.x", "INFO");+ "nodejs24.x", "INFO", this::datapoint);platform.requestComplete("KXH25FBDZ33GP4TQ4ARAUYSTSA", "dev", 504, "Runtime.RequestTimeout", 3_000_716_400L, 0);@@ -70,7 +72,7 @@ class LambdaWebPlatformLogTest {void eventsBelowTheSystemLogLevelAreDroppedAndAFailedReportIsWarn() {LambdaWebPlatformLog platform = new LambdaWebPlatformLog(logs.open("111122223333", "eu-west-1", GROUP, STREAM, "WARN"), "eu-west-1", "web", "rev-abcde",- "nodejs24.x", "INFO");+ "nodejs24.x", "INFO", this::datapoint);platform.initStart();platform.initReport(null, new LambdaWebPlatformLog.Usage(178_400, 142L * 1024 * 1024 + 5));platform.invokeStart(1);@@ -91,7 +93,7 @@ class LambdaWebPlatformLogTest {void theListenFailureIsDroppedAtFatal() {LambdaWebPlatformLog platform = new LambdaWebPlatformLog(logs.open("111122223333", "eu-west-1", GROUP, STREAM, "DEBUG"), "eu-west-1", "web", "rev-abcde",- "nodejs24.x", "FATAL");+ "nodejs24.x", "FATAL", this::datapoint);platform.applicationError("Application.TimeoutListenError: nothing was listening");platform.spinDownStart();@@ -99,6 +101,44 @@ class LambdaWebPlatformLogTest {assertEquals("platform.spinDownStart", JsonPath.from(firstMessage()).getString("type"));}+ @Test+ void anEnvironmentPublishesItsMetricsAtInitAndForEachWindowWhateverTheSystemLogLevel() {+ LambdaWebPlatformLog platform = new LambdaWebPlatformLog(+ logs.open("111122223333", "eu-west-1", GROUP, STREAM, "WARN"), "eu-west-1", "web", "rev-abcde",+ "nodejs24.x", "INFO", this::datapoint);+ platform.initStart();+ platform.initReport(null, new LambdaWebPlatformLog.Usage(178_400, 142L * 1024 * 1024 + 5));+ platform.invokeStart(1);+ platform.concurrency(2);+ platform.requestComplete("KXH25FBDZ33GP4TQ4ARAUYSTSA", "dev", 200, null, 1_000_000, 18);+ platform.requestComplete("Q2TRUVQ6VJ5RQHBA4ZKSBWQO7A", "dev", 503, "Runtime.OriginRequestError", 1_000_000, 0);+ platform.invokeSummary(new LambdaWebPlatformLog.Usage(250_000, 150L * 1024 * 1024), 1);+ platform.end(null, "Runtime.ExitError");+ platform.invokeSummary(new LambdaWebPlatformLog.Usage(300_000, 150L * 1024 * 1024), 0);++ assertEquals(3, datapoints.size(), datapoints.toString());+ assertEquals(List.of(178L, 142L, 0L, 0L), datapoints.get(0).subList(1, 5));+ assertEquals(List.of(72L, 150L, 2L, 18L), datapoints.get(1).subList(1, 5));+ assertEquals(List.of(0L, 150L, 1L, 0L), datapoints.get(2).subList(1, 5));+ }++ @Test+ void aFailedInitPublishesOneDatapoint() {+ LambdaWebPlatformLog platform = new LambdaWebPlatformLog(+ logs.open("111122223333", "eu-west-1", GROUP, STREAM, "INFO"), "eu-west-1", "web", "rev-abcde",+ "nodejs24.x", "INFO", this::datapoint);+ platform.initStart();+ platform.initReport("Runtime.ExitError", null);++ assertEquals(1, datapoints.size(), datapoints.toString());+ assertEquals(List.of(0L, 0L, 0L, 0L), datapoints.getFirst().subList(1, 5));+ }++ private void datapoint(long activeMillis, long cpuMillis, long maxMemoryMb, int concurrentRequests,+ long responseBytes) {+ datapoints.add(List.of(activeMillis, cpuMillis, maxMemoryMb, (long) concurrentRequests, responseBytes));+ }+@SuppressWarnings("unchecked")private String firstMessage() {ArgumentCaptor<List<Map<String, Object>>> batch = ArgumentCaptor.forClass(List.class);