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:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-24 18:23:19 -04:00
1 parent 01b388eca9
commit 72bbc809b4
15 files changed
+319 -74

No files matched your search

@@ -228,9 +228,12 @@ public class LambdaWebDataPlane {
acquire(request, host, target, revision, requestId, null);
}
/** The domain is minted for each creation, so a recreated endpoint shares no state with the deleted one. */
/**
* The domain is minted for each creation, so a recreated endpoint shares no state with the deleted one.
* Each region of an endpoint has its own environments and rate limit.
*/
private static String endpointKey(WebFunctionTarget target) {
return String.join("|", target.accountId(), target.region(), target.endpoint().domainName);
return String.join("|", target.accountId(), target.servingRegion(), target.endpoint().domainName);
}
/** Starts or reuses the revision's environment off the event loop, then forwards. */
@@ -242,7 +245,7 @@ public class LambdaWebDataPlane {
}
Integer maxEnvironments = target.endpoint().scalingConfig == null
? null : target.endpoint().scalingConfig.maxEnvironments;
return environments.acquire(target.accountId(), target.region(), target.function(),
return environments.acquire(target.accountId(), target.servingRegion(), target.function(),
endpointKey(target), maxEnvironments, revision);
}, false)
.onSuccess(environment -> forward(request, host, target, revision, environment, requestId, dead == null))
@@ -8,6 +8,7 @@ import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.FileTrees;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -313,8 +314,9 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
* for it. The least busy one is taken, the one idle longest on a tie, so requests rotate. When
* all are full a new one starts. At {@code maxEnvironments} an idle environment of another
* revision makes room, and without one the request is {@link Throttled}. {@code endpointKey}
* names one creation of the endpoint in one region, so a recreated endpoint starts afresh. The
* caller releases the environment when the request is over. Blocks on Docker and S3.
* names one creation of the endpoint in one region, so a recreated endpoint starts afresh.
* {@code region} is the region the environment serves. The caller releases the environment
* when the request is over. Blocks on Docker and S3.
*/
public Environment acquire(String accountId, String region, WebFunction fn, String endpointKey,
Integer maxEnvironments, WebFunctionRevision revision) {
@@ -547,7 +549,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
}
private void start(Environment environment, String region, WebFunction fn, WebFunctionRevision revision) {
if (!executionRole.assumableFor(region, fn.functionArn, revision.serviceConfig.executionRoleArn)) {
String homeRegion = AwsArnUtils.parse(fn.functionArn).region();
if (!executionRole.assumableFor(homeRegion, fn.functionArn, revision.serviceConfig.executionRoleArn)) {
throw new StartFailure(LambdaWebErrorPages.CANNOT_ASSUME_ROLE);
}
// Before the session and the token, which a failed start must not leave behind.
@@ -594,17 +597,17 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
}
LambdaWebPlatformLog platform = null;
try {
copyCode(containerId, accountId, region, fn, revision);
copyCode(containerId, accountId, homeRegion, fn, revision);
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, RUNTIME_DIR, "index.js",
runtime, 0644);
environment.containerId = containerId;
environment.logStream = LOG_STREAM_DATE.format(Instant.now()) + "/" + fn.functionName + "["
+ revision.revisionId + "]" + UUID.randomUUID().toString().replace("-", "");
environment.logs = logs.open(accountId, region, revision.serviceConfig.logGroup, environment.logStream,
revision.serviceConfig.systemLogLevel);
environment.logs = logs.open(accountId, region, homeRegion, revision.serviceConfig.logGroup,
environment.logStream, revision.serviceConfig.systemLogLevel);
platform = new LambdaWebPlatformLog(environment.logs, region, fn.functionName, revision.revisionId,
revision.buildConfig.runtime, revision.serviceConfig.applicationLogLevel,
metrics.environment(accountId, region, fn.functionName));
metrics.environment(accountId, region, homeRegion, fn.functionName));
environment.platformLog = platform;
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
platform.initStart();
@@ -112,7 +112,7 @@ public class LambdaWebIamAuth {
if (distributionArn != null) {
return authorizeCloudFront(distributionArn, target);
}
String accessKeyId = authenticate(request, target.region());
String accessKeyId = authenticate(request, target.servingRegion());
return accessKeyId != null && authorize(accessKeyId, target);
}
@@ -251,7 +251,7 @@ public class LambdaWebIamAuth {
if (callerAccount.isEmpty()) {
return false;
}
boolean allowed = RequestScopes.callAs(callerAccount.get(), target.region(),
boolean allowed = RequestScopes.callAs(callerAccount.get(), target.servingRegion(),
() -> evaluate(accessKeyId, callerAccount.get(), target));
if (!allowed) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}",
@@ -283,7 +283,7 @@ public class LambdaWebIamAuth {
}
String endpointArn = target.endpoint().endpointArn;
Map<String, List<String>> effective = IamConditionContextResolver.withGlobalContext(
context, endpointArn, target.region(), callerAccount, target.accountId());
context, endpointArn, target.servingRegion(), callerAccount, target.accountId());
String policy = target.function().policy;
ResourcePolicyDecision grant = evaluator.evaluateResourcePolicyFor(
isBlank(policy) ? null : List.of(policy), RequestPrincipal.caller(callerArns.orElse(null)),
@@ -24,10 +24,11 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* Delivers the log events of Web Function environments. Each event goes to the stream of its
* environment in the {@code .local} companion of the revision's log group, and to the same stream
* with an {@code -<account>-<region>} suffix in the log group itself, where AWS centralizes the
* regions an endpoint serves. A group or stream is created when its first event arrives. The
* {@code platform.*} events below the revision's {@code systemLogLevel} are dropped.
* environment in the {@code .local} companion of the revision's log group in the region the
* environment serves, and to the same stream with an {@code -<account>-<region>} suffix in the log
* group itself in the home region, where AWS centralizes the regions an endpoint serves. A group or
* stream is created when its first event arrives. The {@code platform.*} events below the
* revision's {@code systemLogLevel} are dropped.
*/
@ApplicationScoped
public class LambdaWebLogs {
@@ -50,10 +51,11 @@ public class LambdaWebLogs {
this.logs = logs;
}
public Sink open(String accountId, String region, String logGroup, String logStream, String systemLogLevel) {
public Sink open(String accountId, String region, String homeRegion, String logGroup, String logStream,
String systemLogLevel) {
return new Sink(accountId, region, SYSTEM_LEVELS.indexOf(systemLogLevel), List.of(
new Destination(logGroup + ".local", logStream),
new Destination(logGroup, logStream + "-" + accountId + "-" + region)));
new Destination(region, logGroup + ".local", logStream),
new Destination(homeRegion, logGroup, logStream + "-" + accountId + "-" + region)));
}
/** A time as AWS writes it in a platform event, without the trailing zeros of the fraction. */
@@ -68,7 +70,7 @@ public class LambdaWebLogs {
writers.shutdownNow();
}
private record Destination(String logGroup, String logStream) {
private record Destination(String region, String logGroup, String logStream) {
}
private record Event(long timestamp, String message) {
@@ -198,20 +200,22 @@ public class LambdaWebLogs {
/** The group and the stream are created when an event finds one of them missing, also after a delete. */
private void putTo(Destination destination, List<Map<String, Object>> batch) {
try {
logs.putLogEventsForAccount(accountId, destination.logGroup(), destination.logStream(), batch, region);
logs.putLogEventsForAccount(accountId, destination.logGroup(), destination.logStream(), batch,
destination.region());
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
createLogGroup(destination);
createLogStream(destination);
logs.putLogEventsForAccount(accountId, destination.logGroup(), destination.logStream(), batch, region);
logs.putLogEventsForAccount(accountId, destination.logGroup(), destination.logStream(), batch,
destination.region());
}
}
private void createLogGroup(Destination destination) {
try {
logs.createLogGroupForAccount(accountId, destination.logGroup(), null, null, region);
logs.createLogGroupForAccount(accountId, destination.logGroup(), null, null, destination.region());
} catch (AwsException e) {
ignoreAlreadyExists(e);
}
@@ -219,7 +223,8 @@ public class LambdaWebLogs {
private void createLogStream(Destination destination) {
try {
logs.createLogStreamForAccount(accountId, destination.logGroup(), destination.logStream(), region);
logs.createLogStreamForAccount(accountId, destination.logGroup(), destination.logStream(),
destination.region());
} catch (AwsException e) {
ignoreAlreadyExists(e);
}
@@ -26,8 +26,8 @@ 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.
* per environment when it starts, each minute and when it ends. Both namespaces go to the region
* that served, and {@code AWS/Lambda/Web} also to the home region, where AWS centralizes it.
*/
@ApplicationScoped
public class LambdaWebMetrics {
@@ -84,14 +84,14 @@ public class LambdaWebMetrics {
datapoints.add(new Datapoint(USAGE_NAMESPACE,
MetricDatum.of("EndpointActiveEnvironments", "Count", activeEnvironments, usage, now)));
statusClass(datapoints, status, request, now);
publish(target.accountId(), target.region(), datapoints);
publish(target.accountId(), target.servingRegion(), 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);
publish(target.accountId(), target.servingRegion(), target.region(), datapoints);
}
/** A request refused with 429. {@code metric} names the limit it hit. */
@@ -101,14 +101,14 @@ public class LambdaWebMetrics {
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);
publish(target.accountId(), target.servingRegion(), target.region(), datapoints);
}
EnvironmentMetrics environment(String accountId, String region, String functionName) {
EnvironmentMetrics environment(String accountId, String region, String homeRegion, 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(
publish(accountId, region, homeRegion, Stream.of(
MetricDatum.of("EnvironmentActiveTime", "Milliseconds", activeMillis, dimensions, now),
MetricDatum.of("EnvironmentCPUTime", "Milliseconds", cpuMillis, dimensions, now),
MetricDatum.of("EnvironmentMaxMemoryUsage", "Megabytes", maxMemoryMb, dimensions, now),
@@ -157,10 +157,10 @@ public class LambdaWebMetrics {
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()));
new Dimension("ExecutionRegion", target.servingRegion()));
}
private synchronized void publish(String accountId, String region, List<Datapoint> datapoints) {
private synchronized void publish(String accountId, String region, String homeRegion, List<Datapoint> datapoints) {
if (datapoints.isEmpty()) {
return;
}
@@ -168,6 +168,9 @@ public class LambdaWebMetrics {
lastWrite = publisher.submit(() -> {
for (Datapoint datapoint : datapoints) {
store(accountId, region, datapoint);
if (!region.equals(homeRegion) && NAMESPACE.equals(datapoint.namespace())) {
store(accountId, homeRegion, datapoint);
}
}
});
dropping = false;
@@ -191,11 +191,16 @@ public class LambdaWebService implements Resettable {
code.clear();
}
/** Where a request to an endpoint domain goes. Domains are unique across accounts and regions. */
public record WebFunctionTarget(String accountId, String region, WebFunction function, WebFunctionEndpoint endpoint) {
/**
* Where a request to an endpoint domain goes. Domains are unique across accounts and regions.
* {@code region} is the function's home region and {@code servingRegion} the region of the domain.
*/
public record WebFunctionTarget(String accountId, String region, WebFunction function, WebFunctionEndpoint endpoint,
String servingRegion) {
}
private record EndpointLocator(String accountId, String region, String functionName, String endpointName) {
private record EndpointLocator(String accountId, String region, String functionName, String endpointName,
String servingRegion) {
}
public Optional<WebFunctionTarget> locate(String host) {
@@ -213,7 +218,7 @@ public class LambdaWebService implements Resettable {
}
WebFunction fn = copy(stored.get(), WebFunction.class);
return Optional.of(new WebFunctionTarget(locator.accountId(), locator.region(), fn,
fn.endpoints.get(locator.endpointName())));
fn.endpoints.get(locator.endpointName()), locator.servingRegion()));
}
});
}
@@ -226,11 +231,13 @@ public class LambdaWebService implements Resettable {
return Optional.ofNullable(originHosts.get(host));
}
/** Floci serves the MultiRegion global domain in the home region. */
private void indexDomains(WebFunction fn, WebFunctionEndpoint endpoint) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(fn.functionArn);
EndpointLocator locator = new EndpointLocator(arn.accountId(), arn.region(), fn.functionName, endpoint.endpointName);
index(endpoint.domainName, locator);
endpoint.regionalDomainNames.values().forEach(domain -> index(domain, locator));
index(endpoint.domainName, new EndpointLocator(arn.accountId(), arn.region(), fn.functionName,
endpoint.endpointName, arn.region()));
endpoint.regionalDomainNames.forEach((region, domain) -> index(domain, new EndpointLocator(arn.accountId(),
arn.region(), fn.functionName, endpoint.endpointName, region)));
}
private void index(String domain, EndpointLocator locator) {
@@ -924,8 +931,9 @@ public class LambdaWebService implements Resettable {
if ("MultiRegion".equals(endpoint.endpointType)) {
endpoint.domainName = randomLowercase(DOMAIN_ID_LENGTH) + ".lambda-web.global." + host;
} else {
String id = randomLowercase(DOMAIN_ID_LENGTH);
for (String each : endpoint.regions) {
endpoint.regionalDomainNames.put(each, regionalDomain(each, host));
endpoint.regionalDomainNames.put(each, regionalDomain(id, each, host));
}
endpoint.domainName = endpoint.regionalDomainNames.get(region);
}
@@ -933,8 +941,8 @@ public class LambdaWebService implements Resettable {
endpoint.updatedAt = endpoint.createdAt;
}
private static String regionalDomain(String region, String host) {
return randomLowercase(DOMAIN_ID_LENGTH) + "." + DOMAIN_SHARD + ".lambda-web." + region + "." + host;
private static String regionalDomain(String id, String region, String host) {
return id + "." + DOMAIN_SHARD + ".lambda-web." + region + "." + host;
}
private static void requireModeAllowed(String mode, String endpointType) {