mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambdaweb): serve each region of a PerRegion endpoint in that region (#6423)
* feat(lambdaweb): serve each region of a PerRegion endpoint in that region A request to the regional domain of another region now runs in an environment of that region. It gets that region in AWS_REGION and from the metadata endpoint, and maxEnvironments and rateLimit count per region. Its .local logs and its metrics go to that region. The centralized logs and AWS/Lambda/Web also go to the home region, as on AWS. SigV4 and aws:RequestedRegion use the region of the domain. The regional domains share one id, as on AWS. The MultiRegion global domain stays in the home region. * test(lambdaweb): wait for the logs once and cover the mirror region deny The Docker test now waits only for the centralized stream, since each batch reaches the .local group first. The Authorization headers come from EnforcementFixtures.auth. The RequestedRegion test also denies us-east-1 and checks that the west domain is still allowed.
This commit is contained in:
1 parent
01b388eca9
commit
72bbc809b4
15 files changed
+319
-74
No files matched your search
+82
-3
@@ -42,10 +42,12 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
@@ -433,6 +435,75 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
assertTrue(answer.getString("token").matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(240)
|
||||
void aPerRegionEndpointServesEachRegionFromItsOwnEnvironments() throws Exception {
|
||||
createFunction(30, 1);
|
||||
String endpoints = BASE + "/web-functions/" + functionName + "/endpoints";
|
||||
String revisionId = given().when().get(endpoints + "/dev").then().statusCode(200)
|
||||
.extract().path("revisionWeights[0].revisionId");
|
||||
JsonPath created = given().contentType("application/json")
|
||||
.body("""
|
||||
{"endpointName": "per", "endpointType": "PerRegion", "regions": ["us-west-2"],
|
||||
"authType": "ApplicationManaged", "scalingConfig": {"maxEnvironments": 2},
|
||||
"revisionWeights": [{"revisionId": "%s", "weight": 100}]}""".formatted(revisionId))
|
||||
.when().put(endpoints)
|
||||
.then().statusCode(202)
|
||||
.extract().jsonPath();
|
||||
String east = created.getString("regionalEndpoints.us-east-1.domainName");
|
||||
String west = created.getString("regionalEndpoints.us-west-2.domainName");
|
||||
|
||||
Response westEcho = given().header("Host", west).when().get("/");
|
||||
westEcho.then().statusCode(200).body("env.region", equalTo("us-west-2"));
|
||||
String westStream = westEcho.header("lambda-web-logstream");
|
||||
given().header("Host", east).when().get("/").then().statusCode(200).body("env.region", equalTo("us-east-1"))
|
||||
.header("lambda-web-logstream", not(equalTo(westStream)));
|
||||
JsonPath zone = given().header("Host", west).when().get("/metadata").then().statusCode(200)
|
||||
.extract().jsonPath();
|
||||
assertEquals("{\"AvailabilityZoneID\":\"usw2-az1\"}\n", zone.getString("body"));
|
||||
|
||||
// maxEnvironments holds in each region on its own, as on AWS.
|
||||
AtomicInteger next = new AtomicInteger();
|
||||
CyclicBarrier together = new CyclicBarrier(4);
|
||||
List<String> waited = parallel(4, () -> raw("GET /wait HTTP/1.1\r\nHost: "
|
||||
+ (next.getAndIncrement() % 2 == 0 ? east : west) + "\r\nConnection: close\r\n\r\n", together));
|
||||
assertTrue(waited.stream().allMatch(response -> response.startsWith("HTTP/1.1 200 ")),
|
||||
String.join("\n----\n", waited));
|
||||
|
||||
// The .local group is in the region that served and the centralized one in the home region. Each batch
|
||||
// reaches the .local group first.
|
||||
String group = "/aws/lambda/web/" + functionName;
|
||||
Predicate<List<String>> started = events -> events.stream().anyMatch(event -> event.contains("\"starting\""));
|
||||
assertTrue(started.test(awaitLogEvents(group, westStream + "-000000000000-us-west-2", started)));
|
||||
List<String> local = logEvents("us-west-2", group + ".local", westStream);
|
||||
JsonPath starting = JsonPath.from(local.stream().filter(event -> event.contains("\"starting\""))
|
||||
.findFirst().orElseThrow());
|
||||
assertEquals("us-west-2", starting.getString("region"));
|
||||
JsonPath initStart = platformEvent(local, "platform.initStart");
|
||||
assertEquals("us-west-2", initStart.getString("region"));
|
||||
assertTrue(initStart.getString("record.runtimeVersionArn").startsWith(
|
||||
"arn:aws:lambda:us-west-2::runtime/nodejs24.x/version/"), initStart.prettify());
|
||||
assertEquals(List.of(), logEvents("us-east-1", group + ".local", westStream));
|
||||
|
||||
// AWS/Lambda/Web is also centralized in the home region. The usage metrics are not.
|
||||
Map<String, String> endpoint = Map.of("FunctionName", functionName, "EndpointName", "per");
|
||||
Map<String, String> westUsage = Map.of("FunctionName", functionName, "EndpointName", "per",
|
||||
"ExecutionRegion", "us-west-2");
|
||||
metrics.awaitPublished(Duration.ofSeconds(5));
|
||||
assertEquals(4, LambdaWebMetricStatistics.of("us-west-2", LambdaWebMetrics.NAMESPACE, "ExecutedRequests",
|
||||
endpoint, "Sum"));
|
||||
assertEquals(7, LambdaWebMetricStatistics.of("us-east-1", LambdaWebMetrics.NAMESPACE, "ExecutedRequests",
|
||||
endpoint, "Sum"));
|
||||
assertEquals(4, LambdaWebMetricStatistics.of("us-west-2", LambdaWebMetrics.USAGE_NAMESPACE,
|
||||
"ExecutedRequests", westUsage, "Sum"));
|
||||
assertEquals(0, LambdaWebMetricStatistics.of("us-east-1", LambdaWebMetrics.USAGE_NAMESPACE,
|
||||
"ExecutedRequests", westUsage, "Sum"));
|
||||
|
||||
given().when().delete(endpoints + "/per").then().statusCode(204);
|
||||
given().header("Host", west).when().get("/").then().statusCode(404)
|
||||
.header("lambda-web-error-type", "Platform.InvalidEndpoint");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void anEnvironmentRunsTheCodeTheRevisionWasCreatedFrom() throws Exception {
|
||||
@@ -786,9 +857,17 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
}
|
||||
|
||||
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))
|
||||
return logEvents("us-east-1", logGroup, logStream);
|
||||
}
|
||||
|
||||
private static List<String> logEvents(String region, String logGroup, String logStream) {
|
||||
List<String> messages = given()
|
||||
.header("Authorization", auth("test", region, "logs"))
|
||||
.header("X-Amz-Target", "Logs_20140328.GetLogEvents")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"logGroupName\": \"%s\", \"logStreamName\": \"%s\", \"startFromHead\": true}"
|
||||
.formatted(logGroup, logStream))
|
||||
.when().post("/")
|
||||
.then().extract().jsonPath().getList("events.message", String.class);
|
||||
return messages == null ? List.of() : messages;
|
||||
}
|
||||
|
||||
+30
@@ -301,6 +301,36 @@ class LambdaWebDataPlaneIntegrationTest {
|
||||
assertTrue(raw("GET / HTTP/1.1\r\n" + headers + pad + "a\r\n\r\n").startsWith("HTTP/1.1 431 "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPerRegionEndpointCountsAPageInTheRegionThatServedAndInTheHomeRegion() {
|
||||
String functionName = "dp-regions-" + Long.toString(System.nanoTime(), 36);
|
||||
createFunction(functionName);
|
||||
String endpoints = BASE + "/web-functions/" + functionName + "/endpoints";
|
||||
String revisionId = given().when().get(endpoints + "/dev").then().statusCode(200)
|
||||
.extract().path("revisionWeights[0].revisionId");
|
||||
String west = given().contentType("application/json")
|
||||
.body("""
|
||||
{"endpointName": "per", "endpointType": "PerRegion", "regions": ["us-west-2"],
|
||||
"authType": "IamAuth", "revisionWeights": [{"revisionId": "%s", "weight": 100}]}"""
|
||||
.formatted(revisionId))
|
||||
.when().put(endpoints)
|
||||
.then().statusCode(202)
|
||||
.extract().path("regionalEndpoints.us-west-2.domainName");
|
||||
given().header("Host", west).when().get("/").then().statusCode(403);
|
||||
|
||||
Map<String, String> endpoint = Map.of("FunctionName", functionName, "EndpointName", "per");
|
||||
metrics.awaitPublished(Duration.ofSeconds(5));
|
||||
assertEquals(1, LambdaWebMetricStatistics.of("us-west-2", LambdaWebMetrics.NAMESPACE,
|
||||
"HTTPResponseStatusClass4XX", endpoint, "Sum"));
|
||||
assertEquals(1, LambdaWebMetricStatistics.of("us-east-1", LambdaWebMetrics.NAMESPACE,
|
||||
"HTTPResponseStatusClass4XX", endpoint, "Sum"));
|
||||
|
||||
given().when().delete(endpoints + "/per").then().statusCode(204);
|
||||
given().header("Host", west).when().get("/")
|
||||
.then().statusCode(404).header("lambda-web-error-type", "Platform.InvalidEndpoint");
|
||||
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherHostsStillReachTheControlPlane() {
|
||||
given().when().get(BASE + "/web-account-settings").then().statusCode(200);
|
||||
|
||||
+34
-3
@@ -40,6 +40,7 @@ class LambdaWebIamAuthTest {
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
private static final String HOST = "abcdefghijklmnop.001.lambda-web.us-east-1.localhost:4566";
|
||||
private static final String WEST_HOST = "abcdefghijklmnop.001.lambda-web.us-west-2.localhost:4566";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":web-function/app";
|
||||
private static final String ENDPOINT_ARN = FUNCTION_ARN + "/endpoint/prod";
|
||||
private static final String USER_KEY = "AKIAUSERKEY000000001";
|
||||
@@ -125,6 +126,12 @@ class LambdaWebIamAuthTest {
|
||||
assertFalse(allows(signer().service("execute-api").sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRegionalDomainOfAnotherRegionTakesOnlyASignatureForThatRegion() {
|
||||
assertTrue(allows(signer().region("us-west-2").sign("GET", WEST_HOST, "/"), WEST_HOST, "us-west-2"));
|
||||
assertFalse(allows(signer().sign("GET", WEST_HOST, "/"), WEST_HOST, "us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSigningTimeMustBeWithinFiveMinutes() {
|
||||
Instant now = Instant.now();
|
||||
@@ -201,6 +208,19 @@ class LambdaWebIamAuthTest {
|
||||
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/env\":\"prod\"}}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementTheRequestedRegionIsTheRegionOfTheDomain() {
|
||||
enforceFor(ACCOUNT);
|
||||
LambdaWebRequestSigner.Signed west = signer().credentials(USER_KEY, USER_SECRET, null).region("us-west-2")
|
||||
.sign("GET", WEST_HOST, "/");
|
||||
function.policy = denyRequestedRegion("us-west-2");
|
||||
assertTrue(allowsUserWith(allow(ENDPOINT_ARN, "")));
|
||||
assertFalse(allows(west, WEST_HOST, "us-west-2"));
|
||||
function.policy = denyRequestedRegion("us-east-1");
|
||||
assertFalse(allowsUserWith(allow(ENDPOINT_ARN, "")));
|
||||
assertTrue(allows(west, WEST_HOST, "us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementTheResourcePolicyAllowsWithinTheAccountAndItsDenyWins() {
|
||||
enforceFor(ACCOUNT);
|
||||
@@ -263,7 +283,7 @@ class LambdaWebIamAuthTest {
|
||||
private boolean allowsCloudFront(Map<String, String> signature) {
|
||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", HOST).addAll(signature);
|
||||
return iamAuth.allows(new Inbound("POST", "/", null, headers, MultiMap.caseInsensitiveMultiMap()),
|
||||
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint));
|
||||
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint, "us-east-1"));
|
||||
}
|
||||
|
||||
private static String cloudFrontPolicy(String... statements) {
|
||||
@@ -301,6 +321,13 @@ class LambdaWebIamAuthTest {
|
||||
.formatted(effect, callerAccount, ENDPOINT_ARN);
|
||||
}
|
||||
|
||||
private static String denyRequestedRegion(String region) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*",
|
||||
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"aws:RequestedRegion":"%s"}}}]}""".formatted(ENDPOINT_ARN, region);
|
||||
}
|
||||
|
||||
private static String allow(String resource, String condition) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"lambda:InvokeWebFunctionEndpoint",
|
||||
@@ -312,11 +339,15 @@ class LambdaWebIamAuthTest {
|
||||
}
|
||||
|
||||
private boolean allows(LambdaWebRequestSigner.Signed signed) {
|
||||
return allows(signed, HOST, "us-east-1");
|
||||
}
|
||||
|
||||
private boolean allows(LambdaWebRequestSigner.Signed signed, String host, String servingRegion) {
|
||||
String pathAndQuery = signed.pathAndQuery();
|
||||
int question = pathAndQuery.indexOf('?');
|
||||
String path = question < 0 ? pathAndQuery : pathAndQuery.substring(0, question);
|
||||
String query = question < 0 ? null : pathAndQuery.substring(question + 1);
|
||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", HOST);
|
||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", host);
|
||||
signed.headers().forEach(headers::add);
|
||||
MultiMap params = MultiMap.caseInsensitiveMultiMap();
|
||||
try {
|
||||
@@ -325,6 +356,6 @@ class LambdaWebIamAuthTest {
|
||||
// The data plane keeps going with no parameters when the query does not decode.
|
||||
}
|
||||
return iamAuth.allows(new Inbound(signed.method(), path, query, headers, params),
|
||||
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint));
|
||||
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint, servingRegion));
|
||||
}
|
||||
}
|
||||
+15
@@ -364,6 +364,21 @@ class LambdaWebIntegrationTest {
|
||||
.then().statusCode(404)
|
||||
.header("X-Amzn-Errortype", "ResourceNotFoundException")
|
||||
.body("message", equalTo("The endpoint global does not exist."));
|
||||
|
||||
// The regional domains of a PerRegion endpoint share one id, and the home one leads.
|
||||
String home = given().contentType("application/json")
|
||||
.body("{\"endpointName\": \"per\", \"endpointType\": \"PerRegion\", \"regions\": [\"us-west-2\"],"
|
||||
+ " \"authType\": \"ApplicationManaged\","
|
||||
+ " \"revisionWeights\": [{\"revisionId\": \"" + revision1 + "\", \"weight\": 100}]}")
|
||||
.when().put(endpoints)
|
||||
.then().statusCode(202)
|
||||
.body("domainName", matchesPattern("[a-z0-9]{16}\\.001\\.lambda-web\\.us-east-1\\..+"))
|
||||
.extract().path("domainName");
|
||||
given().when().get(endpoints + "/per")
|
||||
.then().statusCode(200)
|
||||
.body("regionalEndpoints.us-east-1.domainName", equalTo(home))
|
||||
.body("regionalEndpoints.us-west-2.domainName", equalTo(home.replace(".us-east-1.", ".us-west-2.")));
|
||||
given().when().delete(endpoints + "/per").then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -10,6 +12,7 @@ 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 java.util.concurrent.CountDownLatch;
|
||||
@@ -58,7 +61,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, "INFO").accept("first\n");
|
||||
logs.open(ACCOUNT, REGION, 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"),
|
||||
@@ -72,6 +75,24 @@ class LambdaWebLogsTest {
|
||||
assertEquals("first\n", local.getValue().getFirst().get("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void anEnvironmentInAnotherRegionWritesTheLocalGroupThereAndTheCentralizedOneInTheHomeRegion() {
|
||||
String replica = "eu-central-1";
|
||||
ObjectNode record = new ObjectMapper().createObjectNode().put("functionName", "web");
|
||||
|
||||
logs.open(ACCOUNT, replica, REGION, GROUP, STREAM, "INFO").platform(Instant.now(), "INFO",
|
||||
"platform.initStart", record);
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> local = ArgumentCaptor.forClass(List.class);
|
||||
verify(cloudWatchLogs, timeout(5_000)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP + ".local"), eq(STREAM),
|
||||
local.capture(), eq(replica));
|
||||
verify(cloudWatchLogs, timeout(5_000)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP),
|
||||
eq(STREAM + "-" + ACCOUNT + "-" + replica), anyList(), eq(REGION));
|
||||
String message = (String) local.getValue().getFirst().get("message");
|
||||
assertTrue(message.contains("\"region\":\"eu-central-1\""), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGroupThatCannotBeCreatedTakesNoEventsAndTheOtherStillDoes() {
|
||||
doThrow(notFound()).when(cloudWatchLogs)
|
||||
@@ -79,7 +100,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, "INFO").accept("first\n");
|
||||
logs.open(ACCOUNT, REGION, REGION, GROUP, STREAM, "INFO").accept("first\n");
|
||||
|
||||
verify(cloudWatchLogs, timeout(5_000)).putLogEventsForAccount(eq(ACCOUNT), eq(GROUP), eq(CENTRAL_STREAM),
|
||||
anyList(), eq(REGION));
|
||||
@@ -96,7 +117,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, "INFO");
|
||||
LambdaWebLogs.Sink sink = logs.open(ACCOUNT, REGION, REGION, GROUP, STREAM, "INFO");
|
||||
|
||||
sink.accept("first\n");
|
||||
writing.await(5, TimeUnit.SECONDS);
|
||||
@@ -118,7 +139,7 @@ class LambdaWebLogsTest {
|
||||
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");
|
||||
LambdaWebLogs.Sink sink = logs.open(ACCOUNT, REGION, REGION, GROUP, STREAM, "INFO");
|
||||
sink.accept("first\n");
|
||||
writing.await(5, TimeUnit.SECONDS);
|
||||
|
||||
|
||||
+7
@@ -8,6 +8,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** Reads Web Function metrics back with GetMetricStatistics, as a client does. */
|
||||
@@ -18,12 +19,18 @@ final class 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) {
|
||||
return of("us-east-1", namespace, metric, dimensions, statistic);
|
||||
}
|
||||
|
||||
static double of(String region, 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("Authorization", auth("test", region, "monitoring"))
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics")
|
||||
.body("{\"Namespace\":\"" + namespace + "\",\"MetricName\":\"" + metric + "\",\"Dimensions\":[" + filter
|
||||
+ "],\"StartTime\":" + now.minusSeconds(600).getEpochSecond() + ",\"EndTime\":"
|
||||
|
||||
+41
-3
@@ -49,7 +49,7 @@ class LambdaWebMetricsTest {
|
||||
function.functionName = "web";
|
||||
WebFunctionEndpoint endpoint = new WebFunctionEndpoint();
|
||||
endpoint.endpointName = "dev";
|
||||
target = new WebFunctionTarget(ACCOUNT, REGION, function, endpoint);
|
||||
target = new WebFunctionTarget(ACCOUNT, REGION, function, endpoint, REGION);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -99,7 +99,7 @@ class LambdaWebMetricsTest {
|
||||
|
||||
@Test
|
||||
void anEnvironmentPublishesEachMetricByFunctionName() {
|
||||
metrics.environment(ACCOUNT, REGION, "web").publish(244, 178, 142, 2, 37);
|
||||
metrics.environment(ACCOUNT, REGION, REGION, "web").publish(244, 178, 142, 2, 37);
|
||||
|
||||
assertEquals(List.of(
|
||||
"AWS/Lambda/Web EnvironmentActiveTime FunctionName=web 244.0 Milliseconds",
|
||||
@@ -110,6 +110,40 @@ class LambdaWebMetricsTest {
|
||||
published(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestServedInAnotherRegionAlsoCountsInTheHomeRegionButItsUsageDoesNot() {
|
||||
WebFunctionTarget replica = new WebFunctionTarget(ACCOUNT, REGION, target.function(), target.endpoint(),
|
||||
"eu-central-1");
|
||||
metrics.executed(replica, 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-central-1 3.0 Count",
|
||||
"AWS/Lambda/Web/Usage ExecutedRequests FunctionName=web,EndpointName=dev,ExecutionRegion=eu-central-1"
|
||||
+ " 1.0 Count"),
|
||||
published("eu-central-1", 4));
|
||||
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"),
|
||||
published(REGION, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEnvironmentInAnotherRegionPublishesThereAndInTheHomeRegion() {
|
||||
metrics.environment(ACCOUNT, "eu-central-1", REGION, "web").publish(244, 178, 142, 2, 37);
|
||||
|
||||
List<String> expected = 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");
|
||||
assertEquals(expected, published("eu-central-1", 5));
|
||||
assertEquals(expected, published(REGION, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesPastTheQueueLimitAreDroppedAndTheRestAreStoredBeforeTheWaitEnds() throws InterruptedException {
|
||||
metrics.shutdown();
|
||||
@@ -137,11 +171,15 @@ class LambdaWebMetricsTest {
|
||||
}
|
||||
|
||||
private List<String> published(int count) {
|
||||
return published(REGION, count);
|
||||
}
|
||||
|
||||
private List<String> published(String region, 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());
|
||||
datums.capture(), eq(region), anyString());
|
||||
List<String> published = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
MetricDatum datum = datums.getAllValues().get(i);
|
||||
|
||||
+10
-10
@@ -55,8 +55,8 @@ class LambdaWebPlatformLogTest {
|
||||
@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", this::datapoint);
|
||||
logs.open("111122223333", "eu-west-1", "eu-west-1", GROUP, STREAM, "DEBUG"), "eu-west-1", "web",
|
||||
"rev-abcde", "nodejs24.x", "INFO", this::datapoint);
|
||||
|
||||
platform.requestComplete("KXH25FBDZ33GP4TQ4ARAUYSTSA", "dev", 504, "Runtime.RequestTimeout", 3_000_716_400L, 0);
|
||||
|
||||
@@ -71,8 +71,8 @@ class LambdaWebPlatformLogTest {
|
||||
@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", this::datapoint);
|
||||
logs.open("111122223333", "eu-west-1", "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);
|
||||
@@ -92,8 +92,8 @@ class LambdaWebPlatformLogTest {
|
||||
@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", this::datapoint);
|
||||
logs.open("111122223333", "eu-west-1", "eu-west-1", GROUP, STREAM, "DEBUG"), "eu-west-1", "web",
|
||||
"rev-abcde", "nodejs24.x", "FATAL", this::datapoint);
|
||||
|
||||
platform.applicationError("Application.TimeoutListenError: nothing was listening");
|
||||
platform.spinDownStart();
|
||||
@@ -104,8 +104,8 @@ class LambdaWebPlatformLogTest {
|
||||
@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);
|
||||
logs.open("111122223333", "eu-west-1", "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);
|
||||
@@ -125,8 +125,8 @@ class LambdaWebPlatformLogTest {
|
||||
@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);
|
||||
logs.open("111122223333", "eu-west-1", "eu-west-1", GROUP, STREAM, "INFO"), "eu-west-1", "web",
|
||||
"rev-abcde", "nodejs24.x", "INFO", this::datapoint);
|
||||
platform.initStart();
|
||||
platform.initReport("Runtime.ExitError", null);
|
||||
|
||||
|
||||
Reference in new issue
Block a user