mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambdaweb): send what a Web Function writes to its log groups as AWS does (#5919)
* feat(lambdaweb): send what a Web Function writes to its log groups as AWS does * chore(lambdaweb): write the Web Function runtime as an ES module * fix(lambdaweb): create a log group or stream only when an event finds it missing * fix(lambdaweb): cut a log line by its UTF-8 size after replacing bytes that are not UTF-8 * test(lambdaweb): wait for the last log line instead of a fixed sleep
This commit is contained in:
1 parent
8972b21e1b
commit
8067ecf1de
9 files changed
+681
-13
No files matched your search
+74
@@ -3,12 +3,15 @@ package io.github.hectorvent.floci.services.lambdaweb;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager.Environment;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
@@ -60,7 +63,18 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
private static final String APP = """
|
||||
const http = require('node:http');
|
||||
const [host, port] = process.env.AWS_LAMBDA_HTTP_ENDPOINT.split(':');
|
||||
console.log('starting');
|
||||
http.createServer((req, res) => {
|
||||
if (req.url.startsWith('/log')) {
|
||||
console.info({route: 'log', main: require.main === module, argv: process.argv.slice(1)});
|
||||
console.debug('below the level');
|
||||
console.error(new Error('logged error'));
|
||||
process.stdout.write('raw line\\n');
|
||||
process.stdout.write(' \\n');
|
||||
process.stdout.write('last line\\n');
|
||||
res.end('logged');
|
||||
return;
|
||||
}
|
||||
if (req.url.startsWith('/slow')) { setTimeout(() => res.end('late'), 8000); return; }
|
||||
if (req.url.startsWith('/wait')) { setTimeout(() => res.end('waited'), 3000); return; }
|
||||
if (req.url.startsWith('/stream')) {
|
||||
@@ -100,6 +114,11 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
|
||||
private String functionName;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(), "Docker must be available for the Lambda Web data plane");
|
||||
@@ -181,6 +200,38 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
.body("headers.x-amz-date", equalTo("20260101T000000Z"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void theOutputGoesToTheLocalAndTheCentralizedLogGroupAsJsonEvents() throws Exception {
|
||||
String domain = createFunction(30);
|
||||
Response logged = given().header("Host", domain).when().get("/log");
|
||||
logged.then().statusCode(200);
|
||||
String logStream = logged.header("lambda-web-logstream");
|
||||
String group = "/aws/lambda/web/" + functionName;
|
||||
|
||||
List<String> local = awaitLogEvents(group + ".local", logStream);
|
||||
assertEquals(5, local.size(), local.toString());
|
||||
JsonPath starting = JsonPath.from(local.getFirst());
|
||||
assertEquals("INFO", starting.getString("level"));
|
||||
assertEquals("starting", starting.getString("message"));
|
||||
assertEquals("us-east-1", starting.getString("region"));
|
||||
assertFalse(local.getFirst().contains("requestId"), local.getFirst());
|
||||
JsonPath info = JsonPath.from(local.stream().filter(event -> event.contains("\"route\"")).findFirst().orElseThrow());
|
||||
assertEquals(logged.header("lambda-web-request-id"), info.getString("requestId"));
|
||||
assertEquals("dev", info.getString("endpointName"));
|
||||
assertEquals(false, info.getBoolean("message.main"));
|
||||
assertEquals(List.of("/var/runtime/index.js"), info.getList("message.argv"));
|
||||
JsonPath error = JsonPath.from(local.stream().filter(event -> event.contains("ERROR")).findFirst().orElseThrow());
|
||||
assertEquals("Error", error.getString("message.errorType"));
|
||||
assertEquals("logged error", error.getString("message.errorMessage"));
|
||||
assertEquals("Error: logged error", error.getList("message.stackTrace").getFirst());
|
||||
assertTrue(local.contains("raw line\n"), local.toString());
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void anIamAuthEndpointServesSignedRequestsWithoutTheirSignature() throws Exception {
|
||||
@@ -368,6 +419,29 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
.extract().path("endpoint.domainName");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private static List<String> awaitLogEvents(String logGroup, String logStream) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
|
||||
List<String> messages = logEvents(logGroup, logStream);
|
||||
while (!(messages.contains("last line\n") && messages.stream().anyMatch(event -> event.contains("\"ERROR\"")))
|
||||
&& System.nanoTime() < deadline) {
|
||||
Thread.sleep(200);
|
||||
messages = logEvents(logGroup, logStream);
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
private static List<String> logEvents(String logGroup, String logStream) {
|
||||
List<String> messages = RestAssuredJsonUtils.awsAction("Logs_20140328", "GetLogEvents",
|
||||
"{\"logGroupName\": \"%s\", \"logStreamName\": \"%s\", \"startFromHead\": true}"
|
||||
.formatted(logGroup, logStream))
|
||||
.then().extract().jsonPath().getList("events.message", String.class);
|
||||
return messages == null ? List.of() : messages;
|
||||
}
|
||||
|
||||
/** Sends one raw HTTP/1.1 request with {@code Connection: close} and reads until the server closes. */
|
||||
private static String raw(String request) throws Exception {
|
||||
return raw(request, null);
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
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.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LambdaWebLogsTest {
|
||||
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final String GROUP = "/aws/lambda/web/web";
|
||||
private static final String STREAM = "2026/10/18/web[rev-abcde]0123456789abcdef0123456789abcdef";
|
||||
private static final String CENTRAL_STREAM = STREAM + "-" + ACCOUNT + "-" + REGION;
|
||||
|
||||
@Mock
|
||||
CloudWatchLogsService cloudWatchLogs;
|
||||
|
||||
private LambdaWebLogs logs;
|
||||
|
||||
@BeforeEach
|
||||
void start() {
|
||||
logs = new LambdaWebLogs(cloudWatchLogs);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stop() {
|
||||
logs.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void eventsGoToTheLocalAndTheCentralizedGroupCreatedWhenMissing() {
|
||||
doThrow(notFound()).doReturn("token").when(cloudWatchLogs)
|
||||
.putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"), eq(STREAM), anyList(), eq(REGION));
|
||||
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");
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> local = ArgumentCaptor.forClass(List.class);
|
||||
verify(cloudWatchLogs, timeout(5_000).times(2)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"),
|
||||
eq(STREAM), local.capture(), eq(REGION));
|
||||
verify(cloudWatchLogs, timeout(5_000).times(2)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP),
|
||||
eq(CENTRAL_STREAM), anyList(), eq(REGION));
|
||||
verify(cloudWatchLogs).createLogGroupForAccount(ACCOUNT, GROUP + ".local", null, null, REGION);
|
||||
verify(cloudWatchLogs).createLogStreamForAccount(ACCOUNT, GROUP + ".local", STREAM, REGION);
|
||||
verify(cloudWatchLogs).createLogGroupForAccount(ACCOUNT, GROUP, null, null, REGION);
|
||||
verify(cloudWatchLogs).createLogStreamForAccount(ACCOUNT, GROUP, CENTRAL_STREAM, REGION);
|
||||
assertEquals("first\n", local.getValue().getFirst().get("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGroupThatCannotBeCreatedTakesNoEventsAndTheOtherStillDoes() {
|
||||
doThrow(notFound()).when(cloudWatchLogs)
|
||||
.putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"), eq(STREAM), anyList(), eq(REGION));
|
||||
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");
|
||||
|
||||
verify(cloudWatchLogs, timeout(5_000)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP), eq(CENTRAL_STREAM),
|
||||
anyList(), eq(REGION));
|
||||
verify(cloudWatchLogs, never()).createLogStreamForAccount(ACCOUNT, GROUP + ".local", STREAM, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventsQueuedWhileAWriteFailsAreStillDelivered() throws Exception {
|
||||
CountDownLatch writing = new CountDownLatch(1);
|
||||
CountDownLatch queued = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
writing.countDown();
|
||||
queued.await(5, TimeUnit.SECONDS);
|
||||
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);
|
||||
|
||||
sink.accept("first\n");
|
||||
writing.await(5, TimeUnit.SECONDS);
|
||||
sink.accept("second\n");
|
||||
queued.countDown();
|
||||
|
||||
verify(cloudWatchLogs, timeout(5_000)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"), eq(STREAM),
|
||||
argThat(batch -> batch.size() == 1 && "second\n".equals(batch.getFirst().get("message"))), eq(REGION));
|
||||
}
|
||||
|
||||
private static AwsException notFound() {
|
||||
return new AwsException("ResourceNotFoundException", "The specified log stream does not exist.", 400);
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class LambdaWebOutputLinesTest {
|
||||
|
||||
private static final int MAX = LambdaWebOutputLines.MAX_EVENT_BYTES;
|
||||
|
||||
@Test
|
||||
void eachLineIsAnEventWithItsNewline() {
|
||||
LambdaWebOutputLines lines = new LambdaWebOutputLines();
|
||||
|
||||
assertEquals(List.of("one\n", "two\n"), lines.append(bytes("one\ntwo\nthr")));
|
||||
assertEquals(List.of("three\n"), lines.append(bytes("ee\n")));
|
||||
assertEquals(List.of(), lines.flush());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOutputAfterTheLastNewlineComesOutWhenTheStreamEnds() {
|
||||
LambdaWebOutputLines lines = new LambdaWebOutputLines();
|
||||
|
||||
assertEquals(List.of(), lines.append(bytes("no newline")));
|
||||
assertEquals(List.of("no newline"), lines.flush());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLongLineIsCutBeforeTheCharacterThatWouldPassTheLimit() {
|
||||
LambdaWebOutputLines lines = new LambdaWebOutputLines();
|
||||
|
||||
assertEquals(List.of("y".repeat(MAX - 2), "日tail\n"), lines.append(bytes("y".repeat(MAX - 2) + "日tail\n")));
|
||||
assertEquals(List.of("z".repeat(MAX), "z\n"), lines.append(bytes("z".repeat(MAX + 1) + "\n")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bytesThatAreNotUtf8BecomeReplacementCharactersCountedAtTheirEncodedSize() {
|
||||
LambdaWebOutputLines lines = new LambdaWebOutputLines();
|
||||
|
||||
assertEquals(List.of("a�b��c\n"),
|
||||
lines.append(concat(bytes("a"), new byte[] {(byte) 0x80}, bytes("b"),
|
||||
new byte[] {(byte) 0xFF, (byte) 0xFE}, bytes("c\n"))));
|
||||
assertEquals(List.of("cut � end\n"),
|
||||
lines.append(concat(bytes("cut "), new byte[] {(byte) 0xE6, (byte) 0x97}, bytes(" end\n"))));
|
||||
assertEquals(List.of("x".repeat(MAX - 1), "����tail\n"),
|
||||
lines.append(concat(bytes("x".repeat(MAX - 1)), new byte[] {(byte) 0x80, (byte) 0x80, (byte) 0x80,
|
||||
(byte) 0x80}, bytes("tail\n"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCharacterSplitAcrossPayloadsStaysWhole() {
|
||||
LambdaWebOutputLines lines = new LambdaWebOutputLines();
|
||||
byte[] word = bytes("日本\n");
|
||||
|
||||
assertEquals(List.of(), lines.append(new byte[] {word[0], word[1]}));
|
||||
assertEquals(List.of("日本\n"), lines.append(Arrays.copyOfRange(word, 2, word.length)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnfinishedCharacterAtTheEndBecomesAReplacementCharacter() {
|
||||
LambdaWebOutputLines lines = new LambdaWebOutputLines();
|
||||
|
||||
assertEquals(List.of(), lines.append(new byte[] {'a', (byte) 0xE6, (byte) 0x97}));
|
||||
assertEquals(List.of("a�"), lines.flush());
|
||||
}
|
||||
|
||||
private static byte[] bytes(String text) {
|
||||
return text.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
for (byte[] part : parts) {
|
||||
out.writeBytes(part);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user