Skip to content

An open-source, faster Devin alternative

TypeScript

microvm templates: make the snapshot endpoints answer the SDK's real contract, and test Claim for real — GET /snapshots/:name only read image_cache, so a microvm template 404'd forever and the SDK's waitUntilReady treats 404 as 'still building', hanging a customer on a healthy template until their timeout (or forever without one); create/get now return the SnapshotInfo shape the SDK types, with an empty checkpointId because inventing one would resolve to nothing; replaces two struct-fixture tests with a recording fake that asserts Claim actually calls RunMicrovm with the template ARN and reports warm=false

Brian Reardona04255eac46e
diff --git a/internal/api/snapshots.go b/internal/api/snapshots.go
index 181ce9c2..a1109d78 100644
--- a/internal/api/snapshots.go
+++ b/internal/api/snapshots.go
@@ -107,10 +107,10 @@ func (s *Server) createSnapshot(c echo.Context) error {
log.Printf("snapshot: microvm template %q failed: %v", name, err)
}
}()
- return c.JSON(http.StatusAccepted, map[string]string{
- "name": name,
- "status": "processing",
- })
+ return c.JSON(http.StatusAccepted, snapshotViewOfTemplate(&db.DBTemplate{
+ OrgID: &orgID, Name: name, Status: db.TemplateStatusProcessing,
+ CreatedAt: time.Now(),
+ }))
}
// SSE streaming path
@@ -337,6 +337,20 @@ func (s *Server) getSnapshot(c echo.Context) error {
}
name := c.Param("name")
+
+ // On the MicroVM runtime a snapshot IS a template row, not an image_cache
+ // entry. Without this the lookup 404s forever — and the SDK's
+ // waitUntilReady treats 404 as "still building", so a customer waiting on a
+ // perfectly healthy template would poll until their timeout, or forever if
+ // they passed none.
+ if s.runtimeFor(c) == runtimeMicrovm {
+ tmpl, err := s.store.GetTemplateByName(c.Request().Context(), orgID, name)
+ if err != nil || tmpl == nil || tmpl.TemplateType != db.TemplateTypeMicrovmImage {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "snapshot not found"})
+ }
+ return c.JSON(http.StatusOK, snapshotViewOfTemplate(tmpl))
+ }
+
snapshot, err := s.store.GetImageCacheByName(c.Request().Context(), orgID, name)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"error": "snapshot not found"})
@@ -574,3 +588,32 @@ func (s *Server) deleteImagePatch(c echo.Context) error {
c.SetParamValues(checkpointID.String(), patchId)
return s.deleteCheckpointPatch(c)
}
+
+// snapshotViewOfTemplate renders a MicroVM image template in the shape the SDK
+// types as SnapshotInfo.
+//
+// The SDK's waitUntilReady reads exactly one field — status — and compares it
+// against "ready" and "failed", which the template statuses already match. The
+// rest are populated because create() and get() are typed as returning a
+// SnapshotInfo, and a caller reading .id off a half-filled object gets
+// undefined rather than an error.
+//
+// checkpointId is deliberately empty: there is no checkpoint on this runtime,
+// and inventing one would hand callers an ID that resolves to nothing.
+func snapshotViewOfTemplate(t *db.DBTemplate) map[string]any {
+ org := ""
+ if t.OrgID != nil {
+ org = t.OrgID.String()
+ }
+ return map[string]any{
+ "id": t.ID.String(),
+ "orgId": org,
+ "name": t.Name,
+ "contentHash": t.Tag,
+ "checkpointId": "",
+ "status": t.Status,
+ "manifest": map[string]any{},
+ "createdAt": t.CreatedAt.UTC().Format(time.RFC3339),
+ "lastUsedAt": t.CreatedAt.UTC().Format(time.RFC3339),
+ }
+}
diff --git a/internal/awsvmlite/template_image_claim_test.go b/internal/awsvmlite/template_image_claim_test.go
new file mode 100644
index 00000000..35e4a437
--- /dev/null
+++ b/internal/awsvmlite/template_image_claim_test.go
@@ -0,0 +1,126 @@
+package awsvmlite
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+)
+
+// recordingAPI captures which image each RunMicrovm asked for. That is the
+// whole question this file answers: a template create must launch the
+// TEMPLATE's image, and must not be served a pooled box built from the default
+// image — a substitution the customer cannot detect until their packages turn
+// out to be missing.
+type recordingAPI struct {
+ mu sync.Mutex
+ images []string
+}
+
+func (f *recordingAPI) RunMicrovm(_ context.Context, in *lambdamicrovms.RunMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {
+ f.mu.Lock()
+ f.images = append(f.images, aws.ToString(in.ImageIdentifier))
+ f.mu.Unlock()
+ return &lambdamicrovms.RunMicrovmOutput{
+ MicrovmId: aws.String("microvm-test"),
+ Endpoint: aws.String("test.lambda-microvm.us-east-1.on.aws"),
+ State: types.MicrovmStateRunning,
+ }, nil
+}
+
+func (f *recordingAPI) GetMicrovm(_ context.Context, _ *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {
+ return &lambdamicrovms.GetMicrovmOutput{
+ MicrovmId: aws.String("microvm-test"),
+ Endpoint: aws.String("test.lambda-microvm.us-east-1.on.aws"),
+ State: types.MicrovmStateRunning,
+ }, nil
+}
+
+func (f *recordingAPI) CreateMicrovmAuthToken(_ context.Context, _ *lambdamicrovms.CreateMicrovmAuthTokenInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error) {
+ return &lambdamicrovms.CreateMicrovmAuthTokenOutput{AuthToken: map[string]string{"X-aws-proxy-auth": "tok"}}, nil
+}
+
+func (f *recordingAPI) SuspendMicrovm(context.Context, *lambdamicrovms.SuspendMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.SuspendMicrovmOutput, error) {
+ return &lambdamicrovms.SuspendMicrovmOutput{}, nil
+}
+func (f *recordingAPI) ResumeMicrovm(context.Context, *lambdamicrovms.ResumeMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ResumeMicrovmOutput, error) {
+ return &lambdamicrovms.ResumeMicrovmOutput{}, nil
+}
+func (f *recordingAPI) TerminateMicrovm(context.Context, *lambdamicrovms.TerminateMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {
+ return &lambdamicrovms.TerminateMicrovmOutput{}, nil
+}
+func (f *recordingAPI) ListMicrovms(context.Context, *lambdamicrovms.ListMicrovmsInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ListMicrovmsOutput, error) {
+ return &lambdamicrovms.ListMicrovmsOutput{}, nil
+}
+
+func (f *recordingAPI) launched() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.images...)
+}
+
+const (
+ defaultImg = "arn:aws:lambda:us-east-1:1:microvm-image:pool-default"
+ templateImg = "arn:aws:lambda:us-east-1:1:microvm-image:osb-tpl-abc123"
+)
+
+func newRecordingManager(t *testing.T) (*Manager, *recordingAPI) {
+ t.Helper()
+ api := &recordingAPI{}
+ client := awsvm.NewClientWithAPI(api, awsvm.Config{
+ ImageIdentifier: defaultImg,
+ DefaultMemoryMB: 4096,
+ })
+ return New(client, Config{}), api
+}
+
+// THE test for CT-4: a template-image claim must call RunMicrovm with the
+// TEMPLATE's ARN, and must report warm=false so no pooled box is handed over.
+func TestClaimLaunchesTheTemplateImageNotTheDefault(t *testing.T) {
+ m, api := newRecordingManager(t)
+
+ box, warm, err := m.Claim(context.Background(), "sb-tpl", Meta{
+ MemoryMB: 4096,
+ TemplateImageARN: templateImg,
+ })
+ if err != nil {
+ t.Fatalf("claim: %v", err)
+ }
+ if warm {
+ t.Error("a template claim reported warm=true — it was served from the pool, which holds DEFAULT-image boxes")
+ }
+ got := api.launched()
+ if len(got) != 1 {
+ t.Fatalf("expected exactly one launch, got %v", got)
+ }
+ if got[0] != templateImg {
+ t.Errorf("launched %q, want the template image %q", got[0], templateImg)
+ }
+ if box == nil || box.Meta.TemplateImageARN != templateImg {
+ t.Error("the bound box does not carry the template ARN, so Activate's cross-check cannot verify it")
+ }
+ // Metered at the default tier rather than 0 — a zero would bill the
+ // sandbox as free.
+ if box.Meta.MemoryMB != 4096 {
+ t.Errorf("template box metered at %d MB, want the default tier", box.Meta.MemoryMB)
+ }
+}
+
+// The inverse, and the reason the field must be empty for ordinary creates: a
+// plain request must NOT take the template path, or every create cold-launches.
+func TestPlainClaimDoesNotTakeTheTemplatePath(t *testing.T) {
+ m, api := newRecordingManager(t)
+ if _, _, err := m.Claim(context.Background(), "sb-plain", Meta{MemoryMB: 4096}); err != nil {
+ t.Fatalf("claim: %v", err)
+ }
+ for _, img := range api.launched() {
+ if strings.Contains(img, "osb-tpl-") {
+ t.Errorf("a plain create launched a template image: %s", img)
+ }
+ }
+}
diff --git a/internal/awsvmlite/template_image_test.go b/internal/awsvmlite/template_image_test.go
deleted file mode 100644
index 88d74969..00000000
--- a/internal/awsvmlite/template_image_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package awsvmlite
-
-import "testing"
-
-// A template-image request must never be served from the warm pool. Pooled
-// stock is manufactured from the DEFAULT image, so handing one to a template
-// request returns a box without the customer's template and looks exactly like
-// a successful create — the failure only shows up later, as their code missing
-// a binary it asked for.
-func TestTemplateImageForcesColdLaunch(t *testing.T) {
- // Claim's contract: warm=false whenever a template image is requested.
- // Asserted on the Meta plumbing rather than a live AWS call, so it holds
- // without credentials.
- m := Meta{TemplateImageARN: "arn:aws:lambda:us-east-1:1:microvm-image:tpl"}
- if m.TemplateImageARN == "" {
- t.Fatal("fixture is wrong")
- }
- // A default-tier request must NOT carry an ARN, or every create would take
- // the cold path.
- if (Meta{MemoryMB: 4096}).TemplateImageARN != "" {
- t.Error("a plain size request must not carry a template image")
- }
-}
-
-// The metering rule: a template image is published at the default memory floor,
-// so a bound box reports the default tier rather than 0.
-func TestTemplateImageMetersAtDefaultTier(t *testing.T) {
- m := Meta{TemplateImageARN: "arn:x", MemoryMB: 0}
- if m.MemoryMB != 0 {
- t.Fatal("fixture")
- }
- // claimTemplateImage fills MemoryMB from Config().DefaultMemoryMB when the
- // request left it unset; a zero here would meter the sandbox as free.
-}