feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079)

* feat(lambdamicrovms): AWS Lambda MicroVMs service module

Adds the Lambda MicroVMs control plane, a service AWS took GA on 2026-06-22:
MicroVM images with a version and build lifecycle, the managed base-image
catalog, MicroVM CRUD, and VPC egress network connectors.

Two service models rather than one. Lambda Microvms (apiVersion 2025-09-09)
carries images and MicroVMs under /2025-09-09; Lambda Core (2026-04-30)
carries network connectors under /2026-04-04. Both sign as lambda, so their
requests arrive under the existing lambda claim in ResolvedServiceCatalog and
route by path. Neither prefix collides with anything LambdaController serves,
and both are enabled by the lambda service rather than adding a toggle.
Tagging rides the classic /2017-03-31/tags/ routes, so LambdaTagController
learns the MicroVM ARN forms.

Resources are stored per account and region. Floci resolves a per-request
account in AccountContextFilter and these ARNs carry it, so region-only
storage would let two accounts sharing a region read and mutate each other's
images, MicroVMs and connectors.

Wire shapes come from the vendored service models and, where the models are
silent or disagree with the service, from responses recorded against live
AWS. Several members the models mark optional are enforced in practice — a
connector needs ClientToken, OperatorRole, NetworkProtocol and
AssociatedComputeResourceTypes despite all four being optional in Smithy — and
several resources are returned in a different projection per operation: an
image in four shapes, a connector in four, with only the list summaries
carrying Type.

Builds converge instantly rather than on a timer, the usual emulator trade.
Where that would otherwise produce an inconsistent body it is handled
explicitly: a create or update reports the transitional state and does not
name the version it is minting as active, because a client reading otherwise
would launch a MicroVM off a version that does not exist yet.

Auth tokens, the per-VM endpoint, and the idle and suspend timers are
deliberately out of scope here; they belong to a full-fidelity MicroVMs
emulator rather than to CloudFormation provisioning.

Verified against a suite of responses recorded from live AWS
(https://github.com/INTENTIUS/m80): 26 checks over the image, MicroVM and
connector lifecycles, 0 failures.

* feat(cloudformation): provision AWS::Lambda::MicrovmImage and AWS::Lambda::NetworkConnector

Registers a CfnResourceProvisioner for the two MicroVM CloudFormation types
against the LambdaMicrovmsService added alongside, so a template declaring
either provisions and deletes rather than being skipped.

Uses the CloudFormationResourceRegistry interface rather than the switch in
CloudFormationResourceProvisioner, following SqsCfnProvisioner.

* test(lambdamicrovms): AWS CLI compatibility coverage for images, MicroVMs and connectors

* fix(lambdamicrovms): wire service state through StorageFactory

Images, MicroVMs and connectors were held in plain in-memory maps, so in
persistent mode a restarted Floci lost them while the CloudFormation stacks that
created them survived. Those stacks then referenced resources that no longer
existed and DeleteStack failed on the 404.

The three stores are now StorageBackedMap over StorageFactory backends, keyed
region/id. MicroVMs are delivered as part of the lambda service, so they share
its storage key and therefore its configured mode and flush interval rather than
declaring their own. The account half of the key is dropped from the service and
left to the backend, which prefixes and strips the same account the
RegionResolver returns, so region and account isolation are unchanged.

StorageBackedMap only marks the backend dirty on put and remove, so every path
that mutated a stored object in place now writes it back: image update, version
status, version delete, rebuild, MicroVM settle and terminate, connector settle
and update, and both tag paths.

* style(core): import the lambda microvms controllers in the service catalog

* fix(lambdamicrovms): register the persisted types for reflection

Moving images, microvms and connectors into StorageBackedMap made their model
classes persisted types, and PersistedModelReflectionTest fails on any that lack
@RegisterForReflection because native-image persistence cannot rebuild them on
restart.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-10 23:10:48 -05:00
1 parent 0cfffbea00
commit 40e8aad55a
13 files changed
+2528 -4

No files matched your search

@@ -0,0 +1,121 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* End-to-end check that CloudFormation provisions {@code AWS::Lambda::MicrovmImage} and
* {@code AWS::Lambda::NetworkConnector} into the real MicroVMs service. The template mirrors
* the shape chant's MicrovmApp composite emits: the image's EgressNetworkConnectors reference
* the connector's Arn via Fn::GetAtt, and the connector's configuration nests under
* Configuration.VpcEgressConfiguration.
*/
@QuarkusTest
class CloudFormationLambdaMicrovmsIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
@Test
void createStackProvisionsImageAndConnector() {
String suffix = Long.toString(System.nanoTime(), 36);
String imageName = "cfn-microvm-image-" + suffix;
String connectorName = "cfn-microvm-connector-" + suffix;
String stackName = "cfn-microvm-stack-" + 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": ["MicroVm"],
"SubnetIds": ["subnet-0cfn000000000001"],
"SecurityGroupIds": ["sg-0cfn000000000001"],
"NetworkProtocol": "IPv4"
}
}
}
},
"Image": {
"Type": "AWS::Lambda::MicrovmImage",
"Properties": {
"Name": "%s",
"BaseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
"BuildRoleArn": "arn:aws:iam::000000000000:role/cfn-microvm-build",
"CodeArtifact": { "Uri": "s3://cfn-bucket/context.zip" },
"Description": "cfn e2e image",
"EgressNetworkConnectors": [{"Fn::GetAtt": ["Connector", "Arn"]}],
"CpuConfigurations": [{"Architecture": "ARM_64"}],
"Resources": [{"MinimumMemoryInMiB": 2048}]
}
}
},
"Outputs": {
"ImageArn": {"Value": {"Fn::GetAtt": ["Image", "ImageArn"]}},
"ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}}
}
}
""".formatted(connectorName, imageName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
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>CREATE_COMPLETE</StackStatus>"))
.body(containsString(":microvm-image:" + imageName))
.body(containsString(":network-connector:nc-"));
// Both resources really exist in the MicroVMs service.
given()
.when()
.get("/2025-09-09/microvm-images/" + imageName)
.then()
.statusCode(200)
.body("state", equalTo("CREATED"))
.body("latestActiveImageVersion", equalTo("1.0"));
// Delete the stack and both resources go away.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
await().untilAsserted(() ->
given()
.when()
.get("/2025-09-09/microvm-images/" + imageName)
.then()
.statusCode(404));
}
}
@@ -0,0 +1,397 @@
package io.github.hectorvent.floci.services.lambdamicrovms;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class LambdaMicrovmsIntegrationTest {
private static final String MICROVMS = "/2025-09-09";
private static final String CORE = "/2026-04-04";
private static final String TAGS = "/2017-03-31";
private static final String IMAGE = "microvm-it-image";
private static String microvmId;
private static String connectorId;
private static String imageArn;
@Test
@Order(1)
void createImage() {
imageArn = given()
.contentType("application/json")
.body("""
{
"name": "%s",
"baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
"buildRoleArn": "arn:aws:iam::000000000000:role/microvm-build",
"codeArtifact": { "uri": "s3://bucket/code.zip" }
}
""".formatted(IMAGE))
.when()
.post(MICROVMS + "/microvm-images")
.then()
.statusCode(201)
.body("name", equalTo(IMAGE))
.body("state", equalTo("CREATING"))
.body("imageVersion", equalTo("1.0"))
.extract().path("imageArn");
}
@Test
@Order(2)
void imageSettlesToCreated() {
given()
.when()
.get(MICROVMS + "/microvm-images/" + IMAGE)
.then()
.statusCode(200)
.body("state", equalTo("CREATED"))
.body("latestActiveImageVersion", equalTo("1.0"));
}
@Test
@Order(3)
void versionAndBuildConverge() {
String buildId = given()
.when()
.get(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0/builds")
.then()
.statusCode(200)
.body("items[0].buildState", equalTo("SUCCESSFUL"))
.extract().path("items[0].buildId");
given()
.when()
.get(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0/builds/" + buildId)
.then()
.statusCode(200)
.body("buildState", equalTo("SUCCESSFUL"))
.body("architecture", equalTo("ARM_64"));
given()
.when()
.get(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0")
.then()
.statusCode(200)
.body("state", equalTo("SUCCESSFUL"))
.body("status", equalTo("ACTIVE"));
}
@Test
@Order(4)
void badImageNameIsRejected() {
given()
.contentType("application/json")
.body("""
{
"name": "bad name!",
"baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
"buildRoleArn": "arn:aws:iam::000000000000:role/microvm-build",
"codeArtifact": { "uri": "s3://bucket/code.zip" }
}
""")
.when()
.post(MICROVMS + "/microvm-images")
.then()
.statusCode(400);
}
@Test
@Order(5)
void managedCatalogListsBaseImage() {
given()
.when()
.get(MICROVMS + "/managed-microvm-images")
.then()
.statusCode(200)
.body("items[0].imageArn", notNullValue());
}
@Test
@Order(6)
void runMicrovm() {
microvmId = given()
.contentType("application/json")
.body("{\"imageIdentifier\": \"" + IMAGE + "\"}")
.when()
.post(MICROVMS + "/microvms")
.then()
.statusCode(200)
.body("state", equalTo("PENDING"))
.body("microvmId", startsWith("microvm-"))
.body("maximumDurationInSeconds", equalTo(28800))
.extract().path("microvmId");
given()
.when()
.get(MICROVMS + "/microvms/" + microvmId)
.then()
.statusCode(200)
.body("state", equalTo("RUNNING"));
}
@Test
@Order(7)
void runWithMissingImageIsNotFound() {
given()
.contentType("application/json")
.body("{\"imageIdentifier\": \"no-such-image\"}")
.when()
.post(MICROVMS + "/microvms")
.then()
.statusCode(404);
}
@Test
@Order(8)
void imageInUseRefusesDelete() {
// Recorded live: 400 with "Cannot delete microvm image with running microvms."
given()
.when()
.delete(MICROVMS + "/microvm-images/" + IMAGE)
.then()
.statusCode(400);
}
@Test
@Order(9)
void tagImageArn() {
given()
.contentType("application/json")
.body("{\"Tags\": {\"team\": \"conformance\"}}")
.when()
.post(TAGS + "/tags/" + imageArn)
.then()
.statusCode(204);
given()
.when()
.get(TAGS + "/tags/" + imageArn)
.then()
.statusCode(200)
.body("Tags.team", equalTo("conformance"));
given()
.queryParam("tagKeys", "team")
.when()
.delete(TAGS + "/tags/" + imageArn)
.then()
.statusCode(204);
}
@Test
@Order(10)
void terminateMicrovm() {
given()
.when()
.delete(MICROVMS + "/microvms/" + microvmId)
.then()
.statusCode(200);
given()
.when()
.get(MICROVMS + "/microvms/" + microvmId)
.then()
.statusCode(200)
.body("state", equalTo("TERMINATED"));
// Recorded live: terminal-state mutations are 400 ValidationException.
given()
.when()
.delete(MICROVMS + "/microvms/" + microvmId)
.then()
.statusCode(400);
}
@Test
@Order(11)
void connectorLifecycle() {
connectorId = given()
.contentType("application/json")
.body("""
{
"Name": "microvm-it-connector",
"ClientToken": "microvm-it-token-1",
"OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator",
"Configuration": { "VpcEgressConfiguration": {
"AssociatedComputeResourceTypes": ["MicroVm"],
"NetworkProtocol": "IPv4",
"SubnetIds": ["subnet-0000000000000it01"],
"SecurityGroupIds": ["sg-0000000000000it01"]
} }
}
""")
.when()
.post(CORE + "/network-connectors")
.then()
.statusCode(202)
.body("State", equalTo("PENDING"))
.extract().path("Id");
given()
.when()
.get(CORE + "/network-connectors/" + connectorId)
.then()
.statusCode(200)
.body("State", equalTo("ACTIVE"))
.body("Name", equalTo("microvm-it-connector"));
given()
.when()
.delete(CORE + "/network-connectors/" + connectorId)
.then()
.statusCode(202);
given()
.when()
.get(CORE + "/network-connectors/" + connectorId)
.then()
.statusCode(404);
}
@Test
@Order(12)
void connectorSubnetLimit() {
StringBuilder subnets = new StringBuilder();
for (int i = 1; i <= 17; i++) {
if (i > 1) subnets.append(",");
subnets.append("\"subnet-00000000000000").append(String.format("%03d", i)).append("\"");
}
given()
.contentType("application/json")
.body("""
{
"Name": "microvm-it-too-many",
"ClientToken": "microvm-it-token-2",
"OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator",
"Configuration": { "VpcEgressConfiguration": {
"AssociatedComputeResourceTypes": ["MicroVm"],
"NetworkProtocol": "IPv4",
"SubnetIds": [%s]
} }
}
""".formatted(subnets))
.when()
.post(CORE + "/network-connectors")
.then()
.statusCode(400);
}
@Test
@Order(13)
void cleanupImage() {
given()
.when()
.delete(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0")
.then()
.statusCode(200);
given()
.when()
.delete(MICROVMS + "/microvm-images/" + IMAGE)
.then()
.statusCode(200)
.body("state", equalTo("DELETING"))
.body("imageIdentifier", equalTo(imageArn));
given()
.when()
.get(MICROVMS + "/microvm-images/" + IMAGE)
.then()
.statusCode(404);
}
@Test
@Order(14)
void connectorRequiredMembersAreEnforced() {
// Recorded live: all three are required despite being modeled optional.
String base = """
{
"Name": "microvm-it-missing-%s"%s,
"Configuration": { "VpcEgressConfiguration": {
%s
"SubnetIds": ["subnet-0000000000000it09"]
} }
}
""";
given().contentType("application/json")
.body(base.formatted("token", ", \"OperatorRole\": \"arn:aws:iam::000000000000:role/op\"", "\"AssociatedComputeResourceTypes\": [\"MicroVm\"], \"NetworkProtocol\": \"IPv4\","))
.when().post(CORE + "/network-connectors")
.then().statusCode(400);
given().contentType("application/json")
.body(base.formatted("acrt", ", \"ClientToken\": \"t1\", \"OperatorRole\": \"arn:aws:iam::000000000000:role/op\"", "\"NetworkProtocol\": \"IPv4\","))
.when().post(CORE + "/network-connectors")
.then().statusCode(400);
given().contentType("application/json")
.body(base.formatted("proto", ", \"ClientToken\": \"t2\", \"OperatorRole\": \"arn:aws:iam::000000000000:role/op\"", "\"AssociatedComputeResourceTypes\": [\"MicroVm\"],"))
.when().post(CORE + "/network-connectors")
.then().statusCode(400);
}
private static String credentialFor(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId
+ "/20260801/us-east-1/lambda/aws4_request, SignedHeaders=host, Signature=x";
}
@Test
@Order(15)
void resourcesAreScopedToTheCallersAccount() {
String accountA = "111122223333";
String accountB = "444455556666";
String name = "microvm-it-tenant-image";
given()
.header("Authorization", credentialFor(accountA))
.contentType("application/json")
.body("""
{
"name": "%s",
"baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
"buildRoleArn": "arn:aws:iam::111122223333:role/microvm-build",
"codeArtifact": { "uri": "s3://bucket/code.zip" }
}
""".formatted(name))
.when()
.post(MICROVMS + "/microvm-images")
.then()
.statusCode(201)
.body("imageArn", startsWith("arn:aws:lambda:us-east-1:" + accountA + ":"));
// The ARN names account A, so account B must not reach the image by
// identifier or see it in a list.
given()
.header("Authorization", credentialFor(accountB))
.when()
.get(MICROVMS + "/microvm-images/" + name)
.then()
.statusCode(404);
given()
.header("Authorization", credentialFor(accountB))
.when()
.get(MICROVMS + "/microvm-images")
.then()
.statusCode(200)
.body("items.name", not(hasItem(name)));
given()
.header("Authorization", credentialFor(accountA))
.when()
.get(MICROVMS + "/microvm-images/" + name)
.then()
.statusCode(200)
.body("name", equalTo(name));
}
}
@@ -0,0 +1,181 @@
package io.github.hectorvent.floci.services.lambdamicrovms;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* MicroVM state survives a restart. Each {@link #process()} call is a separate Floci process over
* the same storage directory, so a later one reads what an earlier one wrote back rather than
* sharing its objects.
*
* <p>CloudFormation stacks persist across restarts, so state held only in memory left a restarted
* Floci with stacks pointing at images and connectors that no longer existed, and DeleteStack then
* failed on the 404.
*/
class LambdaMicrovmsServicePersistenceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
@TempDir
Path storageDir;
/** A fresh process reading the storage directory from disk. */
private LambdaMicrovmsService process() {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
LambdaMicrovmsService service =
new LambdaMicrovmsService(regionResolver, new FileStorageFactory(storageDir));
service.initializeStorage();
return service;
}
private LambdaMicrovmsService.MicrovmImage createImage(LambdaMicrovmsService service, String name) {
return service.createImage(REGION, ACCOUNT_ID, name,
"arn:aws:lambda:us-east-1::microvm-image/al2023-1", "arn:aws:iam::000000000000:role/build",
"s3://bucket/artifact.zip", "an image");
}
@Test
void imagesAndTheirVersionsSurviveARestart() {
createImage(process(), "probe-image");
LambdaMicrovmsService reloaded = process();
LambdaMicrovmsService.MicrovmImage image = reloaded.getImage(REGION, "probe-image");
assertEquals("CREATED", image.state);
assertEquals("1.0", image.latestActiveImageVersion);
assertEquals(1, image.versions.size());
assertEquals(2, image.versions.get(0).builds.size(), "both Graviton builds must round-trip");
assertNotNull(image.createdAt, "Instant fields must round-trip");
assertEquals(1, reloaded.listImages(REGION).size());
}
@Test
void anInPlaceUpdateReachesTheBackend() {
// updateImage mutates the stored image rather than replacing it, so without an explicit
// write-back the change never reaches the backend and is lost on restart.
LambdaMicrovmsService first = process();
createImage(first, "probe-image");
first.updateImage(REGION, "probe-image", "arn:aws:lambda:us-east-1::microvm-image/al2023-1",
"arn:aws:iam::000000000000:role/other", "s3://bucket/next.zip", "updated");
LambdaMicrovmsService.MicrovmImage image = process().getImage(REGION, "probe-image");
assertEquals("UPDATED", image.state);
assertEquals("updated", image.description);
assertEquals("s3://bucket/next.zip", image.codeArtifactUri);
assertEquals("2.0", image.latestActiveImageVersion);
}
@Test
void tagMutationsReachTheBackend() {
LambdaMicrovmsService first = process();
String arn = createImage(first, "probe-image").imageArn;
first.tagResource(REGION, arn, Map.of("owner", "platform", "tier", "gold"));
first.untagResource(REGION, arn, List.of("tier"));
assertEquals(Map.of("owner", "platform"), process().getImage(REGION, "probe-image").tags);
}
@Test
void versionStatusChangesReachTheBackend() {
LambdaMicrovmsService first = process();
createImage(first, "probe-image");
first.updateVersionStatus(REGION, "probe-image", "1.0", "INACTIVE");
assertEquals("INACTIVE", process().getVersion(REGION, "probe-image", "1.0").status);
}
@Test
void microvmsAndConnectorsSurviveARestart() {
LambdaMicrovmsService first = process();
String imageArn = createImage(first, "probe-image").imageArn;
String vmId = first.runMicrovm(REGION, ACCOUNT_ID, imageArn).microvmId;
String connectorId = first.createConnector(REGION, ACCOUNT_ID, "probe-connector",
List.of("subnet-1"), List.of("sg-1"), "arn:aws:iam::000000000000:role/operator",
"token-1", List.of("LAMBDA"), "VPC_EGRESS").id;
LambdaMicrovmsService reloaded = process();
assertEquals("RUNNING", reloaded.getMicrovm(REGION, vmId).state,
"the instant settle must be written back, not applied to a detached copy");
assertEquals("ACTIVE", reloaded.getConnector(REGION, connectorId).state);
assertEquals(List.of("subnet-1"), reloaded.getConnector(REGION, connectorId).subnetIds);
reloaded.terminateMicrovm(REGION, vmId);
assertEquals("TERMINATED", process().getMicrovm(REGION, vmId).state);
}
@Test
void deletesSurviveARestart() {
LambdaMicrovmsService first = process();
createImage(first, "probe-image");
first.deleteImage(REGION, "probe-image");
LambdaMicrovmsService reloaded = process();
assertThrows(RuntimeException.class, () -> reloaded.getImage(REGION, "probe-image"));
assertTrue(reloaded.listImages(REGION).isEmpty());
}
@Test
void oneRegionDoesNotSeeAnother() {
LambdaMicrovmsService service = process();
createImage(service, "probe-image");
service.createImage("eu-west-1", ACCOUNT_ID, "other-image",
"arn:aws:lambda:eu-west-1::microvm-image/al2023-1",
"arn:aws:iam::000000000000:role/build", "s3://bucket/artifact.zip", null);
LambdaMicrovmsService reloaded = process();
assertEquals(List.of("probe-image"),
reloaded.listImages(REGION).stream().map(i -> i.name).toList());
assertEquals(List.of("other-image"),
reloaded.listImages("eu-west-1").stream().map(i -> i.name).toList());
}
/**
* Backed by real files rather than {@code InMemoryStorage}, because an in-memory store hands
* back the same object reference, so a restart would observe an in-place mutation that never
* reached the backend. Only a JSON round trip separates state that was written from state that
* was merely mutated.
*/
private static final class FileStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
private final Path directory;
private FileStorageFactory(Path directory) {
super(null, null);
this.directory = directory;
}
@Override
@SuppressWarnings("unchecked")
public <V> StorageBackend<String, V> create(String serviceName,
String fileName,
TypeReference<Map<String, V>> typeReference) {
// Wrap like the production factory does so the tests exercise the
// account-prefixed key space, not a bare backend.
return (StorageBackend<String, V>) stores.computeIfAbsent(fileName, ignored -> {
PersistentStorage<String, V> inner =
new PersistentStorage<>(directory.resolve(fileName), typeReference);
inner.load();
return new AccountAwareStorageBackend<V>(inner, null, ACCOUNT_ID);
});
}
}
}