feat(lambdaweb): publish the Web Function metrics (#5976)

* feat(lambdaweb): publish the Web Function metrics to CloudWatch

AWS counts a request that reached an environment in ExecutedRequests, also one answered with
Runtime.OriginRequestError or Runtime.RequestTimeout. The status classes count the platform pages too,
except the 400, 404 and 505 pages. Each environment has a datapoint at init, also a failed one, then
one each minute and one when it ends.

* fix(lambdaweb): bound the waiting metric writes and store them before shutdown

* fix(lambdaweb): report each answer before it goes out and build datapoints with MetricDatum.of

A test can then wait for the publisher once and read the metrics without polling. RDS and SES build
their datapoints with the same factory.

* fix(lambdaweb): wait for the metric writes even when their queue is full

The wait now takes the last accepted write instead of a slot in the queue.
The writes run one at a time in order, so once it is done all are.
Only PutMetricData stores a zero timestamp as the current time, so the
MetricDatum.of comment says so.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-19 10:22:15 -04:00
1 parent e06013e1fe
commit 6e5b1569fe
13 files changed
+608 -41

No files matched your search

@@ -116,6 +116,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {
@Inject
LambdaWebEnvironmentManager 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"));
}
@Test
@@ -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 {
@Inject
S3Service s3Service;
@Inject
LambdaWebMetrics metrics;
@Test
void 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);
}
@Test
void httpOneDotZeroIsRefused() throws IOException {
String response = raw("GET / HTTP/1.0\r\nHost: " + UNKNOWN_HOST + "\r\n\r\n");
@@ -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();
}
}
@@ -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;
}
}
@@ -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<>();
@BeforeEach
void 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);