mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(lambdaweb): CloudFormation types for Lambda Web Functions (#5722)
* feat(lambdaweb): CloudFormation types for Lambda Web Functions AWS::Lambda::WebFunction, AWS::Lambda::WebFunctionRevision and AWS::Lambda::WebFunctionEndpoint provision through the resource registry. Ref of each is its ARN. Every property of a revision is createOnly in the registry schema, so a changed revision mints a new one and the displaced revision is deleted once the update commits. An endpoint keeps its identity while its function, name, type and regions stay the same. Fn::GetAtt on RegionalEndpoints is recorded as a gap. Part of #5699 * fix(lambdaweb): compare a revision against the function's default log group revisionMatches filled a request without a log group with the existing revision's log group, so a template that dropped a custom log group kept the old revision. The default is the function's log group, as when a revision is created. replaceTags returns the updated function. * fix(cloudformation): put a Lambda Web function or endpoint back after a failed stack update A function's tags and an endpoint's mutable configuration are changed in place on update. The provisioner now snapshots them before the change and restores them from rollbackUpdate, as the other in-place provisioners do. The function attributes after a tag update come from the updated function, so UpdatedAt moves with the tag change. * test(cloudformation): roll a Lambda Web stack update back after a failed revision A revision that fails to create after the endpoint moved to a replaced revision rolls the stack back. The endpoint returns to the kept revision and the replacement is deleted. The doc page says that a CloudFormation endpoint is always Disabled with RevisionWeights, since the schema has no AutoDeploymentMode, and that a failed update puts in-place changes back. * fix(cloudformation): refuse AutoDeploymentMode on a Lambda Web endpoint The registry schema has no AutoDeploymentMode property and AWS fails a template that sets it at validation. An endpoint from CloudFormation is always Disabled and routes by RevisionWeights. Floci passed the property through to the service, which accepted LatestRevision. * refactor(lambdaweb): share the create and tag steps between the API and CloudFormation paths createFunction and createFunctionShell both check the name and refuse a duplicate under the function's lock. tagResource and replaceTags both check the tags, lock, write, stamp and persist. Each pair now calls one private helper, so the two paths cannot drift.
This commit is contained in:
1 parent
01cc020419
commit
0492fc9842
13 files changed
+1223
-21
No files matched your search
@@ -174,7 +174,7 @@ cross-resource references.
|
||||
| SNS | `Topic`, `Subscription`, `TopicPolicy` |
|
||||
| SES | `EmailIdentity` (BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS's region- and identity-specific zone assignment) |
|
||||
| DynamoDB | `Table` (`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one), `GlobalTable` |
|
||||
| Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
|
||||
| Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`, `WebFunction` (control plane only; the endpoint domain does not serve requests yet), `WebFunctionEndpoint` (`RegionalEndpoints` is not exposed to `Fn::GetAtt` yet), `WebFunctionRevision` (every property is createOnly, so a change mints a new revision). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
|
||||
| IAM | `Role`, `User` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
|
||||
| Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` |
|
||||
| SSM | `Parameter` |
|
||||
|
||||
@@ -41,7 +41,7 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
|
||||
- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.
|
||||
- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.
|
||||
- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`.
|
||||
- **Not implemented yet:** invoking a function through its endpoint domain, execution environments, `IamAuth` on requests, the automatic deletion of revisions past 50, and the `AWS::Lambda::WebFunction*` CloudFormation types. The endpoint domain does not answer requests yet.
|
||||
- **Not implemented yet:** invoking a function through its endpoint domain, execution environments, `IamAuth` on requests, and the automatic deletion of revisions past 50. The endpoint domain does not answer requests yet.
|
||||
|
||||
### `aws lambda-web deploy`
|
||||
|
||||
@@ -52,3 +52,9 @@ AWS_ENDPOINT_URL=http://localhost:4566 aws lambda-web deploy --name my-app --hel
|
||||
```
|
||||
|
||||
The command passes `--endpoint-url` only to the Lambda Web client. Its STS, S3 and IAM calls use the default endpoints, so the environment variable is what routes them to Floci. The `endpointUrl` it prints is the Floci domain name behind `https://`, which Floci does not serve yet.
|
||||
|
||||
## CloudFormation
|
||||
|
||||
`AWS::Lambda::WebFunction`, `AWS::Lambda::WebFunctionRevision` and `AWS::Lambda::WebFunctionEndpoint` provision through the resource registry. `Ref` of each is its ARN. Every property of a revision is createOnly, so a changed revision mints a new one and the displaced revision is deleted once the update commits. An endpoint keeps its identity while its function, name, type and regions stay the same. A changed type or region list under the same name is refused the way CloudFormation refuses to replace a custom-named resource. `Fn::GetAtt` on `RegionalEndpoints` is not supported yet.
|
||||
|
||||
CloudFormation has no `AutoDeploymentMode` property, so an endpoint it creates is always `Disabled` and needs `RevisionWeights`, as on AWS. Name the revision with `Fn::GetAtt` so a replaced revision moves the endpoint with it. A stack update that fails after an in-place change to a function's tags or an endpoint's configuration puts the previous values back.
|
||||
+8
@@ -112,6 +112,14 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String REST_API_UPDATE_SNAPSHOT_ATTR = "__FlociRestApiUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the tags a web function or the mutable configuration a web function endpoint carried
|
||||
* before the in-place update in flight changed it, so a failed stack update can put it back.
|
||||
* Written by {@code LambdaWebCfnProvisioner} before its update call and spent by its
|
||||
* {@code rollbackUpdate}.
|
||||
*/
|
||||
public static final String LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR = "__FlociLambdaWebUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the function ARN, status, caching flag, token settings and tags an IoT authorizer
|
||||
* carried before an in-place update changed them, so a failed stack update can put them back.
|
||||
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for {@code AWS::Lambda::WebFunction}, {@code WebFunctionRevision} and
|
||||
* {@code WebFunctionEndpoint}. Each physical id is the resource's ARN, the schemas' primaryIdentifier.
|
||||
* Every property of a revision is createOnly. A function's createOnly property is its name, an
|
||||
* endpoint's are its function, name, type and regions.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaWebCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
static final String FUNCTION = "AWS::Lambda::WebFunction";
|
||||
static final String REVISION = "AWS::Lambda::WebFunctionRevision";
|
||||
static final String ENDPOINT = "AWS::Lambda::WebFunctionEndpoint";
|
||||
private static final Logger LOG = Logger.getLogger(LambdaWebCfnProvisioner.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Set<String> ENDPOINT_CREATE_ONLY = Set.of("FunctionName", "EndpointName", "EndpointType", "Regions");
|
||||
/** Integer properties. A parameter or mapping value arrives as text, which CloudFormation coerces. */
|
||||
private static final Set<String> INTEGER_PROPERTIES =
|
||||
Set.of("TimeoutSeconds", "MaxConcurrencyPerEnvironment", "Weight", "MaxEnvironments", "RateLimit");
|
||||
private static final Pattern INTEGER_TEXT = Pattern.compile("-?[0-9]{1,10}");
|
||||
|
||||
private final LambdaWebService service;
|
||||
|
||||
@Inject
|
||||
public LambdaWebCfnProvisioner(LambdaWebService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(FUNCTION, REVISION, ENDPOINT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case FUNCTION -> provisionFunction(r, props, ctx);
|
||||
case REVISION -> provisionRevision(r, props, ctx);
|
||||
case ENDPOINT -> provisionEndpoint(r, props, ctx);
|
||||
default -> throw new IllegalStateException("LambdaWebCfnProvisioner cannot handle " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
|
||||
/** A revision an endpoint still routes to keeps its ConflictException, so the stack reports it. */
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
switch (resourceType) {
|
||||
case FUNCTION -> CfnDeletes.safeDelete("web function", physicalId,
|
||||
() -> service.deleteFunction(region, physicalId), "ResourceNotFoundException");
|
||||
case REVISION -> CfnDeletes.safeDelete("web function revision", physicalId,
|
||||
() -> service.deleteRevision(region, functionArnOf(physicalId), physicalId), "ResourceNotFoundException");
|
||||
case ENDPOINT -> CfnDeletes.safeDelete("web function endpoint", physicalId,
|
||||
() -> service.deleteEndpoint(region, functionArnOf(physicalId), physicalId), "ResourceNotFoundException");
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
/** An in-place change is undone from the snapshot taken before it; the snapshot stays until that succeeds. */
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
String raw = resource.getAttributes().get(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR);
|
||||
if (raw == null) {
|
||||
return false;
|
||||
}
|
||||
JsonNode snapshot;
|
||||
try {
|
||||
snapshot = MAPPER.readTree(raw);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.errorv("Could not parse the Lambda Web update snapshot of {0}: {1}", resource.getLogicalId(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
String region = snapshot.path("region").asText();
|
||||
String functionArn = snapshot.path("functionArn").asText();
|
||||
if ("endpoint".equals(snapshot.path("type").asText())) {
|
||||
service.updateEndpoint(region, functionArn, snapshot.path("endpointName").asText(), snapshot.get("patch"));
|
||||
} else {
|
||||
service.replaceTags(region, functionArn,
|
||||
MAPPER.convertValue(snapshot.get("tags"), new TypeReference<Map<String, String>>() {}));
|
||||
}
|
||||
resource.getAttributes().remove(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void provisionFunction(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String name = require(props, "FunctionName", r, ctx);
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
WebFunction fn = ctx.isUpdate() ? find(() -> service.getFunction(ctx.region(), name)) : null;
|
||||
if (fn != null && ctx.reusesPriorEntity(fn.functionArn)) {
|
||||
if (!tags.equals(fn.tags)) {
|
||||
r.getAttributes().put(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR, tagSnapshot(ctx.region(), fn).toString());
|
||||
fn = service.replaceTags(ctx.region(), name, tags);
|
||||
}
|
||||
} else {
|
||||
fn = service.createFunctionShell(ctx.region(), name, tags);
|
||||
}
|
||||
r.setPhysicalId(fn.functionArn);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
r.getAttributes().put("FunctionArn", fn.functionArn);
|
||||
r.getAttributes().put("State", "Active");
|
||||
r.getAttributes().put("StateReason", "The function is active.");
|
||||
r.getAttributes().put("CreatedAt", LambdaWebService.formatTimestamp(fn.createdAt));
|
||||
r.getAttributes().put("UpdatedAt", LambdaWebService.formatTimestamp(fn.updatedAt));
|
||||
}
|
||||
|
||||
private void provisionRevision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String functionName = require(props, "FunctionName", r, ctx);
|
||||
JsonNode request = toCamelCase(ctx.engine().resolveNodeOmittingNoValue(props), Set.of("FunctionName"));
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
WebFunctionRevision revision = null;
|
||||
if (reusablePrior(ctx, attributesBefore)) {
|
||||
WebFunction fn = find(() -> service.getFunction(ctx.region(), functionName));
|
||||
String prior = ctx.priorPhysicalId();
|
||||
WebFunctionRevision existing = find(() -> service.getRevision(ctx.region(), functionArnOf(prior), prior));
|
||||
if (fn != null && existing != null && existing.functionArn.equals(fn.functionArn)
|
||||
&& service.revisionMatches(existing, request)) {
|
||||
revision = existing;
|
||||
}
|
||||
}
|
||||
if (revision == null) {
|
||||
revision = service.createRevision(ctx.region(), functionName, request);
|
||||
}
|
||||
r.setPhysicalId(revision.revisionArn);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
r.getAttributes().put("FunctionArn", revision.functionArn);
|
||||
r.getAttributes().put("RevisionArn", revision.revisionArn);
|
||||
r.getAttributes().put("RevisionId", revision.revisionId);
|
||||
r.getAttributes().put("State", "Active");
|
||||
r.getAttributes().put("StateReason", "The revision is active.");
|
||||
r.getAttributes().put("CreatedAt", LambdaWebService.formatTimestamp(revision.createdAt));
|
||||
}
|
||||
|
||||
private void provisionEndpoint(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String functionName = require(props, "FunctionName", r, ctx);
|
||||
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props);
|
||||
if (resolved.has("AutoDeploymentMode")) {
|
||||
// Not in the registry schema: a CloudFormation endpoint routes by RevisionWeights only.
|
||||
throw new IllegalArgumentException(r.getResourceType() + " has no AutoDeploymentMode property ("
|
||||
+ r.getLogicalId() + ")");
|
||||
}
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
WebFunctionEndpoint endpoint = null;
|
||||
if (reusablePrior(ctx, attributesBefore)) {
|
||||
WebFunction fn = find(() -> service.getFunction(ctx.region(), functionName));
|
||||
String prior = ctx.priorPhysicalId();
|
||||
WebFunctionEndpoint existing = find(() -> service.getEndpoint(ctx.region(), functionArnOf(prior), prior));
|
||||
if (fn != null && existing != null && existing.functionArn.equals(fn.functionArn)) {
|
||||
if (sameIdentity(existing, resolved, ctx.region())) {
|
||||
r.getAttributes().put(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR,
|
||||
endpointSnapshot(ctx.region(), existing).toString());
|
||||
endpoint = service.updateEndpoint(ctx.region(), functionName, existing.endpointName,
|
||||
endpointPatch(resolved, ctx)).after();
|
||||
} else if (existing.endpointName.equals(resolved.path("EndpointName").asText())) {
|
||||
throw CfnExceptions.customNamedReplacement(existing.endpointName);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (endpoint == null) {
|
||||
endpoint = service.createEndpoint(ctx.region(), functionName, toCamelCase(resolved, Set.of("FunctionName")));
|
||||
}
|
||||
r.setPhysicalId(endpoint.endpointArn);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
r.getAttributes().put("FunctionArn", endpoint.functionArn);
|
||||
r.getAttributes().put("EndpointArn", endpoint.endpointArn);
|
||||
r.getAttributes().put("DomainName", endpoint.domainName);
|
||||
r.getAttributes().put("State", "Active");
|
||||
r.getAttributes().put("StateReason", "The endpoint is active and invokable.");
|
||||
if (endpoint.updateStatus != null) {
|
||||
r.getAttributes().put("UpdateStatus", endpoint.updateStatus);
|
||||
r.getAttributes().put("UpdateStatusReason", "The endpoint is updated.");
|
||||
} else {
|
||||
r.getAttributes().remove("UpdateStatus");
|
||||
r.getAttributes().remove("UpdateStatusReason");
|
||||
}
|
||||
r.getAttributes().put("CreatedAt", LambdaWebService.formatTimestamp(endpoint.createdAt));
|
||||
r.getAttributes().put("UpdatedAt", LambdaWebService.formatTimestamp(endpoint.updatedAt));
|
||||
}
|
||||
|
||||
/** The in-place update. A property the previous template declared and this one dropped is cleared. */
|
||||
private static ObjectNode endpointPatch(JsonNode resolved, ProvisionContext ctx) {
|
||||
ObjectNode patch = (ObjectNode) toCamelCase(resolved, ENDPOINT_CREATE_ONLY);
|
||||
if (!patch.has("scalingConfig") && ctx.previouslyDeclared("ScalingConfig")) {
|
||||
patch.putObject("scalingConfig");
|
||||
}
|
||||
if (!patch.has("throttleConfig") && ctx.previouslyDeclared("ThrottleConfig")) {
|
||||
patch.putObject("throttleConfig");
|
||||
}
|
||||
if (!patch.has("description") && ctx.previouslyDeclared("Description")) {
|
||||
patch.put("description", "");
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
|
||||
private static ObjectNode tagSnapshot(String region, WebFunction fn) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode().put("type", "function").put("region", region)
|
||||
.put("functionArn", fn.functionArn);
|
||||
ObjectNode tags = snapshot.putObject("tags");
|
||||
fn.tags.forEach(tags::put);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** The endpoint's mutable configuration in the shape {@code UpdateWebFunctionEndpoint} takes. */
|
||||
private static ObjectNode endpointSnapshot(String region, WebFunctionEndpoint endpoint) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode().put("type", "endpoint").put("region", region)
|
||||
.put("functionArn", endpoint.functionArn).put("endpointName", endpoint.endpointName);
|
||||
ObjectNode patch = snapshot.putObject("patch");
|
||||
patch.put("authType", endpoint.authType);
|
||||
patch.put("description", endpoint.description == null ? "" : endpoint.description);
|
||||
patch.put("autoDeploymentMode", endpoint.autoDeploymentMode);
|
||||
if (!"LatestRevision".equals(endpoint.autoDeploymentMode)) {
|
||||
ArrayNode weights = patch.putArray("revisionWeights");
|
||||
for (WebFunctionEndpoint.RevisionWeight weight : endpoint.revisionWeights) {
|
||||
weights.addObject().put("revisionId", weight.revisionId).put("weight", weight.weight);
|
||||
}
|
||||
}
|
||||
ObjectNode scaling = patch.putObject("scalingConfig");
|
||||
if (endpoint.scalingConfig != null && endpoint.scalingConfig.maxEnvironments != null) {
|
||||
scaling.put("maxEnvironments", endpoint.scalingConfig.maxEnvironments);
|
||||
}
|
||||
ObjectNode throttle = patch.putObject("throttleConfig");
|
||||
if (endpoint.throttleConfig != null && endpoint.throttleConfig.rateLimit != null) {
|
||||
throttle.put("rateLimit", endpoint.throttleConfig.rateLimit);
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static boolean reusablePrior(ProvisionContext ctx, Map<String, String> attributesBefore) {
|
||||
return ctx.isUpdate() && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore);
|
||||
}
|
||||
|
||||
private static boolean sameIdentity(WebFunctionEndpoint existing, JsonNode props, String homeRegion) {
|
||||
if (!existing.endpointName.equals(props.path("EndpointName").asText())
|
||||
|| !existing.endpointType.equals(props.path("EndpointType").asText())) {
|
||||
return false;
|
||||
}
|
||||
Set<String> regions = new LinkedHashSet<>();
|
||||
regions.add(homeRegion);
|
||||
props.path("Regions").forEach(region -> regions.add(region.asText()));
|
||||
return regions.equals(new LinkedHashSet<>(existing.regions));
|
||||
}
|
||||
|
||||
private static <T> T find(Supplier<T> lookup) {
|
||||
try {
|
||||
return lookup.get();
|
||||
} catch (AwsException e) {
|
||||
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("No prior web function entity to reuse: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String require(JsonNode props, String name, StackResource r, ProvisionContext ctx) {
|
||||
String value = ctx.resolveOptional(props, name);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException(r.getResourceType() + " requires " + name + " (" + r.getLogicalId() + ")");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String functionArnOf(String childArn) {
|
||||
int child = childArn.indexOf("/revision/");
|
||||
if (child < 0) {
|
||||
child = childArn.indexOf("/endpoint/");
|
||||
}
|
||||
return child < 0 ? childArn : childArn.substring(0, child);
|
||||
}
|
||||
|
||||
/** The keys of {@code EnvironmentVariables} are the user's own and stay as written. */
|
||||
private static JsonNode toCamelCase(JsonNode node, Set<String> skip) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return MAPPER.createObjectNode();
|
||||
}
|
||||
ObjectNode out = MAPPER.createObjectNode();
|
||||
node.fields().forEachRemaining(entry -> {
|
||||
if (skip.contains(entry.getKey())) {
|
||||
return;
|
||||
}
|
||||
String key = Character.toLowerCase(entry.getKey().charAt(0)) + entry.getKey().substring(1);
|
||||
JsonNode value = entry.getValue();
|
||||
if (INTEGER_PROPERTIES.contains(entry.getKey()) && value.isTextual()
|
||||
&& INTEGER_TEXT.matcher(value.textValue()).matches()) {
|
||||
value = MAPPER.getNodeFactory().numberNode(Long.parseLong(value.textValue()));
|
||||
}
|
||||
out.set(key, "EnvironmentVariables".equals(entry.getKey()) ? value : lowerKeys(value));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
private static JsonNode lowerKeys(JsonNode node) {
|
||||
if (node.isObject()) {
|
||||
return toCamelCase(node, Set.of());
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode out = MAPPER.createArrayNode();
|
||||
node.forEach(item -> out.add(lowerKeys(item)));
|
||||
return out;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -191,9 +192,7 @@ public class LambdaWebService implements Resettable {
|
||||
validateTagsShape(validation, "tags", tags);
|
||||
validation.throwIfAny();
|
||||
|
||||
if (!FUNCTION_NAME.matcher(functionName).matches()) {
|
||||
throw invalidFunctionName(functionName);
|
||||
}
|
||||
requireFunctionName(functionName);
|
||||
if (revisionConfig == null || endpointConfig == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The revisionConfig and endpointConfig must be specified.", 400);
|
||||
@@ -202,19 +201,44 @@ public class LambdaWebService implements Resettable {
|
||||
validateRevisionRules(revisionConfig);
|
||||
String accountId = regionResolver.getAccountId();
|
||||
WebFunctionEndpoint endpoint = draftEndpoint(region, accountId, functionName, endpointConfig, false);
|
||||
String arn = functionArn(region, accountId, functionName);
|
||||
synchronized (lockFor(region, functionName)) {
|
||||
if (functions.get(key(region, functionName)).isPresent()) {
|
||||
throw new AwsException("ConflictException", "The function " + arn + " already exists.", 409);
|
||||
}
|
||||
WebFunction fn = newFunction(region, accountId, functionName, tags == null ? Map.of() : tags);
|
||||
return storeNewFunction(region, functionName, tags, fn -> {
|
||||
WebFunctionRevision revision = buildRevision(fn, revisionConfig);
|
||||
attachEndpoint(region, fn, endpoint, revision);
|
||||
fn.revisions.put(revision.revisionId, revision);
|
||||
fn.endpoints.put(endpoint.endpointName, endpoint);
|
||||
functions.put(key(region, functionName), fn);
|
||||
LOG.infov("Created web function {0} with revision {1} and endpoint {2}",
|
||||
functionName, revision.revisionId, endpoint.endpointName);
|
||||
});
|
||||
}
|
||||
|
||||
/** A function with no revision and no endpoint, for AWS::Lambda::WebFunction. */
|
||||
public WebFunction createFunctionShell(String region, String functionName, Map<String, String> tags) {
|
||||
requireFunctionName(functionName);
|
||||
LambdaWebValidation validation = new LambdaWebValidation();
|
||||
validateTagsShape(validation, "tags", tags);
|
||||
validation.throwIfAny();
|
||||
requireValidTags(tags);
|
||||
return storeNewFunction(region, functionName, tags, fn -> { });
|
||||
}
|
||||
|
||||
private static void requireFunctionName(String functionName) {
|
||||
if (functionName == null || !FUNCTION_NAME.matcher(functionName).matches()) {
|
||||
throw invalidFunctionName(functionName);
|
||||
}
|
||||
}
|
||||
|
||||
/** Stores a new function under its lock, refusing a name the region already has. */
|
||||
private WebFunction storeNewFunction(String region, String functionName, Map<String, String> tags,
|
||||
Consumer<WebFunction> populate) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
synchronized (lockFor(region, functionName)) {
|
||||
if (functions.get(key(region, functionName)).isPresent()) {
|
||||
throw new AwsException("ConflictException",
|
||||
"The function " + functionArn(region, accountId, functionName) + " already exists.", 409);
|
||||
}
|
||||
WebFunction fn = newFunction(region, accountId, functionName, tags == null ? Map.of() : tags);
|
||||
populate.accept(fn);
|
||||
functions.put(key(region, functionName), fn);
|
||||
return copy(fn, WebFunction.class);
|
||||
}
|
||||
}
|
||||
@@ -337,6 +361,31 @@ public class LambdaWebService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a revision already carries the configuration a request describes. */
|
||||
public boolean revisionMatches(WebFunctionRevision existing, JsonNode request) {
|
||||
WebFunctionRevision desired = new WebFunctionRevision();
|
||||
desired.description = LambdaWebJson.text(request, "description");
|
||||
desired.kmsKeyArn = LambdaWebJson.text(request, "kmsKeyArn");
|
||||
desired.buildConfig = buildConfigOf(LambdaWebJson.structure(request, "buildConfig"));
|
||||
String functionName = existing.functionArn.substring(existing.functionArn.lastIndexOf('/') + 1);
|
||||
desired.serviceConfig = serviceConfigOf(LambdaWebJson.structure(request, "serviceConfig"),
|
||||
defaultLogGroup(functionName));
|
||||
return objectMapper.valueToTree(configOnly(existing)).equals(objectMapper.valueToTree(configOnly(desired)));
|
||||
}
|
||||
|
||||
private static String defaultLogGroup(String functionName) {
|
||||
return "/aws/lambda/web/" + functionName;
|
||||
}
|
||||
|
||||
private static WebFunctionRevision configOnly(WebFunctionRevision revision) {
|
||||
WebFunctionRevision copy = new WebFunctionRevision();
|
||||
copy.description = revision.description;
|
||||
copy.kmsKeyArn = revision.kmsKeyArn;
|
||||
copy.buildConfig = revision.buildConfig;
|
||||
copy.serviceConfig = revision.serviceConfig;
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static WebFunctionRevision revision(WebFunction fn, String revisionId) {
|
||||
WebFunctionRevision revision = fn.revisions.get(revisionId);
|
||||
if (revision == null) {
|
||||
@@ -372,7 +421,7 @@ public class LambdaWebService implements Resettable {
|
||||
"The runtime " + revision.buildConfig.runtime + " is invalid.", 400);
|
||||
}
|
||||
revision.serviceConfig = serviceConfigOf(LambdaWebJson.structure(request, "serviceConfig"),
|
||||
"/aws/lambda/web/" + fn.functionName);
|
||||
defaultLogGroup(fn.functionName));
|
||||
requireCodeObject(revision.buildConfig);
|
||||
revision.description = LambdaWebJson.text(request, "description");
|
||||
revision.kmsKeyArn = LambdaWebJson.text(request, "kmsKeyArn");
|
||||
@@ -872,14 +921,7 @@ public class LambdaWebService implements Resettable {
|
||||
validation.pattern("resource", resourceArn, RESOURCE_ARN).required("tags", tags);
|
||||
validateTagsShape(validation, "tags", tags);
|
||||
validation.throwIfAny();
|
||||
requireValidTags(tags);
|
||||
String functionName = resolveFunctionName(region, resourceArn, "TagResource");
|
||||
synchronized (lockFor(region, functionName)) {
|
||||
WebFunction fn = function(region, functionName);
|
||||
fn.tags.putAll(tags);
|
||||
fn.updatedAt = now();
|
||||
persist(region, fn);
|
||||
}
|
||||
writeTags(region, resourceArn, tags, fn -> fn.tags.putAll(tags));
|
||||
}
|
||||
|
||||
public void untagResource(String region, String resourceArn, List<String> tagKeys) {
|
||||
@@ -900,6 +942,27 @@ public class LambdaWebService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the stored tags to exactly {@code desired}, for AWS::Lambda::WebFunction. */
|
||||
public WebFunction replaceTags(String region, String functionNameOrArn, Map<String, String> desired) {
|
||||
LambdaWebValidation validation = new LambdaWebValidation();
|
||||
validateTagsShape(validation, "tags", desired);
|
||||
validation.throwIfAny();
|
||||
return writeTags(region, functionNameOrArn, desired, fn -> fn.tags = new LinkedHashMap<>(desired));
|
||||
}
|
||||
|
||||
private WebFunction writeTags(String region, String functionNameOrArn, Map<String, String> tags,
|
||||
Consumer<WebFunction> write) {
|
||||
requireValidTags(tags);
|
||||
String functionName = resolveFunctionName(region, functionNameOrArn, "TagResource");
|
||||
synchronized (lockFor(region, functionName)) {
|
||||
WebFunction fn = function(region, functionName);
|
||||
write.accept(fn);
|
||||
fn.updatedAt = now();
|
||||
persist(region, fn);
|
||||
return copy(fn, WebFunction.class);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateTagsShape(LambdaWebValidation v, String path, Map<String, String> tags) {
|
||||
if (tags == null || tags.isEmpty()) {
|
||||
return;
|
||||
|
||||
@@ -574,6 +574,22 @@
|
||||
"ProvisionedConcurrencyConfig",
|
||||
"RuntimePolicy"
|
||||
],
|
||||
"AWS::Lambda::WebFunction": [
|
||||
"FunctionName"
|
||||
],
|
||||
"AWS::Lambda::WebFunctionEndpoint": [
|
||||
"FunctionName",
|
||||
"EndpointName",
|
||||
"EndpointType",
|
||||
"Regions"
|
||||
],
|
||||
"AWS::Lambda::WebFunctionRevision": [
|
||||
"FunctionName",
|
||||
"Description",
|
||||
"KmsKeyArn",
|
||||
"BuildConfig",
|
||||
"ServiceConfig"
|
||||
],
|
||||
"AWS::Logs::LogGroup": [
|
||||
"LogGroupName"
|
||||
],
|
||||
|
||||
+11
@@ -87,6 +87,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEve
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventSourceMappingCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaMicrovmsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVersionAliasCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaWebCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsLogStreamCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetricFilterCfnProvisioner;
|
||||
@@ -142,6 +143,7 @@ import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
@@ -239,6 +241,7 @@ final class CfnProvisionerFixture {
|
||||
private IotDomainConfigurationService iotDomainConfigurationService;
|
||||
private IotService iotService;
|
||||
private LambdaMicrovmsService lambdaMicrovmsService;
|
||||
private LambdaWebService lambdaWebService;
|
||||
private AwsConfigService awsConfigService;
|
||||
private OrganizationsService organizationsService;
|
||||
private SqsService sqsService;
|
||||
@@ -423,6 +426,9 @@ final class CfnProvisionerFixture {
|
||||
if (lambdaMicrovmsService != null) {
|
||||
discovered.add(new LambdaMicrovmsCfnProvisioner(lambdaMicrovmsService));
|
||||
}
|
||||
if (lambdaWebService != null) {
|
||||
discovered.add(new LambdaWebCfnProvisioner(lambdaWebService));
|
||||
}
|
||||
if (awsConfigService != null) {
|
||||
discovered.add(new ConfigCfnProvisioner(awsConfigService));
|
||||
}
|
||||
@@ -742,6 +748,11 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder lambdaWeb(LambdaWebService v) {
|
||||
this.lambdaWebService = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder awsConfig(AwsConfigService v) {
|
||||
this.awsConfigService = v;
|
||||
return this;
|
||||
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A stack with the three Web Function types against the real service: {@code Ref} is each ARN,
|
||||
* {@code Fn::GetAtt} exposes the attributes the registry schemas declare, a changed revision is
|
||||
* replaced and its predecessor deleted once the update commits, and deleting the stack removes the
|
||||
* function.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationLambdaWebIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String BUCKET = "cfn-web-code";
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Test
|
||||
void stackProvisionsFunctionRevisionAndEndpoint() {
|
||||
s3Service.createBucket(BUCKET, "us-east-1");
|
||||
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String functionName = "cfn-web-" + suffix;
|
||||
String stackName = "cfn-web-stack-" + suffix;
|
||||
String functionArn = "arn:aws:lambda:us-east-1:000000000000:web-function/" + functionName;
|
||||
|
||||
cloudFormation(stackName, "CreateStack", template(functionName, 30));
|
||||
Map<String, String> created = outputs(describeStacks(stackName, "CREATE_COMPLETE"));
|
||||
assertEquals(functionArn, created.get("FnRef"));
|
||||
assertEquals(functionArn, created.get("FnArn"));
|
||||
assertEquals("Active", created.get("FnState"));
|
||||
String revisionId = created.get("RevId");
|
||||
assertTrue(revisionId.matches("rev-[a-z0-9]{5}"), revisionId);
|
||||
assertEquals(functionArn + "/revision/" + revisionId, created.get("RevRef"));
|
||||
assertEquals(created.get("RevRef"), created.get("RevArn"));
|
||||
assertEquals("Active", created.get("RevState"));
|
||||
assertEquals(functionArn + "/endpoint/prod", created.get("EpRef"));
|
||||
assertEquals(created.get("EpRef"), created.get("EpArn"));
|
||||
assertTrue(created.get("EpDomain").matches("[a-z0-9]{16}\\.001\\.lambda-web\\.us-east-1\\..+"), created.get("EpDomain"));
|
||||
assertEquals("Active", created.get("EpState"));
|
||||
|
||||
given().when().get("/2025-03-07/web-functions/" + functionName + "/endpoints/prod")
|
||||
.then().statusCode(200)
|
||||
.body("authType", equalTo("ApplicationManaged"))
|
||||
.body("revisionWeights[0].revisionId", equalTo(revisionId))
|
||||
.body("revisionWeights[0].weight", equalTo(100));
|
||||
given().when().get("/2025-03-07/tags/" + functionArn)
|
||||
.then().statusCode(200)
|
||||
.body("Tags.env", equalTo("probe"));
|
||||
|
||||
// A changed timeout replaces the revision; the endpoint follows and the old revision is deleted.
|
||||
cloudFormation(stackName, "UpdateStack", template(functionName, 45));
|
||||
Map<String, String> updated = outputs(describeStacks(stackName, "UPDATE_COMPLETE"));
|
||||
String newRevisionId = updated.get("RevId");
|
||||
assertNotEquals(revisionId, newRevisionId);
|
||||
assertEquals(functionArn + "/endpoint/prod", updated.get("EpRef"), "the endpoint keeps its identity");
|
||||
await().untilAsserted(() -> given().contentType("application/json").body("{}")
|
||||
.when().post("/2025-03-07/web-functions/" + functionName + "/list-revisions")
|
||||
.then().statusCode(200)
|
||||
.body("revisions", hasSize(1))
|
||||
.body("revisions[0].revisionId", equalTo(newRevisionId)));
|
||||
given().when().get("/2025-03-07/web-functions/" + functionName + "/revisions/" + newRevisionId)
|
||||
.then().statusCode(200)
|
||||
.body("serviceConfig.timeoutSeconds", equalTo(45));
|
||||
|
||||
// A failure after the next replacement rolls the endpoint back to this revision and deletes the replacement.
|
||||
cloudFormation(stackName, "UpdateStack", template(functionName, 60, BAD_REVISION));
|
||||
await().untilAsserted(() -> describeStacks(stackName, "UPDATE_ROLLBACK_COMPLETE"));
|
||||
given().when().get("/2025-03-07/web-functions/" + functionName + "/endpoints/prod")
|
||||
.then().statusCode(200)
|
||||
.body("revisionWeights[0].revisionId", equalTo(newRevisionId));
|
||||
await().untilAsserted(() -> given().contentType("application/json").body("{}")
|
||||
.when().post("/2025-03-07/web-functions/" + functionName + "/list-revisions")
|
||||
.then().statusCode(200)
|
||||
.body("revisions", hasSize(1))
|
||||
.body("revisions[0].revisionId", equalTo(newRevisionId)));
|
||||
|
||||
cloudFormation(stackName, "DeleteStack", null);
|
||||
await().untilAsserted(() -> given().when().get("/2025-03-07/web-functions/" + functionName)
|
||||
.then().statusCode(404));
|
||||
}
|
||||
|
||||
/** A revision whose code object does not exist, created after the endpoint, so the update fails there. */
|
||||
private static final String BAD_REVISION = """
|
||||
"Bad": {
|
||||
"Type": "AWS::Lambda::WebFunctionRevision",
|
||||
"DependsOn": ["Ep"],
|
||||
"Properties": {
|
||||
"FunctionName": {"Ref": "Fn"},
|
||||
"BuildConfig": {
|
||||
"CodeConfig": {"S3Object": {"Bucket": "%s", "Key": "missing.zip"}},
|
||||
"RuntimeConfig": {"Runtime": "nodejs24.x"}
|
||||
},
|
||||
"ServiceConfig": {"ExecutionRoleArn": "arn:aws:iam::000000000000:role/cfn-web"}
|
||||
}
|
||||
},
|
||||
""".formatted(BUCKET);
|
||||
|
||||
private static String template(String functionName, int timeoutSeconds) {
|
||||
return template(functionName, timeoutSeconds, "");
|
||||
}
|
||||
|
||||
private static String template(String functionName, int timeoutSeconds, String extraResources) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Fn": {
|
||||
"Type": "AWS::Lambda::WebFunction",
|
||||
"Properties": {"FunctionName": "%s", "Tags": [{"Key": "env", "Value": "probe"}]}
|
||||
},
|
||||
"Rev": {
|
||||
"Type": "AWS::Lambda::WebFunctionRevision",
|
||||
"Properties": {
|
||||
"FunctionName": {"Ref": "Fn"},
|
||||
"Description": "cfn revision",
|
||||
"BuildConfig": {
|
||||
"CodeConfig": {"S3Object": {"Bucket": "%s", "Key": "app.zip"}},
|
||||
"RuntimeConfig": {"Runtime": "nodejs24.x"}
|
||||
},
|
||||
"ServiceConfig": {
|
||||
"ExecutionRoleArn": "arn:aws:iam::000000000000:role/cfn-web",
|
||||
"TimeoutSeconds": %d
|
||||
}
|
||||
}
|
||||
},
|
||||
%s"Ep": {
|
||||
"Type": "AWS::Lambda::WebFunctionEndpoint",
|
||||
"Properties": {
|
||||
"FunctionName": {"Ref": "Fn"},
|
||||
"EndpointName": "prod",
|
||||
"EndpointType": "HomeRegion",
|
||||
"AuthType": "ApplicationManaged",
|
||||
"RevisionWeights": [{"RevisionId": {"Fn::GetAtt": ["Rev", "RevisionId"]}, "Weight": 100}]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"FnRef": {"Value": {"Ref": "Fn"}},
|
||||
"FnArn": {"Value": {"Fn::GetAtt": ["Fn", "FunctionArn"]}},
|
||||
"FnState": {"Value": {"Fn::GetAtt": ["Fn", "State"]}},
|
||||
"RevRef": {"Value": {"Ref": "Rev"}},
|
||||
"RevArn": {"Value": {"Fn::GetAtt": ["Rev", "RevisionArn"]}},
|
||||
"RevId": {"Value": {"Fn::GetAtt": ["Rev", "RevisionId"]}},
|
||||
"RevState": {"Value": {"Fn::GetAtt": ["Rev", "State"]}},
|
||||
"EpRef": {"Value": {"Ref": "Ep"}},
|
||||
"EpArn": {"Value": {"Fn::GetAtt": ["Ep", "EndpointArn"]}},
|
||||
"EpDomain": {"Value": {"Fn::GetAtt": ["Ep", "DomainName"]}},
|
||||
"EpState": {"Value": {"Fn::GetAtt": ["Ep", "State"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(functionName, BUCKET, timeoutSeconds, extraResources);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stackName, String action, String templateBody) {
|
||||
if (templateBody == null) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().statusCode(200);
|
||||
return;
|
||||
}
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", templateBody)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String stackName, String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static Map<String, String> outputs(String describeStacksXml) {
|
||||
return XmlParser.extractPairs(describeStacksXml, "Outputs", "OutputKey", "OutputValue");
|
||||
}
|
||||
}
|
||||
+514
@@ -0,0 +1,514 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
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.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class LambdaWebCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String FN_ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/app";
|
||||
private static final String OTHER_FN_ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/other";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/web";
|
||||
private static final Set<String> FUNCTION_ATTRIBUTES = Set.of("FunctionArn", "State", "StateReason", "CreatedAt", "UpdatedAt");
|
||||
private static final Set<String> REVISION_ATTRIBUTES =
|
||||
Set.of("FunctionArn", "RevisionArn", "RevisionId", "State", "StateReason", "CreatedAt");
|
||||
private static final Set<String> ENDPOINT_ATTRIBUTES =
|
||||
Set.of("FunctionArn", "EndpointArn", "DomainName", "State", "StateReason", "CreatedAt", "UpdatedAt");
|
||||
|
||||
private final LambdaWebService service = mock(LambdaWebService.class);
|
||||
private final LambdaWebCfnProvisioner provisioner = new LambdaWebCfnProvisioner(service);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
return ctx(priorPhysicalId, null);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, ACCOUNT, "my-stack", priorPhysicalId, event -> {}, priorProperties);
|
||||
}
|
||||
|
||||
private static StackResource resource(String type) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Res");
|
||||
r.setResourceType(type);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private static StackResource updateOf(StackResource prior) {
|
||||
StackResource r = resource(prior.getResourceType());
|
||||
r.setPhysicalId(prior.getPhysicalId());
|
||||
r.setAttributes(new HashMap<>(prior.getAttributes()));
|
||||
return r;
|
||||
}
|
||||
|
||||
private static WebFunction function(String arn) {
|
||||
WebFunction fn = new WebFunction();
|
||||
fn.functionName = arn.substring(arn.lastIndexOf('/') + 1);
|
||||
fn.functionArn = arn;
|
||||
fn.createdAt = Instant.parse("2026-10-14T20:37:19.533870Z");
|
||||
fn.updatedAt = fn.createdAt;
|
||||
return fn;
|
||||
}
|
||||
|
||||
private static WebFunctionRevision revision(String id) {
|
||||
WebFunctionRevision revision = new WebFunctionRevision();
|
||||
revision.revisionId = id;
|
||||
revision.revisionArn = FN_ARN + "/revision/" + id;
|
||||
revision.functionArn = FN_ARN;
|
||||
revision.createdAt = Instant.parse("2026-10-14T20:37:19.533870Z");
|
||||
return revision;
|
||||
}
|
||||
|
||||
private static WebFunctionEndpoint endpoint(String name, String type, List<String> regions) {
|
||||
WebFunctionEndpoint endpoint = new WebFunctionEndpoint();
|
||||
endpoint.endpointName = name;
|
||||
endpoint.endpointArn = FN_ARN + "/endpoint/" + name;
|
||||
endpoint.functionArn = FN_ARN;
|
||||
endpoint.endpointType = type;
|
||||
endpoint.regions = regions;
|
||||
endpoint.domainName = "abc.001.lambda-web.us-east-1.localhost:4566";
|
||||
endpoint.createdAt = Instant.parse("2026-10-14T20:37:19.533870Z");
|
||||
endpoint.updatedAt = endpoint.createdAt;
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
private ObjectNode revisionProps() {
|
||||
ObjectNode props = mapper.createObjectNode().put("FunctionName", "app").put("Description", "first");
|
||||
ObjectNode build = props.putObject("BuildConfig");
|
||||
build.putObject("CodeConfig").putObject("S3Object").put("Bucket", "code").put("Key", "app.zip");
|
||||
build.putObject("RuntimeConfig").put("Runtime", "nodejs24.x");
|
||||
ObjectNode service = props.putObject("ServiceConfig").put("ExecutionRoleArn", ROLE).put("TimeoutSeconds", 45);
|
||||
service.putObject("EnvironmentVariables").put("APP_VERSION", "2");
|
||||
return props;
|
||||
}
|
||||
|
||||
private ObjectNode endpointProps(String type) {
|
||||
ObjectNode props = mapper.createObjectNode().put("FunctionName", "app").put("EndpointName", "prod")
|
||||
.put("EndpointType", type).put("AuthType", "IamAuth");
|
||||
props.putArray("RevisionWeights").addObject().put("RevisionId", "rev-aaaaa").put("Weight", 100);
|
||||
if (!"HomeRegion".equals(type)) {
|
||||
props.putArray("Regions").add("us-west-2");
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionIsCreatedBareAndIdentifiedByArn() {
|
||||
WebFunction fn = function(FN_ARN);
|
||||
fn.tags.put("env", "prod");
|
||||
when(service.createFunctionShell(REGION, "app", Map.of("env", "prod"))).thenReturn(fn);
|
||||
ObjectNode props = mapper.createObjectNode().put("FunctionName", "app");
|
||||
props.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.FUNCTION);
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
assertEquals(FN_ARN, r.getPhysicalId());
|
||||
assertEquals(FUNCTION_ATTRIBUTES, r.getAttributes().keySet());
|
||||
assertEquals(FN_ARN, r.getAttributes().get("FunctionArn"));
|
||||
assertEquals("Active", r.getAttributes().get("State"));
|
||||
assertEquals("The function is active.", r.getAttributes().get("StateReason"));
|
||||
assertEquals("2026-10-14T20:37:19.533870Z", r.getAttributes().get("CreatedAt"));
|
||||
assertEquals("2026-10-14T20:37:19.533870Z", r.getAttributes().get("UpdatedAt"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionUpdateWithTheSameNameReconcilesTags() {
|
||||
WebFunction fn = function(FN_ARN);
|
||||
fn.tags.put("env", "prod");
|
||||
when(service.getFunction(REGION, "app")).thenReturn(fn);
|
||||
WebFunction retagged = function(FN_ARN);
|
||||
retagged.tags.put("team", "web");
|
||||
retagged.updatedAt = fn.updatedAt.plusSeconds(5);
|
||||
when(service.replaceTags(REGION, "app", Map.of("team", "web"))).thenReturn(retagged);
|
||||
StackResource prior = resource(LambdaWebCfnProvisioner.FUNCTION);
|
||||
prior.setPhysicalId(FN_ARN);
|
||||
ObjectNode props = mapper.createObjectNode().put("FunctionName", "app");
|
||||
props.putArray("Tags").addObject().put("Key", "team").put("Value", "web");
|
||||
|
||||
StackResource r = updateOf(prior);
|
||||
provisioner.provision(r, props, ctx(FN_ARN));
|
||||
|
||||
verify(service).replaceTags(REGION, "app", Map.of("team", "web"));
|
||||
verify(service, never()).createFunctionShell(anyString(), anyString(), any());
|
||||
assertEquals(FN_ARN, r.getPhysicalId());
|
||||
assertEquals(LambdaWebService.formatTimestamp(retagged.updatedAt), r.getAttributes().get("UpdatedAt"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
// A failed stack update puts the prior tags back.
|
||||
assertTrue(r.getAttributes().containsKey(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR));
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
verify(service).replaceTags(REGION, FN_ARN, Map.of("env", "prod"));
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionUpdateWithTheSameTagsWritesNothing() {
|
||||
WebFunction fn = function(FN_ARN);
|
||||
fn.tags.put("env", "prod");
|
||||
when(service.getFunction(REGION, "app")).thenReturn(fn);
|
||||
ObjectNode props = mapper.createObjectNode().put("FunctionName", "app");
|
||||
props.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.FUNCTION);
|
||||
r.setPhysicalId(FN_ARN);
|
||||
|
||||
provisioner.provision(r, props, ctx(FN_ARN));
|
||||
|
||||
verify(service, never()).replaceTags(anyString(), anyString(), any());
|
||||
assertEquals(FN_ARN, r.getPhysicalId());
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR));
|
||||
assertFalse(provisioner.rollbackUpdate(r), "nothing changed in place, so there is nothing to put back");
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionUpdateWithANewNameCreatesAndDisplacesThePriorFunction() {
|
||||
when(service.getFunction(REGION, "app2"))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "The function does not exist.", 404));
|
||||
when(service.createFunctionShell(REGION, "app2", Map.of()))
|
||||
.thenReturn(function("arn:aws:lambda:us-east-1:000000000000:web-function/app2"));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.FUNCTION);
|
||||
r.setPhysicalId(FN_ARN);
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("FunctionName", "app2"), ctx(FN_ARN));
|
||||
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:web-function/app2", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals(FN_ARN, provisioner.updateCleanupPhysicalId(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void integerPropertiesGivenAsTextArriveAsNumbers() {
|
||||
when(service.createRevision(eq(REGION), eq("app"), any())).thenReturn(revision("rev-aaaaa"));
|
||||
when(service.createEndpoint(eq(REGION), eq("app"), any()))
|
||||
.thenReturn(endpoint("prod", "HomeRegion", List.of("us-east-1")));
|
||||
ObjectNode revisionProps = revisionProps();
|
||||
((ObjectNode) revisionProps.get("ServiceConfig")).put("TimeoutSeconds", "45").put("MaxConcurrencyPerEnvironment", "8");
|
||||
ObjectNode endpointProps = endpointProps("HomeRegion");
|
||||
((ObjectNode) endpointProps.get("RevisionWeights").get(0)).put("Weight", "100");
|
||||
endpointProps.putObject("ScalingConfig").put("MaxEnvironments", "4");
|
||||
endpointProps.putObject("ThrottleConfig").put("RateLimit", "x");
|
||||
|
||||
provisioner.provision(resource(LambdaWebCfnProvisioner.REVISION), revisionProps, ctx(null));
|
||||
provisioner.provision(resource(LambdaWebCfnProvisioner.ENDPOINT), endpointProps, ctx(null));
|
||||
|
||||
ArgumentCaptor<JsonNode> revision = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createRevision(eq(REGION), eq("app"), revision.capture());
|
||||
assertTrue(revision.getValue().path("serviceConfig").path("timeoutSeconds").isIntegralNumber());
|
||||
assertEquals(45, revision.getValue().path("serviceConfig").path("timeoutSeconds").intValue());
|
||||
assertEquals(8, revision.getValue().path("serviceConfig").path("maxConcurrencyPerEnvironment").intValue());
|
||||
ArgumentCaptor<JsonNode> endpoint = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createEndpoint(eq(REGION), eq("app"), endpoint.capture());
|
||||
assertEquals(100, endpoint.getValue().path("revisionWeights").get(0).path("weight").intValue());
|
||||
assertEquals(4, endpoint.getValue().path("scalingConfig").path("maxEnvironments").intValue());
|
||||
assertTrue(endpoint.getValue().path("throttleConfig").path("rateLimit").isTextual(),
|
||||
"text that is not an integer is left for the service to reject");
|
||||
}
|
||||
|
||||
@Test
|
||||
void revisionPropertiesReachTheServiceInCamelCase() {
|
||||
when(service.createRevision(eq(REGION), eq("app"), any())).thenReturn(revision("rev-aaaaa"));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.REVISION);
|
||||
ObjectNode props = revisionProps();
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
verify(engine).resolveNodeOmittingNoValue(props);
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createRevision(eq(REGION), eq("app"), request.capture());
|
||||
JsonNode sent = request.getValue();
|
||||
assertEquals("code", sent.path("buildConfig").path("codeConfig").path("s3Object").path("bucket").asText());
|
||||
assertEquals("nodejs24.x", sent.path("buildConfig").path("runtimeConfig").path("runtime").asText());
|
||||
assertEquals(45, sent.path("serviceConfig").path("timeoutSeconds").asInt());
|
||||
assertEquals("2", sent.path("serviceConfig").path("environmentVariables").path("APP_VERSION").asText(),
|
||||
"environment variable keys are the user's own and are not lowered");
|
||||
assertEquals("first", sent.path("description").asText());
|
||||
assertFalse(sent.has("functionName"));
|
||||
assertEquals(FN_ARN + "/revision/rev-aaaaa", r.getPhysicalId());
|
||||
assertEquals(REVISION_ATTRIBUTES, r.getAttributes().keySet());
|
||||
assertEquals("rev-aaaaa", r.getAttributes().get("RevisionId"));
|
||||
assertEquals(FN_ARN + "/revision/rev-aaaaa", r.getAttributes().get("RevisionArn"));
|
||||
assertEquals(FN_ARN, r.getAttributes().get("FunctionArn"));
|
||||
assertEquals("Active", r.getAttributes().get("State"));
|
||||
assertEquals("The revision is active.", r.getAttributes().get("StateReason"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedRevisionIsKeptOnUpdate() {
|
||||
WebFunctionRevision existing = revision("rev-aaaaa");
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getRevision(REGION, FN_ARN, existing.revisionArn)).thenReturn(existing);
|
||||
when(service.revisionMatches(eq(existing), any())).thenReturn(true);
|
||||
StackResource prior = resource(LambdaWebCfnProvisioner.REVISION);
|
||||
prior.setPhysicalId(existing.revisionArn);
|
||||
|
||||
StackResource r = updateOf(prior);
|
||||
provisioner.provision(r, revisionProps(), ctx(existing.revisionArn));
|
||||
|
||||
verify(service, never()).createRevision(anyString(), anyString(), any());
|
||||
assertEquals(existing.revisionArn, r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changedRevisionIsReplacedAndTheOldOneOwedADelete() {
|
||||
WebFunctionRevision existing = revision("rev-aaaaa");
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getRevision(REGION, FN_ARN, existing.revisionArn)).thenReturn(existing);
|
||||
when(service.revisionMatches(eq(existing), any())).thenReturn(false);
|
||||
when(service.createRevision(eq(REGION), eq("app"), any())).thenReturn(revision("rev-bbbbb"));
|
||||
StackResource prior = resource(LambdaWebCfnProvisioner.REVISION);
|
||||
prior.setPhysicalId(existing.revisionArn);
|
||||
prior.getAttributes().put("RevisionId", "rev-aaaaa");
|
||||
|
||||
StackResource r = updateOf(prior);
|
||||
provisioner.provision(r, revisionProps(), ctx(existing.revisionArn));
|
||||
|
||||
assertEquals(FN_ARN + "/revision/rev-bbbbb", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals(existing.revisionArn, provisioner.updateCleanupPhysicalId(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void revisionOfAnotherFunctionIsNotReused() {
|
||||
WebFunctionRevision existing = revision("rev-aaaaa");
|
||||
when(service.getFunction(REGION, "other")).thenReturn(function(OTHER_FN_ARN));
|
||||
when(service.getRevision(REGION, FN_ARN, existing.revisionArn)).thenReturn(existing);
|
||||
when(service.revisionMatches(eq(existing), any())).thenReturn(true);
|
||||
when(service.createRevision(eq(REGION), eq("other"), any())).thenReturn(revision("rev-bbbbb"));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.REVISION);
|
||||
r.setPhysicalId(existing.revisionArn);
|
||||
|
||||
provisioner.provision(r, revisionProps().put("FunctionName", "other"), ctx(existing.revisionArn));
|
||||
|
||||
verify(service).createRevision(eq(REGION), eq("other"), any());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void autoDeploymentModeIsNotACloudFormationProperty() {
|
||||
ObjectNode props = endpointProps("HomeRegion").put("AutoDeploymentMode", "LatestRevision");
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
|
||||
() -> provisioner.provision(r, props, ctx(null)));
|
||||
assertTrue(e.getMessage().contains("AutoDeploymentMode"), e.getMessage());
|
||||
verify(service, never()).createEndpoint(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointPropertiesReachTheServiceInCamelCase() {
|
||||
when(service.createEndpoint(eq(REGION), eq("app"), any()))
|
||||
.thenReturn(endpoint("prod", "MultiRegion", List.of("us-east-1", "us-west-2")));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
ObjectNode props = endpointProps("MultiRegion");
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
verify(engine).resolveNodeOmittingNoValue(props);
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createEndpoint(eq(REGION), eq("app"), request.capture());
|
||||
JsonNode sent = request.getValue();
|
||||
assertEquals("prod", sent.path("endpointName").asText());
|
||||
assertEquals("IamAuth", sent.path("authType").asText());
|
||||
assertEquals("rev-aaaaa", sent.path("revisionWeights").get(0).path("revisionId").asText());
|
||||
assertEquals(100, sent.path("revisionWeights").get(0).path("weight").asInt());
|
||||
assertEquals("us-west-2", sent.path("regions").get(0).asText());
|
||||
assertEquals(FN_ARN + "/endpoint/prod", r.getPhysicalId());
|
||||
assertEquals(ENDPOINT_ATTRIBUTES, r.getAttributes().keySet());
|
||||
assertEquals("abc.001.lambda-web.us-east-1.localhost:4566", r.getAttributes().get("DomainName"));
|
||||
assertEquals("The endpoint is active and invokable.", r.getAttributes().get("StateReason"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointWithTheSameIdentityIsUpdatedInPlace() {
|
||||
WebFunctionEndpoint existing = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
existing.authType = "ApplicationManaged";
|
||||
existing.autoDeploymentMode = "LatestRevision";
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getEndpoint(REGION, FN_ARN, existing.endpointArn)).thenReturn(existing);
|
||||
WebFunctionEndpoint updated = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
updated.updateStatus = "Successful";
|
||||
when(service.updateEndpoint(eq(REGION), eq("app"), eq("prod"), any()))
|
||||
.thenReturn(new LambdaWebService.EndpointUpdate(existing, updated));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
r.setPhysicalId(existing.endpointArn);
|
||||
|
||||
provisioner.provision(r, endpointProps("HomeRegion"), ctx(existing.endpointArn));
|
||||
|
||||
ArgumentCaptor<JsonNode> patch = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updateEndpoint(eq(REGION), eq("app"), eq("prod"), patch.capture());
|
||||
assertEquals("IamAuth", patch.getValue().path("authType").asText());
|
||||
assertFalse(patch.getValue().has("endpointType"));
|
||||
assertFalse(patch.getValue().has("scalingConfig"), "a config the stack never declared is left alone");
|
||||
assertFalse(patch.getValue().has("throttleConfig"));
|
||||
assertFalse(patch.getValue().has("description"));
|
||||
verify(service, never()).createEndpoint(anyString(), anyString(), any());
|
||||
assertEquals(existing.endpointArn, r.getPhysicalId());
|
||||
Set<String> expected = new HashSet<>(ENDPOINT_ATTRIBUTES);
|
||||
expected.add("UpdateStatus");
|
||||
expected.add("UpdateStatusReason");
|
||||
expected.add(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR);
|
||||
assertEquals(expected, r.getAttributes().keySet());
|
||||
assertEquals("Successful", r.getAttributes().get("UpdateStatus"));
|
||||
assertEquals("The endpoint is updated.", r.getAttributes().get("UpdateStatusReason"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
// A failed stack update puts the prior configuration back.
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
ArgumentCaptor<JsonNode> restored = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updateEndpoint(eq(REGION), eq(FN_ARN), eq("prod"), restored.capture());
|
||||
assertEquals("ApplicationManaged", restored.getValue().path("authType").asText());
|
||||
assertEquals("LatestRevision", restored.getValue().path("autoDeploymentMode").asText());
|
||||
assertFalse(restored.getValue().has("revisionWeights"));
|
||||
assertEquals("", restored.getValue().path("description").asText());
|
||||
assertTrue(restored.getValue().path("scalingConfig").isEmpty());
|
||||
assertTrue(restored.getValue().path("throttleConfig").isEmpty());
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void propertiesThePreviousTemplateDeclaredAreClearedWhenDropped() {
|
||||
WebFunctionEndpoint existing = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getEndpoint(REGION, FN_ARN, existing.endpointArn)).thenReturn(existing);
|
||||
when(service.updateEndpoint(eq(REGION), eq("app"), eq("prod"), any()))
|
||||
.thenReturn(new LambdaWebService.EndpointUpdate(existing, existing));
|
||||
ObjectNode priorProps = endpointProps("HomeRegion").put("Description", "blue");
|
||||
priorProps.putObject("ScalingConfig").put("MaxEnvironments", 4);
|
||||
priorProps.putObject("ThrottleConfig").put("RateLimit", 100);
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
r.setPhysicalId(existing.endpointArn);
|
||||
|
||||
provisioner.provision(r, endpointProps("HomeRegion"), ctx(existing.endpointArn, priorProps));
|
||||
|
||||
ArgumentCaptor<JsonNode> patch = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updateEndpoint(eq(REGION), eq("app"), eq("prod"), patch.capture());
|
||||
assertTrue(patch.getValue().path("scalingConfig").isObject() && patch.getValue().path("scalingConfig").isEmpty());
|
||||
assertTrue(patch.getValue().path("throttleConfig").isObject() && patch.getValue().path("throttleConfig").isEmpty());
|
||||
assertEquals("", patch.getValue().path("description").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointWithAChangedTypeIsRefusedAsACustomNamedReplacement() {
|
||||
WebFunctionEndpoint existing = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getEndpoint(REGION, FN_ARN, existing.endpointArn)).thenReturn(existing);
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
r.setPhysicalId(existing.endpointArn);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, endpointProps("PerRegion"), ctx(existing.endpointArn)));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing."
|
||||
+ " Rename prod and update the stack again.", e.getMessage());
|
||||
verify(service, never()).createEndpoint(anyString(), anyString(), any());
|
||||
verify(service, never()).updateEndpoint(anyString(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamedEndpointIsReplacedAndTheOldOneOwedADelete() {
|
||||
WebFunctionEndpoint existing = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getEndpoint(REGION, FN_ARN, existing.endpointArn)).thenReturn(existing);
|
||||
when(service.createEndpoint(eq(REGION), eq("app"), any()))
|
||||
.thenReturn(endpoint("prod2", "HomeRegion", List.of("us-east-1")));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
r.setPhysicalId(existing.endpointArn);
|
||||
r.getAttributes().put("UpdateStatus", "Successful");
|
||||
r.getAttributes().put("UpdateStatusReason", "The endpoint is updated.");
|
||||
|
||||
provisioner.provision(r, endpointProps("HomeRegion").put("EndpointName", "prod2"), ctx(existing.endpointArn));
|
||||
|
||||
assertEquals(FN_ARN + "/endpoint/prod2", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals(existing.endpointArn, provisioner.updateCleanupPhysicalId(r));
|
||||
Set<String> published = new HashSet<>(r.getAttributes().keySet());
|
||||
published.removeIf(key -> key.startsWith("__Floci"));
|
||||
assertEquals(ENDPOINT_ATTRIBUTES, published, "a replacement does not inherit UpdateStatus");
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointMovedToAnotherFunctionIsCreatedThere() {
|
||||
WebFunctionEndpoint existing = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
when(service.getFunction(REGION, "other")).thenReturn(function(OTHER_FN_ARN));
|
||||
when(service.getEndpoint(REGION, FN_ARN, existing.endpointArn)).thenReturn(existing);
|
||||
WebFunctionEndpoint created = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
created.endpointArn = OTHER_FN_ARN + "/endpoint/prod";
|
||||
created.functionArn = OTHER_FN_ARN;
|
||||
when(service.createEndpoint(eq(REGION), eq("other"), any())).thenReturn(created);
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
r.setPhysicalId(existing.endpointArn);
|
||||
|
||||
provisioner.provision(r, endpointProps("HomeRegion").put("FunctionName", "other"), ctx(existing.endpointArn));
|
||||
|
||||
verify(service, never()).updateEndpoint(anyString(), anyString(), anyString(), any());
|
||||
assertEquals(OTHER_FN_ARN + "/endpoint/prod", r.getPhysicalId());
|
||||
assertEquals(existing.endpointArn, provisioner.updateCleanupPhysicalId(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPriorLookupFailureOtherThanNotFoundPropagates() {
|
||||
when(service.getFunction(REGION, "app")).thenReturn(function(FN_ARN));
|
||||
when(service.getEndpoint(REGION, FN_ARN, FN_ARN + "/endpoint/prod"))
|
||||
.thenThrow(new AwsException("ValidationException", "Invalid endpoint name or ARN", 400));
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
r.setPhysicalId(FN_ARN + "/endpoint/prod");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, endpointProps("HomeRegion"), ctx(FN_ARN + "/endpoint/prod")));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletesTolerateAnAbsentResourceButNotARevisionStillInUse() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "The function " + FN_ARN + " does not exist.", 404))
|
||||
.when(service).deleteEndpoint(REGION, FN_ARN, FN_ARN + "/endpoint/prod");
|
||||
provisioner.delete(LambdaWebCfnProvisioner.ENDPOINT, FN_ARN + "/endpoint/prod", REGION);
|
||||
|
||||
doThrow(new AwsException("ConflictException", "in use", 409))
|
||||
.when(service).deleteRevision(REGION, FN_ARN, FN_ARN + "/revision/rev-aaaaa");
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(LambdaWebCfnProvisioner.REVISION, FN_ARN + "/revision/rev-aaaaa", REGION));
|
||||
|
||||
provisioner.delete(LambdaWebCfnProvisioner.FUNCTION, FN_ARN, REGION);
|
||||
verify(service).deleteFunction(REGION, FN_ARN);
|
||||
}
|
||||
}
|
||||
@@ -364,6 +364,27 @@ class LambdaWebServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void revisionMatchesComparesTheConfigurationAfterDefaults() {
|
||||
LambdaWebService service = service();
|
||||
WebFunction fn = service.createFunction(REGION, createRequest("app"));
|
||||
WebFunctionRevision revision = fn.revisions.values().iterator().next();
|
||||
assertTrue(service.revisionMatches(revision, revisionConfig(30)));
|
||||
assertFalse(service.revisionMatches(revision, revisionConfig(31)));
|
||||
ObjectNode described = revisionConfig(30).put("description", "d");
|
||||
assertFalse(service.revisionMatches(revision, described));
|
||||
// The default log group is the function's, so writing it out matches and dropping a custom one does not.
|
||||
ObjectNode explicit = revisionConfig(30);
|
||||
((ObjectNode) explicit.get("serviceConfig")).putObject("telemetryConfig").putObject("loggingConfig")
|
||||
.put("logGroup", "/aws/lambda/web/app");
|
||||
assertTrue(service.revisionMatches(revision, explicit));
|
||||
ObjectNode custom = revisionConfig(30);
|
||||
((ObjectNode) custom.get("serviceConfig")).putObject("telemetryConfig").putObject("loggingConfig")
|
||||
.put("logGroup", "custom-group");
|
||||
WebFunctionRevision customized = service.createRevision(REGION, "app", custom);
|
||||
assertFalse(service.revisionMatches(customized, revisionConfig(30)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void identifiersAcceptArnsOfTheHomeRegionAndAccount() {
|
||||
LambdaWebService service = service();
|
||||
|
||||
@@ -19,6 +19,7 @@ AWS::Lambda::MicrovmImage LatestFailedImageVersion failure history is not tracke
|
||||
AWS::Lambda::MicrovmImage State microvm image state is not modelled
|
||||
AWS::Lambda::MicrovmImage UpdatedAt microvm image lifecycle fields are not tracked
|
||||
AWS::Lambda::NetworkConnector State network connector state is not modelled
|
||||
AWS::Lambda::WebFunctionEndpoint RegionalEndpoints the attribute is a map of per-region state, and Floci GetAtt values are strings; the endpoint's own State and UpdateStatus carry the same values
|
||||
AWS::Lambda::Permission Id schema gives no description and AWS's value is unclear; the physical id is a composite functionName|statementId
|
||||
AWS::Pipes::Pipe CreationTime pipe lifecycle timestamps are not tracked
|
||||
AWS::Pipes::Pipe CurrentState pipe state transitions are not modelled
|
||||
|
||||
|
@@ -134,6 +134,9 @@ AWS::Lambda::NetworkConnector LambdaMicrovmsCfnProvisioner
|
||||
AWS::Lambda::Permission LambdaAddressingCfnProvisioner
|
||||
AWS::Lambda::Url LambdaAddressingCfnProvisioner
|
||||
AWS::Lambda::Version LambdaVersionAliasCfnProvisioner
|
||||
AWS::Lambda::WebFunction LambdaWebCfnProvisioner
|
||||
AWS::Lambda::WebFunctionEndpoint LambdaWebCfnProvisioner
|
||||
AWS::Lambda::WebFunctionRevision LambdaWebCfnProvisioner
|
||||
AWS::Logs::LogGroup LogsCfnProvisioner
|
||||
AWS::Logs::LogStream LogsLogStreamCfnProvisioner
|
||||
AWS::Logs::MetricFilter LogsMetricFilterCfnProvisioner
|
||||
|
||||
|
@@ -177,6 +177,9 @@ notes:
|
||||
AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored'
|
||||
AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands into
|
||||
AWS::Lambda::EventInvokeConfig: also what a SAM function's `EventInvokeConfig` expands into
|
||||
AWS::Lambda::WebFunction: control plane only; the endpoint domain does not serve requests yet
|
||||
AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision
|
||||
AWS::Lambda::WebFunctionEndpoint: '`RegionalEndpoints` is not exposed to `Fn::GetAtt` yet'
|
||||
AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS'
|
||||
AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported
|
||||
AWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling'
|
||||
|
||||
Reference in new issue
Block a user