feat(lambdaweb): write the platform events of Web Function environments (#5936)

* feat(lambdaweb): write the platform events of Web Function environments

Each environment now writes the platform.* events AWS writes, filtered by the revision's systemLogLevel. CPU time and memory come from the container's cgroup. The output of an environment that fails before it listens reaches its stream too. Node runs under Docker's init, so a server without a SIGTERM handler stops at once, as on AWS where it is not PID 1. The server has 9 seconds to listen, as the AWS TimeoutListenError message says.

* fix(lambdaweb): settle the platform events of an environment that ends early

The last reports wait for the requests the exit failed, so they are counted. A periodic summary comes no more after the last report. An exit right after the app listens is handled as an exit. The CPU time counts on a host without memory.peak. The listen failure event is dropped at applicationLogLevel FATAL, as on AWS.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-18 11:09:24 -04:00
1 parent 356c79e78e
commit 301ac79c6e
8 files changed
+824 -37

No files matched your search

@@ -34,6 +34,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -64,6 +65,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {
const http = require('node:http');
const [host, port] = process.env.AWS_LAMBDA_HTTP_ENDPOINT.split(':');
console.log('starting');
if (process.env.MODE === 'throw') { throw new Error('init boom'); }
http.createServer((req, res) => {
if (req.url.startsWith('/log')) {
console.info({route: 'log', main: require.main === module, argv: process.argv.slice(1)});
@@ -209,7 +211,10 @@ class LambdaWebDataPlaneDockerIntegrationTest {
String logStream = logged.header("lambda-web-logstream");
String group = "/aws/lambda/web/" + functionName;
List<String> local = awaitLogEvents(group + ".local", logStream);
List<String> all = awaitLogEvents(group + ".local", logStream);
assertEquals(List.of("platform.initStart", "platform.initReport", "platform.invokeStart"),
types(all), all.toString());
List<String> local = all.stream().filter(event -> !isPlatformEvent(event)).toList();
assertEquals(5, local.size(), local.toString());
JsonPath starting = JsonPath.from(local.getFirst());
assertEquals("INFO", starting.getString("level"));
@@ -229,7 +234,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {
assertTrue(local.stream().allMatch(event -> event.endsWith("\n")), local.toString());
List<String> centralized = awaitLogEvents(group, logStream + "-000000000000-us-east-1");
assertEquals(new HashSet<>(local), new HashSet<>(centralized));
assertEquals(new HashSet<>(all), new HashSet<>(centralized));
}
@Test
@@ -398,6 +403,11 @@ class LambdaWebDataPlaneDockerIntegrationTest {
}
private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment) throws IOException {
return createFunction(timeoutSeconds, maxConcurrencyPerEnvironment, "INFO", "serve");
}
private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment, String systemLogLevel,
String mode) throws IOException {
functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());
@@ -409,16 +419,136 @@ class LambdaWebDataPlaneDockerIntegrationTest {
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": %d,
"maxConcurrencyPerEnvironment": %d,
"environmentVariables": {"CUSTOM": "yes"}}},
"environmentVariables": {"CUSTOM": "yes", "MODE": "%s"},
"telemetryConfig": {"loggingConfig": {"systemLogLevel": "%s"}}}},
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
""".formatted(functionName, BUCKET, functionName, ROLE, timeoutSeconds,
maxConcurrencyPerEnvironment))
maxConcurrencyPerEnvironment, mode, systemLogLevel))
.when().put(BASE + "/web-functions")
.then().statusCode(202)
.extract().path("endpoint.domainName");
}
@Test
@Timeout(180)
void platformEventsFollowAnEnvironmentFromItsStartToItsEnd() throws Exception {
String domain = createFunction(30, 64, "DEBUG", "serve");
String group = "/aws/lambda/web/" + functionName + ".local";
Response served = given().header("Host", domain).when().get("/status/201");
served.then().statusCode(201);
String crashed = served.header("lambda-web-logstream");
given().header("Host", domain).when().get("/crash").then().statusCode(503);
List<String> crash = awaitLogEvents(group, crashed, events -> types(events).contains("platform.spinDownReport")
&& types(events).stream().filter("platform.requestComplete"::equals).count() == 2);
JsonPath initStart = platformEvent(crash, "platform.initStart");
String instanceId = initStart.getString("record.instanceId");
assertEquals("INFO", initStart.getString("level"));
assertEquals("us-east-1", initStart.getString("region"));
assertEquals(functionName, initStart.getString("record.functionName"));
assertEquals("nodejs24.x:nodejs.web24.v30", initStart.getString("record.runtimeVersion"));
assertEquals("arn:aws:lambda:us-east-1::runtime/nodejs24.x/version/nodejs.web24.v30",
initStart.getString("record.runtimeVersionArn"));
assertEquals("native-http", initStart.getString("record.initializationType"));
JsonPath initReport = platformEvent(crash, "platform.initReport");
assertEquals("success", initReport.getString("record.status"));
assertEquals(instanceId, initReport.getString("record.instanceId"));
assertTrue(initReport.getInt("record.metrics.maxMemoryUsageMb") > 0, initReport.prettify());
List<JsonPath> requests = crash.stream().filter(event -> event.contains("platform.requestComplete"))
.map(JsonPath::from).toList();
assertEquals(2, requests.size(), crash.toString());
JsonPath ok = requests.stream().filter(event -> event.getInt("record.result") == 201).findFirst().orElseThrow();
assertEquals("DEBUG", ok.getString("level"));
assertEquals(served.header("lambda-web-request-id"), ok.getString("record.requestId"));
assertEquals("dev", ok.getString("record.endpointName"));
assertEquals(11, ok.getInt("record.metrics.responseBytes"));
assertFalse(ok.getMap("record").containsKey("errorType"), ok.prettify());
JsonPath failed = requests.stream().filter(event -> event.getInt("record.result") == 503).findFirst().orElseThrow();
assertEquals("Runtime.OriginRequestError", failed.getString("record.errorType"));
assertEquals(0, failed.getInt("record.metrics.responseBytes"));
JsonPath crashReport = platformEvent(crash, "platform.invokeReport");
assertEquals("WARN", crashReport.getString("level"));
assertEquals("failure", crashReport.getString("record.status"));
assertEquals("Runtime.ExitError", crashReport.getString("record.errorType"));
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");
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",
"platform.requestComplete", "platform.invokeSummary", "platform.invokeReport",
"platform.spinDownStart", "platform.spinDownReport"), types(stop), stop.toString());
JsonPath stopReport = platformEvent(stop, "platform.invokeReport");
assertEquals("INFO", stopReport.getString("level"));
assertEquals("success", stopReport.getString("record.status"));
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"));
}
@Test
@Timeout(180)
void anAppThatFailsAtImportWritesItsOutputAndAFailedInitReport() throws Exception {
String domain = createFunction(30, 64, "WARN", "throw");
String group = "/aws/lambda/web/" + functionName + ".local";
given().header("Host", domain).when().get("/").then().statusCode(502)
.header("lambda-web-error-type", "Application.InitCodeError");
List<String> events = awaitLogEvents(group, awaitLogStream(group), each -> types(each).contains(
"platform.initReport") && each.stream().anyMatch(event -> event.contains("init boom")));
assertEquals(List.of("platform.initReport"), types(events), events.toString());
JsonPath initReport = platformEvent(events, "platform.initReport");
assertEquals("WARN", initReport.getString("level"));
assertEquals("failure", initReport.getString("record.status"));
assertEquals("Application.InitCodeError", initReport.getString("record.errorType"));
assertTrue(events.stream().anyMatch(event -> event.contains("\"message\":\"starting\"")), events.toString());
assertTrue(events.stream().anyMatch(event -> event.contains("init boom")), events.toString());
}
private static boolean isPlatformEvent(String event) {
return event.startsWith("{") && event.contains("\"type\":\"platform.");
}
private static List<String> types(List<String> events) {
return events.stream().filter(LambdaWebDataPlaneDockerIntegrationTest::isPlatformEvent)
.map(event -> JsonPath.from(event).getString("type")).toList();
}
private static JsonPath platformEvent(List<String> events, String type) {
return events.stream().filter(LambdaWebDataPlaneDockerIntegrationTest::isPlatformEvent)
.map(JsonPath::from).filter(event -> type.equals(event.getString("type")))
.findFirst().orElseThrow(() -> new AssertionError("No " + type + " in " + events));
}
/** The messages of a log stream once they are {@code complete}, or what it holds after 15 seconds. */
private static List<String> awaitLogEvents(String logGroup, String logStream, Predicate<List<String>> complete)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
List<String> messages = logEvents(logGroup, logStream);
while (!complete.test(messages) && System.nanoTime() < deadline) {
Thread.sleep(200);
messages = logEvents(logGroup, logStream);
}
return messages;
}
private static String awaitLogStream(String logGroup) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
while (true) {
List<String> streams = RestAssuredJsonUtils.awsAction("Logs_20140328", "DescribeLogStreams",
"{\"logGroupName\": \"%s\"}".formatted(logGroup))
.then().extract().jsonPath().getList("logStreams.logStreamName", String.class);
if (streams != null && !streams.isEmpty()) {
return streams.getFirst();
}
assertTrue(System.nanoTime() < deadline, "No log stream in " + logGroup);
Thread.sleep(200);
}
}
/**
* The messages of a log stream once the last output of {@code /log} on stdout and on stderr is in it, or what it
* holds after 15 seconds. The output of one stream arrives in order, so nothing written before comes later.
@@ -16,6 +16,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -57,7 +58,7 @@ class LambdaWebLogsTest {
doThrow(notFound()).doReturn("token").when(cloudWatchLogs)
.putLogEventsForAccount(eq(ACCOUNT), eq(GROUP), eq(CENTRAL_STREAM), anyList(), eq(REGION));
logs.open(ACCOUNT, REGION, GROUP, STREAM).accept("first\n");
logs.open(ACCOUNT, REGION, GROUP, STREAM, "INFO").accept("first\n");
ArgumentCaptor<List<Map<String, Object>>> local = ArgumentCaptor.forClass(List.class);
verify(cloudWatchLogs, timeout(5_000).times(2)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"),
@@ -78,7 +79,7 @@ class LambdaWebLogsTest {
doThrow(new AwsException("InvalidParameterException", "Invalid log group name.", 400)).when(cloudWatchLogs)
.createLogGroupForAccount(ACCOUNT, GROUP + ".local", null, null, REGION);
logs.open(ACCOUNT, REGION, GROUP, STREAM).accept("first\n");
logs.open(ACCOUNT, REGION, GROUP, STREAM, "INFO").accept("first\n");
verify(cloudWatchLogs, timeout(5_000)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP), eq(CENTRAL_STREAM),
anyList(), eq(REGION));
@@ -95,7 +96,7 @@ class LambdaWebLogsTest {
throw new IllegalStateException("the store failed");
}).doReturn("token").when(cloudWatchLogs)
.putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"), eq(STREAM), anyList(), eq(REGION));
LambdaWebLogs.Sink sink = logs.open(ACCOUNT, REGION, GROUP, STREAM);
LambdaWebLogs.Sink sink = logs.open(ACCOUNT, REGION, GROUP, STREAM, "INFO");
sink.accept("first\n");
writing.await(5, TimeUnit.SECONDS);
@@ -106,6 +107,41 @@ class LambdaWebLogsTest {
argThat(batch -> batch.size() == 1 && "second\n".equals(batch.getFirst().get("message"))), eq(REGION));
}
@Test
@SuppressWarnings("unchecked")
void eventsDroppedWhileTheQueueIsFullAreReportedBeforeTheNextOne() throws Exception {
CountDownLatch writing = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
writing.countDown();
release.await(5, TimeUnit.SECONDS);
return "token";
}).doReturn("token").when(cloudWatchLogs)
.putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"), eq(STREAM), anyList(), eq(REGION));
LambdaWebLogs.Sink sink = logs.open(ACCOUNT, REGION, GROUP, STREAM, "INFO");
sink.accept("first\n");
writing.await(5, TimeUnit.SECONDS);
for (int i = 0; i < LambdaWebLogs.MAX_QUEUED_EVENTS + 3; i++) {
sink.accept("queued\n");
}
release.countDown();
int drained = 1 + LambdaWebLogs.MAX_QUEUED_EVENTS / 1_000;
verify(cloudWatchLogs, timeout(5_000).times(drained)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"),
eq(STREAM), anyList(), eq(REGION));
sink.accept("after\n");
ArgumentCaptor<List<Map<String, Object>>> batches = ArgumentCaptor.forClass(List.class);
verify(cloudWatchLogs, timeout(5_000).times(drained + 1)).putLogEventsForAccount(eq(ACCOUNT),
eq(GROUP + ".local"), eq(STREAM), batches.capture(), eq(REGION));
List<String> messages = batches.getAllValues().stream().flatMap(List::stream)
.map(event -> (String) event.get("message")).toList();
String dropped = messages.get(messages.size() - 2);
assertTrue(dropped.contains("\"level\":\"WARN\",\"type\":\"platform.logsDropped\""), dropped);
assertTrue(dropped.endsWith("\"droppedRecords\":3,\"droppedBytes\":21}}"), dropped);
assertEquals("after\n", messages.getLast());
}
private static AwsException notFound() {
return new AwsException("ResourceNotFoundException", "The specified log stream does not exist.", 400);
}
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.restassured.path.json.JsonPath;
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.Instant;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class LambdaWebPlatformLogTest {
private static final String GROUP = "/aws/lambda/web/web";
private static final String STREAM = "2026/10/18/web[rev-abcde]0123456789abcdef0123456789abcdef";
@Mock
CloudWatchLogsService cloudWatchLogs;
private LambdaWebLogs logs;
@BeforeEach
void start() {
logs = new LambdaWebLogs(cloudWatchLogs);
}
@AfterEach
void stop() {
logs.shutdown();
}
@Test
void timesDropTheTrailingZerosOfTheFraction() {
assertEquals("2026-10-18T13:49:46.67Z", LambdaWebLogs.timestamp(Instant.parse("2026-10-18T13:49:46.670Z"), 3));
assertEquals("2026-10-18T13:49:33.4Z", LambdaWebLogs.timestamp(Instant.parse("2026-10-18T13:49:33.400999Z"), 3));
assertEquals("2026-10-18T13:49:33Z", LambdaWebLogs.timestamp(Instant.parse("2026-10-18T13:49:33.000Z"), 3));
assertEquals("2026-10-18T13:50:09.0405147Z",
LambdaWebLogs.timestamp(Instant.parse("2026-10-18T13:50:09.040514700Z"), 9));
}
@Test
void aRequestIsReportedWithItsDurationInMillisecondsToThreeDecimals() {
LambdaWebPlatformLog platform = new LambdaWebPlatformLog(
logs.open("111122223333", "eu-west-1", GROUP, STREAM, "DEBUG"), "eu-west-1", "web", "rev-abcde",
"nodejs24.x", "INFO");
platform.requestComplete("KXH25FBDZ33GP4TQ4ARAUYSTSA", "dev", 504, "Runtime.RequestTimeout", 3_000_716_400L, 0);
JsonPath event = JsonPath.from(firstMessage());
assertEquals("DEBUG", event.getString("level"));
assertEquals("platform.requestComplete", event.getString("type"));
assertEquals("eu-west-1", event.getString("region"));
assertTrue(firstMessage().endsWith("\"result\":504,\"errorType\":\"Runtime.RequestTimeout\","
+ "\"metrics\":{\"durationMs\":3000.716,\"responseBytes\":0}}}"), firstMessage());
}
@Test
void eventsBelowTheSystemLogLevelAreDroppedAndAFailedReportIsWarn() {
LambdaWebPlatformLog platform = new LambdaWebPlatformLog(
logs.open("111122223333", "eu-west-1", GROUP, STREAM, "WARN"), "eu-west-1", "web", "rev-abcde",
"nodejs24.x", "INFO");
platform.initStart();
platform.initReport(null, new LambdaWebPlatformLog.Usage(178_400, 142L * 1024 * 1024 + 5));
platform.invokeStart(1);
platform.concurrency(3);
platform.end(null, "Runtime.ExitError");
JsonPath event = JsonPath.from(firstMessage());
assertEquals("WARN", event.getString("level"));
assertEquals("platform.invokeReport", event.getString("type"));
assertEquals("failure", event.getString("record.status"));
assertEquals(3, event.getInt("record.metrics.concurrentRequests"));
assertEquals(142, event.getInt("record.metrics.maxMemoryUsageMb"));
assertTrue(firstMessage().contains("\"totalCpuTimeMs\":0.000,"), firstMessage());
}
@Test
void theListenFailureIsDroppedAtFatal() {
LambdaWebPlatformLog platform = new LambdaWebPlatformLog(
logs.open("111122223333", "eu-west-1", GROUP, STREAM, "DEBUG"), "eu-west-1", "web", "rev-abcde",
"nodejs24.x", "FATAL");
platform.applicationError("Application.TimeoutListenError: nothing was listening");
platform.spinDownStart();
assertEquals("platform.spinDownStart", JsonPath.from(firstMessage()).getString("type"));
}
@SuppressWarnings("unchecked")
private String firstMessage() {
ArgumentCaptor<List<Map<String, Object>>> batch = ArgumentCaptor.forClass(List.class);
verify(cloudWatchLogs, timeout(5_000).atLeastOnce()).putLogEventsForAccount(eq("111122223333"),
eq(GROUP + ".local"), eq(STREAM), batch.capture(), eq("eu-west-1"));
return (String) batch.getAllValues().getFirst().getFirst().get("message");
}
}