feat(lambda): version network connectors as AWS does (#6595)

* feat(lambdamicrovms): version network connectors as AWS does

* fix(lambda): lock connector versions and refresh them after a CFN rollback

Updates, deletes and version reads hold one lock, so two updates cannot
take the same version number.

A CloudFormation rollback restores the connector through an update. On
AWS that makes the next version, and a later Fn::GetAtt returns it. The
resource now keeps that version in LatestVersion and LatestVersionArn.

Read the connector ARN through AwsArnUtils.parse.

AWS refuses LatestVersion, an integer, as a string Output, so the stack
test reads LatestVersionArn only.

* fix(lambda): type the connector LatestVersion attribute as an integer

AWS::Lambda::NetworkConnector declares LatestVersion as an integer. On AWS
a stack whose string Output reads it fails with "Template format error:
Every Value member must be a string.", and Fn::Sub refuses it with
"variable Connector.LatestVersion in Fn::Sub expression does not resolve
to a string".

* chore(lambda): share the connector version ARN and integer attribute helpers
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-26 08:38:47 -04:00
1 parent f32db4fe49
commit 3438a00daf
14 files changed
+650 -78

No files matched your search

@@ -235,6 +235,35 @@ create_image() {
CONNECTOR_ID=""
}
@test "MicroVMs: a network connector update makes the next version" {
name=$(unique_name "cli-conn-ver")
run aws_cmd lambda-core create-network-connector \
--name "$name" \
--operator-role "arn:aws:iam::000000000000:role/microvm-connector-operator" \
--configuration "VpcEgressConfiguration={AssociatedComputeResourceTypes=WebFunction,NetworkProtocol=IPv4,SubnetIds=subnet-0000000000000cli1,SecurityGroupIds=sg-0000000000000cli1}"
assert_success
CONNECTOR_ID=$(json_get "$output" '.Id')
[ "$(json_get "$output" '.Version')" = "1" ]
run aws_cmd lambda-core update-network-connector --identifier "$CONNECTOR_ID" \
--configuration '{"VpcEgressConfiguration":{"SubnetIds":["subnet-0000000000000cli1","subnet-0000000000000cli2"]}}'
assert_success
[ "$(json_get "$output" '.Version')" = "2" ]
run aws_cmd lambda-core get-network-connector --identifier "$name:1"
assert_success
[ "$(json_get "$output" '.Version')" = "1" ]
[ "$(json_get "$output" '.Configuration.VpcEgressConfiguration.SubnetIds | length')" = "1" ]
run aws_cmd lambda-core list-network-connector-versions --identifier "$CONNECTOR_ID"
assert_success
[ "$(json_get "$output" '[.NetworkConnectorVersions[].Version] | map(tostring) | join(",")')" = "1,2" ]
run aws_cmd lambda-core delete-network-connector --identifier "$CONNECTOR_ID"
assert_success
CONNECTOR_ID=""
}
@test "MicroVMs: get a nonexistent connector returns not found" {
run aws_cmd lambda-core get-network-connector --id "nc-00000000000000cli"
assert_failure
+2 -1
View File
@@ -648,7 +648,8 @@ a list is `Template format error: unsupported structure.`
## Attribute types
`AWS::EC2::PrefixList` `Version` remains numeric when used as another resource's property.
`AWS::EC2::PrefixList` `Version` and `AWS::Lambda::NetworkConnector` `LatestVersion` remain numeric when used as
another resource's property.
Numeric attributes are rejected in string outputs and `Fn::Join`, `Fn::Sub`,
`Fn::Split`, and `Fn::Base64`, including selected `Fn::If` and `Fn::Select` values.
Literal numbers and Number-parameter references retain their existing string coercion.
+6 -4
View File
@@ -39,10 +39,11 @@ Two AWS service models, not one. `Lambda Microvms` (apiVersion 2025-09-09) carri
| Action | Description |
| --- | --- |
| `CreateNetworkConnector` | Create a VPC egress connector |
| `GetNetworkConnector` | Connector detail |
| `GetNetworkConnector` | Connector detail, or one version with `:<version>` |
| `ListNetworkConnectors` | List connectors — a six-member summary per item |
| `UpdateNetworkConnector` | Replace the connector configuration |
| `DeleteNetworkConnector` | Asynchronous delete, answers `DELETING` |
| `ListNetworkConnectorVersions` | The versions of a connector, oldest first |
| `UpdateNetworkConnector` | Replace the connector configuration. A change makes the next version |
| `DeleteNetworkConnector` | Asynchronous delete, answers `DELETING`. With `:<version>`, deletes only that version |
## Emulation Behavior
@@ -50,12 +51,13 @@ Two AWS service models, not one. `Lambda Microvms` (apiVersion 2025-09-09) carri
- **Per-operation projections:** an image is returned in four different shapes and a connector in four. Create and Update carry full detail, Get is a smaller summary, and only the list summaries carry `Type`. Absent members are absent rather than null — a connector that has never been updated has no `LastUpdateStatus` at all.
- **Members the model marks optional but the service enforces:** a connector requires `ClientToken`, `OperatorRole`, `NetworkProtocol` and `AssociatedComputeResourceTypes`. A client written from the Smithy model alone receives four validation errors in turn.
- **ARN or bare identifier:** images, MicroVMs and connectors resolve by either in URI paths.
- **Connector versions:** a connector starts at version 1. As on AWS, an update that changes the subnets, the security groups, the network protocol or the operator role makes the next version, and one that only lists the subnets in another order changes nothing. A connector also resolves by its name, and `:<version>` after an id, a name or an ARN names one version. The latest version cannot be deleted on its own, and `AssociatedComputeResourceTypes` cannot change. Errors use the AWS wording.
- **Builds per generation:** each version is built once per Graviton generation the service targets, so a version has more than one build.
- **Not emulated:** auth tokens, the per-VM endpoint, idle and suspend timers, and suspend/resume. Those belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning; see [m80](https://github.com/INTENTIUS/m80).
## CloudFormation
`AWS::Lambda::MicrovmImage` and `AWS::Lambda::NetworkConnector` provision and delete through the resource registry, so a template declaring either is handled rather than skipped.
`AWS::Lambda::MicrovmImage` and `AWS::Lambda::NetworkConnector` provision and delete through the resource registry, so a template declaring either is handled rather than skipped. A connector returns `LatestVersion` and `LatestVersionArn` through `Fn::GetAtt`.
## Verification
@@ -1,10 +1,12 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
@@ -22,8 +24,16 @@ public interface CfnResourceProvisioner {
Set<String> resourceTypes();
/** GetAtt attributes the registry schema types as integers, by resource type. */
default Map<String, Set<String>> integerAttributes() {
return Map.of();
}
/** The JSON type of a stored GetAtt value; most resource attributes are strings. */
default JsonNode attributeValue(String resourceType, String attributeName, String value) {
if (integerAttributes().getOrDefault(resourceType, Set.of()).contains(attributeName)) {
return LongNode.valueOf(Long.parseLong(value));
}
return TextNode.valueOf(value);
}
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
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.LongNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
@@ -88,11 +87,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
}
@Override
public JsonNode attributeValue(String resourceType, String attributeName, String value) {
if (PREFIX_LIST.equals(resourceType) && "Version".equals(attributeName)) {
return LongNode.valueOf(Long.parseLong(value));
}
return CfnResourceProvisioner.super.attributeValue(resourceType, attributeName, value);
public Map<String, Set<String>> integerAttributes() {
return Map.of(PREFIX_LIST, Set.of("Version"));
}
@Override
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -56,6 +57,11 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner {
return Set.of("AWS::Lambda::MicrovmImage", "AWS::Lambda::NetworkConnector");
}
@Override
public Map<String, Set<String>> integerAttributes() {
return Map.of(NETWORK_CONNECTOR, Set.of("LatestVersion"));
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
@@ -123,10 +129,13 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner {
throw new IllegalStateException("Could not read the network connector update snapshot for "
+ resource.getLogicalId(), e);
}
microvmsService.updateConnector(snapshot.path("region").asText(), snapshot.path("arn").asText(),
LambdaMicrovmsService.NetworkConnector restored = microvmsService.updateConnector(
snapshot.path("region").asText(), snapshot.path("arn").asText(),
textList(snapshot.path("subnetIds")), textList(snapshot.path("securityGroupIds")),
snapshot.path("operatorRole").asText(null), snapshot.path("networkProtocol").asText(null),
textList(snapshot.path("associatedComputeResourceTypes")));
// The restore is an update too, so it makes the next version.
putLatestVersion(resource, restored);
resource.getAttributes().remove(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR);
return true;
}
@@ -194,6 +203,13 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("Arn", connector.arn);
r.getAttributes().put("Id", connector.id);
r.getAttributes().put("Name", connector.name);
putLatestVersion(r, connector);
}
private static void putLatestVersion(StackResource r, LambdaMicrovmsService.NetworkConnector connector) {
r.getAttributes().put("LatestVersion", Long.toString(connector.latestVersion));
r.getAttributes().put("LatestVersionArn",
LambdaArnUtils.networkConnectorVersionArn(connector.arn, connector.latestVersion));
}
/** Records the connector's settings before an in-place update, for {@link #rollbackUpdate}. */
@@ -56,6 +56,11 @@ public final class LambdaArnUtils {
return arn.resource().substring(EVENT_SOURCE_MAPPING_PREFIX.length());
}
/** {@code arn:<partition>:lambda:<region>:<account>:network-connector:<id>:<version>}. */
public static String networkConnectorVersionArn(String connectorArn, long version) {
return connectorArn + ":" + version;
}
/**
* The full function ARN a {@code FunctionName} reference names, the way an IAM policy's
* {@code Resource} names it. The reference is read as {@link #resolve} reads it, so a malformed
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
@@ -17,7 +18,9 @@ import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
@@ -47,6 +50,7 @@ public class LambdaMicrovmsService {
private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_]{1,64}");
private static final int MAX_CONNECTOR_SUBNETS = 16;
private static final Pattern CONNECTOR_VERSION = Pattern.compile("[1-9][0-9]{0,17}");
/** The one AWS-managed base image the catalog serves. */
private static final String MANAGED_IMAGE = "al2023-1";
@@ -411,9 +415,33 @@ public class LambdaMicrovmsService {
public String stateReason;
public String lastUpdateStatus;
public String lastUpdateStatusReason;
public long latestVersion = 1;
/** Oldest first. The latest one has the configuration above. */
public List<NetworkConnectorVersion> versions = new ArrayList<>();
public final Map<String, String> tags = new LinkedHashMap<>();
}
@RegisterForReflection
public static final class NetworkConnectorVersion {
public long version;
public String state;
public String stateReason;
public String operatorRole;
public List<String> subnetIds = List.of();
public List<String> securityGroupIds = List.of();
public String networkProtocol;
public List<String> associatedComputeResourceTypes = List.of();
public Instant lastModified;
}
/** A connector and the version an identifier names, the latest one when it names none. */
public record ConnectorVersion(NetworkConnector connector, NetworkConnectorVersion version, boolean qualified) {
public String versionArn() {
return LambdaArnUtils.networkConnectorVersionArn(connector.arn, version.version);
}
}
public NetworkConnector createConnector(String region, String accountId, String name,
List<String> subnetIds, List<String> securityGroupIds,
String operatorRole, String clientToken,
@@ -465,16 +493,23 @@ public class LambdaMicrovmsService {
connector.stateReason = "Initial creation";
// Settle instantly, as with VMs.
connector.state = "ACTIVE";
connector.versions.add(snapshot(connector, 1));
connectors.put(key(region, connector.id), connector);
// The create response is a snapshot taken before the instant settle,
// so it reports PENDING while the stored connector is already ACTIVE.
// It has to carry every member the stored one does, or a client reads
// back less than it just sent.
NetworkConnector response = responseOf(connector);
response.state = "PENDING";
return response;
}
private static NetworkConnector responseOf(NetworkConnector connector) {
NetworkConnector response = new NetworkConnector();
response.id = connector.id;
response.name = connector.name;
response.arn = connector.arn;
response.state = "PENDING";
response.state = connector.state;
response.operatorRole = connector.operatorRole;
response.subnetIds = connector.subnetIds;
response.securityGroupIds = connector.securityGroupIds;
@@ -482,18 +517,99 @@ public class LambdaMicrovmsService {
response.associatedComputeResourceTypes = connector.associatedComputeResourceTypes;
response.lastModified = connector.lastModified;
response.stateReason = connector.stateReason;
response.lastUpdateStatus = connector.lastUpdateStatus;
response.lastUpdateStatusReason = connector.lastUpdateStatusReason;
response.latestVersion = connector.latestVersion;
return response;
}
public NetworkConnector getConnector(String region, String id) {
NetworkConnector connector = connectors.get(key(region, unwrap(id)));
private static NetworkConnectorVersion snapshot(NetworkConnector connector, long version) {
NetworkConnectorVersion out = new NetworkConnectorVersion();
out.version = version;
out.state = connector.state;
out.stateReason = connector.stateReason;
out.operatorRole = connector.operatorRole;
out.subnetIds = connector.subnetIds;
out.securityGroupIds = connector.securityGroupIds;
out.networkProtocol = connector.networkProtocol;
out.associatedComputeResourceTypes = connector.associatedComputeResourceTypes;
out.lastModified = connector.lastModified;
return out;
}
public NetworkConnector getConnector(String region, String identifier) {
return getConnectorVersion(region, identifier).connector();
}
/**
* The identifier is an id, a name or an ARN, each with an optional {@code :<version>}. AWS names
* the full ARN, with the version asked for, when either is missing.
*/
public synchronized ConnectorVersion getConnectorVersion(String region, String identifier) {
ConnectorRef ref = ConnectorRef.parse(identifier);
NetworkConnector connector = find(region, ref);
long wanted = ref.version() == null ? connector.latestVersion : ref.version();
NetworkConnectorVersion found = connector.versions.stream()
.filter(v -> v.version == wanted)
.findFirst()
.orElseThrow(() -> connectorNotFound(LambdaArnUtils.networkConnectorVersionArn(connector.arn, wanted)));
return new ConnectorVersion(connector, found, ref.version() != null);
}
/** Oldest first. */
public synchronized List<NetworkConnectorVersion> listConnectorVersions(String region, String identifier) {
ConnectorRef ref = ConnectorRef.parse(identifier);
if (ref.version() != null) {
throw new AwsException("InvalidParameterValueException",
"Identifier must not include a version qualifier", 400);
}
return List.copyOf(find(region, ref).versions);
}
private record ConnectorRef(String unqualified, boolean arn, String idOrName, Long version) {
static ConnectorRef parse(String identifier) {
boolean arn = AwsArnUtils.isArn(identifier);
// network-connector:<id>, with an optional :<version>
String[] resource = arn ? AwsArnUtils.parse(identifier).resource().split(":", -1) : null;
String unqualified = identifier;
Long version = null;
int colon = identifier.lastIndexOf(':');
if (colon >= 0 && (!arn || resource.length == 3)
&& CONNECTOR_VERSION.matcher(identifier.substring(colon + 1)).matches()) {
unqualified = identifier.substring(0, colon);
version = Long.parseLong(identifier.substring(colon + 1));
}
String idOrName = arn ? unqualified.substring(unqualified.lastIndexOf(':') + 1) : unqualified;
return new ConnectorRef(unqualified, arn, idOrName, version);
}
}
private NetworkConnector find(String region, ConnectorRef ref) {
NetworkConnector connector = connectors.get(key(region, ref.idOrName()));
if (connector == null) {
throw new AwsException("ResourceNotFoundException",
"Network connector not found: " + id, 404);
connector = in(connectors, region)
.filter(c -> ref.idOrName().equals(c.name))
.findFirst()
.orElseThrow(() -> {
String arn = ref.arn() ? ref.unqualified()
: AwsArnUtils.Arn.of("lambda", region, regionResolver.getAccountId(),
"network-connector:" + ref.idOrName()).toString();
return connectorNotFound(ref.version() == null ? arn
: LambdaArnUtils.networkConnectorVersionArn(arn, ref.version()));
});
}
// One stored before versions has only its latest version.
if (connector.versions.isEmpty()) {
connector.versions.add(snapshot(connector, connector.latestVersion));
}
return connector;
}
private static AwsException connectorNotFound(String arn) {
return new AwsException("ResourceNotFoundException", "Network connector not found: " + arn, 404);
}
public List<NetworkConnector> listConnectors(String region) {
return in(connectors, region)
.sorted(Comparator.comparing(c -> c.id))
@@ -502,46 +618,73 @@ public class LambdaMicrovmsService {
/**
* UpdateNetworkConnector: every member is optional and a null one leaves the connector's value
* as it is. The model lets an update change the operator role, the network protocol and the
* associated compute resource types as well as the subnets and security groups.
* as it is. As on AWS, an update that changes the configuration or the operator role makes the
* next version, one that changes nothing keeps the version, and the compute resource types
* cannot change. Updates hold the service lock, so a version names the one update that made it.
*/
public NetworkConnector updateConnector(String region, String id,
List<String> subnetIds, List<String> securityGroupIds,
String operatorRole, String networkProtocol,
List<String> computeResourceTypes) {
public synchronized NetworkConnector updateConnector(String region, String id,
List<String> subnetIds, List<String> securityGroupIds,
String operatorRole, String networkProtocol,
List<String> computeResourceTypes) {
NetworkConnector connector = getConnector(region, id);
if (subnetIds != null && !subnetIds.isEmpty()) {
if (subnetIds.size() > MAX_CONNECTOR_SUBNETS) {
throw new AwsException("InvalidParameterValueException",
"SubnetIds must contain between 1 and " + MAX_CONNECTOR_SUBNETS + " entries", 400);
}
connector.subnetIds = List.copyOf(subnetIds);
connector.lastModified = Instant.now();
connector.lastUpdateStatus = "Successful";
if (computeResourceTypes != null && !computeResourceTypes.isEmpty()
&& !Set.copyOf(computeResourceTypes).equals(Set.copyOf(connector.associatedComputeResourceTypes))) {
throw new AwsException("InvalidParameterValueException",
"AssociatedComputeResourceTypes cannot be changed on an existing network connector. Current: "
+ connector.associatedComputeResourceTypes + ", requested: " + computeResourceTypes + ".", 400);
}
if (subnetIds != null && subnetIds.size() > MAX_CONNECTOR_SUBNETS) {
throw new AwsException("InvalidParameterValueException",
"SubnetIds must contain between 1 and " + MAX_CONNECTOR_SUBNETS + " entries", 400);
}
List<String> newSubnets = subnetIds != null && !subnetIds.isEmpty()
? List.copyOf(subnetIds) : connector.subnetIds;
List<String> newGroups = securityGroupIds != null ? List.copyOf(securityGroupIds) : connector.securityGroupIds;
String newRole = operatorRole != null && !operatorRole.isBlank() ? operatorRole : connector.operatorRole;
String newProtocol = networkProtocol != null && !networkProtocol.isBlank()
? networkProtocol : connector.networkProtocol;
connector.lastModified = Instant.now();
connector.lastUpdateStatus = "Successful";
// AWS keeps the stored order when only the order differs.
if (Set.copyOf(newSubnets).equals(Set.copyOf(connector.subnetIds))
&& Set.copyOf(newGroups).equals(Set.copyOf(connector.securityGroupIds))
&& Objects.equals(newRole, connector.operatorRole)
&& Objects.equals(newProtocol, connector.networkProtocol)) {
connector.lastUpdateStatusReason = "No configuration changes detected";
persist(connectors, region, connector.id, connector);
return responseOf(connector);
}
if (securityGroupIds != null) {
connector.securityGroupIds = List.copyOf(securityGroupIds);
}
if (operatorRole != null && !operatorRole.isBlank()) {
connector.operatorRole = operatorRole;
connector.lastModified = Instant.now();
}
if (networkProtocol != null && !networkProtocol.isBlank()) {
connector.networkProtocol = networkProtocol;
connector.lastModified = Instant.now();
}
if (computeResourceTypes != null && !computeResourceTypes.isEmpty()) {
connector.associatedComputeResourceTypes = List.copyOf(computeResourceTypes);
connector.lastModified = Instant.now();
}
connector.subnetIds = newSubnets;
connector.securityGroupIds = newGroups;
connector.operatorRole = newRole;
connector.networkProtocol = newProtocol;
connector.latestVersion++;
connector.stateReason = "Update initiated";
connector.lastUpdateStatusReason = "Update was successful";
connector.versions.add(snapshot(connector, connector.latestVersion));
persist(connectors, region, connector.id, connector);
return connector;
// Taken before the instant settle, so it reports the update in progress.
NetworkConnector response = responseOf(connector);
response.lastUpdateStatus = "InProgress";
response.lastUpdateStatusReason = "Update in progress";
return response;
}
public void deleteConnector(String region, String id) {
getConnector(region, id);
connectors.remove(key(region, unwrap(id)));
/** Deletes the connector, or only the version the identifier names. Returns what was deleted. */
public synchronized ConnectorVersion deleteConnector(String region, String identifier) {
ConnectorVersion named = getConnectorVersion(region, identifier);
NetworkConnector connector = named.connector();
if (!named.qualified()) {
connectors.remove(key(region, connector.id));
return named;
}
if (named.version().version == connector.latestVersion) {
throw new AwsException("InvalidParameterValueException",
"Cannot delete the latest version of a network connector.", 400);
}
connector.versions.remove(named.version());
persist(connectors, region, connector.id, connector);
return named;
}
// ------------------------------------------------------------------ tags
@@ -6,7 +6,10 @@ 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.core.common.RegionResolver;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.ConnectorVersion;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.NetworkConnector;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.NetworkConnectorVersion;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -87,7 +90,32 @@ public class LambdaNetworkConnectorsController {
public Response getNetworkConnector(@Context HttpHeaders headers,
@PathParam("identifier") String identifier) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(connectorNode(service.getConnector(region, identifier), ConnectorShape.GET)).build();
ConnectorVersion named = service.getConnectorVersion(region, identifier);
return Response.ok(named.qualified() ? versionNode(named, false)
: connectorNode(named.connector(), ConnectorShape.GET)).build();
}
@GET
@Path("/network-connectors/{identifier}/versions")
public Response listNetworkConnectorVersions(@Context HttpHeaders headers,
@PathParam("identifier") String identifier) {
String region = regionResolver.resolveRegion(headers);
List<NetworkConnectorVersion> versions = service.listConnectorVersions(region, identifier);
NetworkConnector connector = service.getConnector(region, identifier);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("NetworkConnectorVersions");
for (NetworkConnectorVersion version : versions) {
ObjectNode item = items.addObject();
item.put("Arn", connector.arn);
item.put("VersionArn", LambdaArnUtils.networkConnectorVersionArn(connector.arn, version.version));
item.put("Name", connector.name);
item.put("Id", connector.id);
item.put("Version", version.version);
item.put("State", version.state);
item.put("StateReason", version.stateReason);
item.put("LastModified", iso(version.lastModified));
}
return Response.ok(root).build();
}
@PUT
@@ -110,19 +138,20 @@ public class LambdaNetworkConnectorsController {
public Response deleteNetworkConnector(@Context HttpHeaders headers,
@PathParam("identifier") String identifier) {
String region = regionResolver.resolveRegion(headers);
// Read the connector before it goes: the delete answers 202 with the
// connector's own body in DELETING, not an empty object.
NetworkConnector doomed = service.getConnector(region, identifier);
ObjectNode body = connectorNode(doomed, ConnectorShape.DELETE);
// The delete answers 202 with the body of what it deletes in DELETING, not an empty object.
ConnectorVersion deleted = service.deleteConnector(region, identifier);
ObjectNode body = deleted.qualified() ? versionNode(deleted, true)
: connectorNode(deleted.connector(), ConnectorShape.DELETE);
body.put("State", "DELETING");
service.deleteConnector(region, identifier);
return Response.status(202).entity(body).build();
}
/**
* The four shapes a connector is returned in. Create and Delete return a
* base six; Get adds LastModified and StateReason; Update adds the update
* status but not StateReason; and only the list summary carries Type.
* base six; Get adds LastModified, StateReason and the update status; Update
* adds the update status but not StateReason; and only the list summary
* carries Type. Get names the latest version, Create and Update the version
* they made, and Delete none.
* Absent means absent — a connector that has never been updated has no
* LastUpdateStatus at all, and sending one as null diverges on every read.
*/
@@ -133,24 +162,18 @@ public class LambdaNetworkConnectorsController {
node.put("Id", connector.id);
node.put("Name", connector.name);
node.put("Arn", connector.arn);
if (shape == ConnectorShape.GET) {
node.put("LatestVersionArn",
LambdaArnUtils.networkConnectorVersionArn(connector.arn, connector.latestVersion));
node.put("LatestVersion", connector.latestVersion);
} else if (shape != ConnectorShape.DELETE) {
node.put("VersionArn", LambdaArnUtils.networkConnectorVersionArn(connector.arn, connector.latestVersion));
node.put("Version", connector.latestVersion);
}
node.put("State", shape == ConnectorShape.CREATE ? "PENDING" : connector.state);
if (connector.operatorRole == null) {
node.putNull("OperatorRole");
} else {
node.put("OperatorRole", connector.operatorRole);
}
ObjectNode vpc = node.putObject("Configuration").putObject("VpcEgressConfiguration");
ArrayNode subnets = vpc.putArray("SubnetIds");
connector.subnetIds.forEach(subnets::add);
ArrayNode sgs = vpc.putArray("SecurityGroupIds");
connector.securityGroupIds.forEach(sgs::add);
// Both arrive on the request; echoing them is what lets a client read
// back what it set.
ArrayNode types = vpc.putArray("AssociatedComputeResourceTypes");
connector.associatedComputeResourceTypes.forEach(types::add);
if (connector.networkProtocol != null) {
vpc.put("NetworkProtocol", connector.networkProtocol);
}
putOperatorRole(node, connector.operatorRole);
putConfiguration(node, connector.subnetIds, connector.securityGroupIds,
connector.associatedComputeResourceTypes, connector.networkProtocol);
if (shape == ConnectorShape.GET || shape == ConnectorShape.UPDATE) {
node.put("LastModified", iso(connector.lastModified));
@@ -158,7 +181,7 @@ public class LambdaNetworkConnectorsController {
if (shape == ConnectorShape.GET && connector.stateReason != null) {
node.put("StateReason", connector.stateReason);
}
if (shape == ConnectorShape.UPDATE) {
if (shape == ConnectorShape.GET || shape == ConnectorShape.UPDATE) {
if (connector.lastUpdateStatus != null) {
node.put("LastUpdateStatus", connector.lastUpdateStatus);
}
@@ -169,6 +192,51 @@ public class LambdaNetworkConnectorsController {
return node;
}
/** A version-qualified Get, or the body of a version-qualified Delete, which has no state reason or time. */
private ObjectNode versionNode(ConnectorVersion named, boolean deleted) {
NetworkConnector connector = named.connector();
NetworkConnectorVersion version = named.version();
ObjectNode node = objectMapper.createObjectNode();
node.put("Id", connector.id);
node.put("Name", connector.name);
node.put("Arn", connector.arn);
node.put("VersionArn", named.versionArn());
node.put("Version", version.version);
node.put("State", version.state);
putOperatorRole(node, version.operatorRole);
putConfiguration(node, version.subnetIds, version.securityGroupIds,
version.associatedComputeResourceTypes, version.networkProtocol);
if (!deleted) {
node.put("StateReason", version.stateReason);
node.put("LastModified", iso(version.lastModified));
}
return node;
}
private static void putOperatorRole(ObjectNode node, String operatorRole) {
if (operatorRole == null) {
node.putNull("OperatorRole");
} else {
node.put("OperatorRole", operatorRole);
}
}
private static void putConfiguration(ObjectNode node, List<String> subnetIds, List<String> securityGroupIds,
List<String> computeResourceTypes, String networkProtocol) {
ObjectNode vpc = node.putObject("Configuration").putObject("VpcEgressConfiguration");
ArrayNode subnets = vpc.putArray("SubnetIds");
subnetIds.forEach(subnets::add);
ArrayNode sgs = vpc.putArray("SecurityGroupIds");
securityGroupIds.forEach(sgs::add);
// Both arrive on the request; echoing them is what lets a client read
// back what it set.
ArrayNode types = vpc.putArray("AssociatedComputeResourceTypes");
computeResourceTypes.forEach(types::add);
if (networkProtocol != null) {
vpc.put("NetworkProtocol", networkProtocol);
}
}
/** The list summary, the only shape carrying Type. */
private ObjectNode connectorSummaryNode(NetworkConnector connector) {
ObjectNode node = objectMapper.createObjectNode();
@@ -178,6 +246,8 @@ public class LambdaNetworkConnectorsController {
node.put("Type", "VPC_EGRESS");
node.put("State", connector.state);
node.put("LastModified", iso(connector.lastModified));
node.put("LatestVersionArn", LambdaArnUtils.networkConnectorVersionArn(connector.arn, connector.latestVersion));
node.put("LatestVersion", connector.latestVersion);
return node;
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
@@ -136,10 +137,12 @@ class CloudFormationLambdaMicrovmsIntegrationTest {
assertTrue(connectorArn.contains(":network-connector:nc-"), connectorArn);
assertEquals(connectorArn, created.get("ConnectorRef"), "Ref is the connector ARN, its primaryIdentifier");
assertEquals(created.get("ImageArn"), created.get("ImageRef"), "Ref is the image ARN, its primaryIdentifier");
assertEquals(connectorArn + ":1", created.get("ConnectorLatestVersionArn"));
cloudFormation(stackName, "UpdateStack", refTemplate(connectorName, "subnet-0cfn000000000002"));
Map<String, String> updated = outputs(describeStacks(stackName, "UPDATE_COMPLETE"));
assertEquals(connectorArn, updated.get("ConnectorRef"), "a subnet change updates the connector in place");
assertEquals(connectorArn + ":2", updated.get("ConnectorLatestVersionArn"));
given()
.when()
.get("/2026-04-04/network-connectors/" + connectorArn)
@@ -157,6 +160,49 @@ class CloudFormationLambdaMicrovmsIntegrationTest {
.statusCode(404));
}
@Test
void latestVersionIsAnIntegerSoAStringOutputFailsTheStack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-microvm-version-" + suffix;
String connectorName = "cfn-microvm-version-connector-" + suffix;
String template = """
{
"Resources": {
"Connector": {
"Type": "AWS::Lambda::NetworkConnector",
"Properties": {
"Name": "%s",
"OperatorRole": "arn:aws:iam::000000000000:role/cfn-microvm-connector-operator",
"Configuration": {
"VpcEgressConfiguration": {
"AssociatedComputeResourceTypes": ["WebFunction"],
"SubnetIds": ["subnet-0cfn000000000001"],
"SecurityGroupIds": ["sg-0cfn000000000001"],
"NetworkProtocol": "IPv4"
}
}
}
}
},
"Outputs": {
"LatestVersion": {"Value": {"Fn::GetAtt": ["Connector", "LatestVersion"]}}
}
}
""".formatted(connectorName);
cloudFormation(stackName, "CreateStack", template);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName, CFN_AUTH);
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
given()
.when()
.get("/2026-04-04/network-connectors/" + connectorName)
.then()
.statusCode(404);
cloudFormation(stackName, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stackName, CFN_AUTH);
}
private static String refTemplate(String connectorName, String subnetId) {
return """
{
@@ -190,7 +236,8 @@ class CloudFormationLambdaMicrovmsIntegrationTest {
"ImageRef": {"Value": {"Ref": "Image"}},
"ImageArn": {"Value": {"Fn::GetAtt": ["Image", "ImageArn"]}},
"ConnectorRef": {"Value": {"Ref": "Connector"}},
"ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}}
"ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}},
"ConnectorLatestVersionArn": {"Value": {"Fn::GetAtt": ["Connector", "LatestVersionArn"]}}
}
}
""".formatted(connectorName, subnetId);
@@ -210,6 +210,15 @@ class LambdaMicrovmsCfnProvisionerTest {
assertEquals(arn, r.getAttributes().get("Arn"));
assertEquals("nc-1", r.getAttributes().get("Id"));
assertEquals("nc", r.getAttributes().get("Name"));
assertEquals("1", r.getAttributes().get("LatestVersion"));
assertEquals(arn + ":1", r.getAttributes().get("LatestVersionArn"));
}
@Test
void latestVersionIsTheOnlyNumericConnectorAttribute() {
assertTrue(provisioner.attributeValue(CONNECTOR_TYPE, "LatestVersion", "2").isIntegralNumber());
assertTrue(provisioner.attributeValue(CONNECTOR_TYPE, "LatestVersionArn", "arn:2").isTextual());
assertTrue(provisioner.attributeValue("AWS::Lambda::MicrovmImage", "LatestVersion", "2").isTextual());
}
@Test
@@ -241,8 +250,12 @@ class LambdaMicrovmsCfnProvisionerTest {
prior.setPhysicalId(arn);
prior.getAttributes().put("Name", "nc");
when(service.getConnector(REGION, arn)).thenReturn(connector("nc-1", "nc"));
LambdaMicrovmsService.NetworkConnector attempted = connector("nc-1", "nc");
attempted.latestVersion = 2;
LambdaMicrovmsService.NetworkConnector restored = connector("nc-1", "nc");
restored.latestVersion = 3;
when(service.updateConnector(anyString(), anyString(), any(), any(), any(), any(), any()))
.thenReturn(connector("nc-1", "nc"));
.thenReturn(attempted, restored);
ObjectNode props = connectorProps("nc", "subnet-2");
props.put("OperatorRole", "arn:aws:iam::000000000000:role/operator-v2");
ObjectNode vpc = (ObjectNode) props.path("Configuration").path("VpcEgressConfiguration");
@@ -253,9 +266,12 @@ class LambdaMicrovmsCfnProvisionerTest {
verify(service).updateConnector(REGION, arn, List.of("subnet-2"), List.of("sg-1"),
"arn:aws:iam::000000000000:role/operator-v2", "DUAL_STACK", List.of("MICROVM"));
assertEquals(arn + ":2", updated.getAttributes().get("LatestVersionArn"));
assertTrue(provisioner.rollbackUpdate(updated));
verify(service).updateConnector(REGION, arn, List.of("subnet-1"), List.of("sg-1"), OPERATOR_ROLE, "IPv4",
List.of("MICROVM"));
assertEquals("3", updated.getAttributes().get("LatestVersion"));
assertEquals(arn + ":3", updated.getAttributes().get("LatestVersionArn"));
assertFalse(updated.getAttributes().containsKey(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR),
"the snapshot is spent");
}
@@ -7,8 +7,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
@@ -416,4 +418,142 @@ class LambdaMicrovmsIntegrationTest {
.statusCode(200)
.body("name", equalTo(name));
}
@Test
@Order(16)
void anUpdateThatChangesTheConnectorMakesTheNextVersion() {
String create = """
{
"Name": "microvm-it-versions",
"ClientToken": "microvm-it-token-versions",
"OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator",
"Configuration": { "VpcEgressConfiguration": {
"AssociatedComputeResourceTypes": ["WebFunction"],
"NetworkProtocol": "IPv4",
"SubnetIds": ["subnet-0000000000000ver1"],
"SecurityGroupIds": ["sg-0000000000000ver1"]
} }
}
""";
String arn = given().contentType("application/json").body(create)
.when().post(CORE + "/network-connectors")
.then().statusCode(202)
.body("Version", equalTo(1))
.body("State", equalTo("PENDING"))
.extract().path("Arn");
String id = arn.substring(arn.lastIndexOf(':') + 1);
given().when().get(CORE + "/network-connectors/microvm-it-versions")
.then().statusCode(200)
.body("Id", equalTo(id))
.body("LatestVersion", equalTo(1))
.body("LatestVersionArn", equalTo(arn + ":1"))
.body("$", not(hasKey("Version")));
String same = """
{ "Configuration": { "VpcEgressConfiguration": {
"SubnetIds": ["subnet-0000000000000ver1"], "SecurityGroupIds": ["sg-0000000000000ver1"] } } }
""";
given().contentType("application/json").body(same)
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(1))
.body("LastUpdateStatus", equalTo("Successful"))
.body("LastUpdateStatusReason", equalTo("No configuration changes detected"));
String moreSubnets = """
{ "Configuration": { "VpcEgressConfiguration": {
"SubnetIds": ["subnet-0000000000000ver1", "subnet-0000000000000ver2"] } } }
""";
given().contentType("application/json").body(moreSubnets)
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(2))
.body("VersionArn", equalTo(arn + ":2"))
.body("LastUpdateStatus", equalTo("InProgress"))
.body("LastUpdateStatusReason", equalTo("Update in progress"));
String reordered = """
{ "Configuration": { "VpcEgressConfiguration": {
"SubnetIds": ["subnet-0000000000000ver2", "subnet-0000000000000ver1"] } } }
""";
given().contentType("application/json").body(reordered)
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(2))
.body("LastUpdateStatusReason", equalTo("No configuration changes detected"))
.body("Configuration.VpcEgressConfiguration.SubnetIds",
contains("subnet-0000000000000ver1", "subnet-0000000000000ver2"));
given().contentType("application/json")
.body("""
{ "OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator-v2" }
""")
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("Version", equalTo(3));
given().when().get(CORE + "/network-connectors/" + arn)
.then().statusCode(200)
.body("LatestVersion", equalTo(3))
.body("StateReason", equalTo("Update initiated"))
.body("LastUpdateStatus", equalTo("Successful"))
.body("LastUpdateStatusReason", equalTo("Update was successful"));
given().when().get(CORE + "/network-connectors/" + id + ":1")
.then().statusCode(200)
.body("Version", equalTo(1))
.body("VersionArn", equalTo(arn + ":1"))
.body("StateReason", equalTo("Initial creation"))
.body("OperatorRole", equalTo("arn:aws:iam::000000000000:role/microvm-connector-operator"))
.body("Configuration.VpcEgressConfiguration.SubnetIds", contains("subnet-0000000000000ver1"))
.body("$", not(hasKey("LatestVersion")))
.body("$", not(hasKey("LastUpdateStatus")));
given().when().get(CORE + "/network-connectors/" + arn + ":2")
.then().statusCode(200)
.body("Version", equalTo(2))
.body("Configuration.VpcEgressConfiguration.SubnetIds",
contains("subnet-0000000000000ver1", "subnet-0000000000000ver2"));
given().when().get(CORE + "/network-connectors/" + arn + ":4")
.then().statusCode(404)
.body("message", equalTo("Network connector not found: " + arn + ":4"));
given().when().get(CORE + "/network-connectors/" + id + "/versions")
.then().statusCode(200)
.body("NetworkConnectorVersions.Version", contains(1, 2, 3))
.body("NetworkConnectorVersions[1].VersionArn", equalTo(arn + ":2"))
.body("NetworkConnectorVersions[1].StateReason", equalTo("Update initiated"));
given().when().get(CORE + "/network-connectors/" + id + ":9/versions")
.then().statusCode(400)
.body("message", equalTo("Identifier must not include a version qualifier"));
given().when().get(CORE + "/network-connectors")
.then().statusCode(200)
.body("NetworkConnectors.find { it.Id == '%s' }.LatestVersion".formatted(id), equalTo(3));
given().contentType("application/json")
.body("""
{ "Configuration": { "VpcEgressConfiguration": { "AssociatedComputeResourceTypes": ["MicroVm"] } } }
""")
.when().put(CORE + "/network-connectors/" + id)
.then().statusCode(400)
.body("message", equalTo("AssociatedComputeResourceTypes cannot be changed on an existing network"
+ " connector. Current: [WebFunction], requested: [MicroVm]."));
given().when().delete(CORE + "/network-connectors/" + id + ":3")
.then().statusCode(400)
.body("message", equalTo("Cannot delete the latest version of a network connector."));
given().when().delete(CORE + "/network-connectors/" + id + ":1")
.then().statusCode(202)
.body("Version", equalTo(1))
.body("State", equalTo("DELETING"))
.body("Configuration.VpcEgressConfiguration.SubnetIds", contains("subnet-0000000000000ver1"));
given().when().get(CORE + "/network-connectors/" + id + ":1")
.then().statusCode(404)
.body("message", equalTo("Network connector not found: " + arn + ":1"));
given().when().get(CORE + "/network-connectors/" + id + "/versions")
.then().statusCode(200)
.body("NetworkConnectorVersions.Version", contains(2, 3));
given().when().delete(CORE + "/network-connectors/" + id)
.then().statusCode(202)
.body("State", equalTo("DELETING"))
.body("$", not(hasKey("Version")));
given().when().get(CORE + "/network-connectors/" + id)
.then().statusCode(404)
.body("message", equalTo("Network connector not found: " + arn));
}
}
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.lambdamicrovms;
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.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
@@ -9,6 +12,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
@@ -154,6 +158,38 @@ class LambdaMicrovmsServicePersistenceTest {
* reached the backend. Only a JSON round trip separates state that was written from state that
* was merely mutated.
*/
@Test
void connectorVersionsSurviveARestart() {
LambdaMicrovmsService first = process();
String connectorId = createConnector(first);
first.updateConnector(REGION, connectorId, List.of("subnet-2"), null, null, null, null);
LambdaMicrovmsService reloaded = process();
assertEquals(2, reloaded.getConnector(REGION, connectorId).latestVersion);
assertEquals(List.of("subnet-1"),
reloaded.getConnectorVersion(REGION, connectorId + ":1").version().subnetIds);
}
@Test
void aConnectorStoredBeforeVersionsIsItsFirstVersion() throws IOException {
String connectorId = createConnector(process());
Path file = storageDir.resolve("lambda-network-connectors.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode stored = mapper.readTree(file.toFile());
stored.findParents("versions").forEach(node -> ((ObjectNode) node).remove(List.of("versions", "latestVersion")));
mapper.writeValue(file.toFile(), stored);
LambdaMicrovmsService.NetworkConnectorVersion first =
process().getConnectorVersion(REGION, connectorId + ":1").version();
assertEquals(List.of("subnet-1"), first.subnetIds);
}
private static String createConnector(LambdaMicrovmsService service) {
return service.createConnector(REGION, ACCOUNT_ID, "probe-connector",
List.of("subnet-1"), List.of("sg-1"), "arn:aws:iam::000000000000:role/operator",
"token-1", List.of("WebFunction"), "IPv4").id;
}
private static final class FileStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
private final Path directory;
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.lambdamicrovms;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LambdaMicrovmsServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
@Test
void concurrentConnectorUpdatesEachMakeTheirOwnVersion() throws Exception {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
LambdaMicrovmsService service = new LambdaMicrovmsService(regionResolver, mock(StorageFactory.class));
LambdaMicrovmsService.NetworkConnector created = service.createConnector(REGION, ACCOUNT_ID, "concurrent",
List.of("subnet-00000000000000001"), List.of("sg-00000000000000000"),
"arn:aws:iam::000000000000:role/operator", "token", List.of("WebFunction"), "IPv4");
int updates = 16;
ExecutorService executor = Executors.newFixedThreadPool(updates);
CountDownLatch start = new CountDownLatch(1);
List<Future<LambdaMicrovmsService.NetworkConnector>> results = new ArrayList<>();
for (int i = 1; i <= updates; i++) {
List<String> groups = List.of(String.format("sg-%017d", i));
results.add(executor.submit(() -> {
start.await();
return service.updateConnector(REGION, created.id, null, groups, null, null, null);
}));
}
start.countDown();
Set<Long> versions = new HashSet<>();
for (Future<LambdaMicrovmsService.NetworkConnector> result : results) {
LambdaMicrovmsService.NetworkConnector updated = result.get(10, TimeUnit.SECONDS);
versions.add(updated.latestVersion);
LambdaMicrovmsService.ConnectorVersion named =
service.getConnectorVersion(REGION, created.id + ":" + updated.latestVersion);
assertEquals(updated.securityGroupIds, named.version().securityGroupIds);
}
executor.shutdown();
assertEquals(updates, versions.size());
assertEquals(updates + 1, service.getConnector(REGION, created.id).latestVersion);
assertEquals(updates + 1, service.listConnectorVersions(REGION, created.id).size());
}
}