Skip to content

An open-source, faster Devin alternative

TypeScript

add the checkpoint d1 status sync

Brian Reardon13cf4de9ef39
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index f9e6a358..3d14b1a6 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -1001,5 +1001,200 @@ export async function handleDashboard(
});
}
+ // ── Stripe-backed billing ops ───────────────────────────────────────
+ //
+ // The legacy CP had these as dashboard_billing.go handlers. Edge equivalents
+ // call Stripe's REST API directly with STRIPE_API_KEY. Customer state lives
+ // in D1 orgs (stripe_customer_id, stripe_subscription_id) populated by the
+ // stripe webhook handler.
+ if (sub === "/billing/portal" && method === "POST") {
+ return handleBillingPortal(req, env, caller);
+ }
+ if (sub === "/billing/setup" && method === "POST") {
+ return handleBillingSetup(req, env, caller);
+ }
+ if (sub === "/billing/redeem" && method === "POST") {
+ return handleBillingRedeem(req, env, caller);
+ }
+ if (sub === "/billing/invoices" && method === "GET") {
+ return handleBillingInvoices(req, env, caller);
+ }
+
return json({ error: `not found: ${method} ${sub}` }, 404);
}
+
+// ── Stripe helpers ─────────────────────────────────────────────────────
+
+// stripeApi POSTs form-urlencoded to Stripe's REST API. GET is supported via
+// the `method` arg; body is ignored for GET. Returns parsed JSON or throws.
+async function stripeApi(env: DashboardEnv, path: string, body: Record<string, string> | null, method: "GET" | "POST" = "POST"): Promise<any> {
+ const url = `https://api.stripe.com${path}`;
+ const init: RequestInit = {
+ method,
+ headers: {
+ authorization: "Bearer " + env.STRIPE_API_KEY,
+ "stripe-version": "2024-06-20",
+ },
+ };
+ if (method === "POST" && body) {
+ (init.headers as Record<string, string>)["content-type"] = "application/x-www-form-urlencoded";
+ init.body = new URLSearchParams(body).toString();
+ }
+ const resp = await fetch(url, init);
+ const text = await resp.text();
+ let parsed: any;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ parsed = { raw: text };
+ }
+ if (!resp.ok) {
+ const msg = parsed?.error?.message ?? parsed?.raw ?? `stripe ${path} returned ${resp.status}`;
+ throw new Error(msg);
+ }
+ return parsed;
+}
+
+// loadOrgStripe pulls just the Stripe-relevant columns for a caller's org.
+async function loadOrgStripe(env: DashboardEnv, orgID: string): Promise<{ name: string; stripe_customer_id: string | null; stripe_subscription_id: string | null } | null> {
+ return env.OPENCOMPUTER_DB.prepare(
+ `SELECT name, stripe_customer_id, stripe_subscription_id FROM orgs WHERE id = ?1`,
+ )
+ .bind(orgID)
+ .first();
+}
+
+// ── Stripe billing handlers ────────────────────────────────────────────
+
+async function handleBillingPortal(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ const org = await loadOrgStripe(env, caller.orgID);
+ if (!org) return json({ error: "org not found" }, 404);
+ if (!org.stripe_customer_id) {
+ return json({ error: "no billing customer — upgrade to Pro first" }, 400);
+ }
+ // Bounce back wherever the dashboard came from when the user closes the portal.
+ const returnURL = req.headers.get("referer") ?? `${new URL(req.url).origin}/dashboard/billing`;
+ try {
+ const session = await stripeApi(env, "/v1/billing_portal/sessions", {
+ customer: org.stripe_customer_id,
+ return_url: returnURL,
+ });
+ return json({ url: session.url });
+ } catch (e) {
+ console.error("billing/portal:", e);
+ return json({ error: (e as Error).message }, 500);
+ }
+}
+
+async function handleBillingSetup(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ const org = await loadOrgStripe(env, caller.orgID);
+ if (!org) return json({ error: "org not found" }, 404);
+
+ // Ensure a Stripe customer exists — create one if this org has never been
+ // through checkout. Persist the ID back to D1 so the webhook flow can find
+ // it later (subscription.created carries customer_id + metadata.org_id).
+ let customerID = org.stripe_customer_id;
+ if (!customerID) {
+ try {
+ const cust = await stripeApi(env, "/v1/customers", {
+ name: org.name ?? "",
+ "metadata[org_id]": caller.orgID,
+ });
+ customerID = cust.id as string;
+ await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE orgs SET stripe_customer_id = ?1, updated_at = ?2 WHERE id = ?3`,
+ )
+ .bind(customerID, Math.floor(Date.now() / 1000), caller.orgID)
+ .run();
+ } catch (e) {
+ console.error("billing/setup create customer:", e);
+ return json({ error: "failed to create customer" }, 500);
+ }
+ }
+
+ const origin = new URL(req.url).origin;
+ try {
+ // SetupIntent-style checkout — Stripe collects the payment method, then
+ // the webhook (subscription.created or checkout.session.completed) marks
+ // the org as Pro. Mirrors legacy CreateSetupCheckoutSession field-for-
+ // field (mode=setup + currency=usd + metadata.type=setup); Stripe rejects
+ // setup-mode checkouts without `currency`.
+ const session = await stripeApi(env, "/v1/checkout/sessions", {
+ mode: "setup",
+ currency: "usd",
+ customer: customerID!,
+ success_url: `${origin}/dashboard/billing?setup=success`,
+ cancel_url: `${origin}/dashboard/billing?setup=cancel`,
+ "metadata[org_id]": caller.orgID,
+ "metadata[type]": "setup",
+ });
+ return json({ url: session.url });
+ } catch (e) {
+ console.error("billing/setup create checkout:", e);
+ // Surface Stripe's error message instead of a generic 500 so the
+ // dashboard / CLI can show it. Stripe errors carry useful detail
+ // (test/live mode mismatch, invalid customer, missing capability, etc).
+ return json({ error: (e as Error).message }, 500);
+ }
+}
+
+async function handleBillingRedeem(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ const body = (await req.json().catch(() => null)) as { code?: string } | null;
+ if (!body?.code) return json({ error: "code is required" }, 400);
+
+ const org = await loadOrgStripe(env, caller.orgID);
+ if (!org) return json({ error: "org not found" }, 404);
+ if (!org.stripe_customer_id) {
+ return json({ error: "billing not set up — upgrade to Pro first" }, 400);
+ }
+
+ try {
+ // Look up the promotion code → coupon
+ const promos = await stripeApi(env, `/v1/promotion_codes?code=${encodeURIComponent(body.code)}&active=true`, null, "GET");
+ const pc = promos?.data?.[0];
+ if (!pc) return json({ error: "promo code not found or inactive" }, 400);
+ const couponAmount = pc?.coupon?.amount_off as number | undefined;
+ if (!couponAmount || couponAmount <= 0) {
+ return json({ error: "promo code has no fixed amount_off" }, 400);
+ }
+
+ // Apply as a negative customer balance transaction (= credit). Stripe
+ // pulls from this on the next invoice.
+ await stripeApi(env, `/v1/customers/${org.stripe_customer_id}/balance_transactions`, {
+ amount: String(-couponAmount),
+ currency: pc?.coupon?.currency ?? "usd",
+ description: `Promotion code ${body.code}`,
+ });
+
+ return json({ creditAppliedCents: couponAmount });
+ } catch (e) {
+ console.error("billing/redeem:", e);
+ return json({ error: (e as Error).message }, 400);
+ }
+}
+
+async function handleBillingInvoices(_req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ const org = await loadOrgStripe(env, caller.orgID);
+ if (!org) return json({ error: "org not found" }, 404);
+ if (!org.stripe_customer_id) return json({ invoices: [] });
+ try {
+ const list = await stripeApi(env, `/v1/invoices?customer=${org.stripe_customer_id}&limit=25`, null, "GET");
+ const invoices = (list?.data ?? []).map((inv: any) => ({
+ id: inv.id,
+ status: inv.status,
+ total: inv.total,
+ amountPaid: inv.amount_paid,
+ amountDue: inv.amount_due,
+ currency: inv.currency,
+ hostedInvoiceUrl: inv.hosted_invoice_url,
+ invoicePdf: inv.invoice_pdf,
+ created: inv.created,
+ periodStart: inv.period_start,
+ periodEnd: inv.period_end,
+ }));
+ return json({ invoices });
+ } catch (e) {
+ console.error("billing/invoices:", e);
+ return json({ error: (e as Error).message }, 500);
+ }
+}
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 022635c6..de25f555 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1034,6 +1034,26 @@ export default {
return haltList(req, env);
}
+ // /internal/admin/do-mark-free — operator-only escape hatch to flip a
+ // CreditAccount DO's internal plan from "pro" back to "free" without
+ // running a real Stripe subscription.deleted webhook. HMAC-auth'd with
+ // the shared CF_ADMIN_SECRET. Body: { org_id }. Used by halt-flow tests
+ // and incident recovery when Stripe webhooks are missed; not exposed
+ // through any UI.
+ if (path === "/internal/admin/do-mark-free" && req.method === "POST") {
+ const ts = req.headers.get("X-Timestamp") ?? "";
+ const sig = req.headers.get("X-Signature") ?? "";
+ const body = await req.text();
+ const expected = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${body}`);
+ if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+ if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) return json({ error: "timestamp out of window" }, 401);
+ const parsed = JSON.parse(body) as { org_id?: string };
+ if (!parsed.org_id) return json({ error: "org_id required" }, 400);
+ const stub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(parsed.org_id));
+ const r = await stub.fetch(`https://do/mark-free?org_id=${encodeURIComponent(parsed.org_id)}`, { method: "POST" });
+ return new Response(await r.text(), { status: r.status, headers: { "content-type": "application/json" } });
+ }
+
// /internal/secret-stores/:id — HMAC-auth'd, called by CP at sandbox-create
// time to materialize the encrypted entry list. CP decrypts with the
// shared SECRET_ENCRYPTION_KEY before injecting into worker env.
@@ -1126,6 +1146,38 @@ export default {
if (req.method === "GET") return listSandboxes(req, env);
return json({ error: "method not allowed" }, 405);
}
+
+ // /api/sandboxes/from-checkpoint/{checkpointID} — spawn a new sandbox
+ // from a checkpoint. Routing differs from regular sandbox-scoped ops
+ // because the URL has no sandbox_id; we look up the cell from
+ // checkpoints_index via the checkpoint UUID. The CP-side handler
+ // (createFromCheckpoint) then pulls the checkpoint disks from Tigris
+ // and boots a sandbox in the owning cell.
+ {
+ const fc = path.match(/^\/api\/sandboxes\/from-checkpoint\/([^/]+)$/);
+ if (fc && req.method === "POST") {
+ const caller = await authenticate(req, env);
+ if (!caller) return json({ error: "missing or invalid API key" }, 401);
+ const cpID = fc[1];
+ const cpRow = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT owner_cell_id, org_id FROM checkpoints_index WHERE id = ?1`,
+ )
+ .bind(cpID)
+ .first<{ owner_cell_id: string; org_id: string }>();
+ if (!cpRow) return json({ error: "checkpoint not found" }, 404);
+ if (cpRow.org_id !== caller.orgID) return json({ error: "checkpoint not in your org" }, 403);
+ const cell = await lookupCell(env, cpRow.owner_cell_id);
+ if (!cell) return json({ error: `cell ${cpRow.owner_cell_id} not registered` }, 503);
+ const orgRow = await env.OPENCOMPUTER_DB.prepare("SELECT plan FROM orgs WHERE id = ?1")
+ .bind(caller.orgID).first<{ plan: string }>();
+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, orgRow?.plan ?? "free", caller.userID);
+ const fwd = new Request(cell.base_url.replace(/\/$/, "") + path, req);
+ fwd.headers.set("authorization", "Bearer " + token);
+ fwd.headers.delete("x-api-key");
+ return await fetch(fwd);
+ }
+ }
+
const m = path.match(/^\/api\/sandboxes\/([^/]+)(\/.*)?$/);
if (m) {
const id = m[1];
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.ts
index cbda36ea..1bdbeb2f 100644
--- a/cloudflare-workers/events-ingest/src/index.ts
+++ b/cloudflare-workers/events-ingest/src/index.ts
@@ -186,8 +186,56 @@ export default {
return lifecycleRunning.bind(tsSec, e.sandbox_id);
});
+ // Checkpoint lifecycle: keep D1 checkpoints_index in sync with cell PG
+ // sandbox_checkpoints. CP emits checkpoint_ready after SetCheckpointReady
+ // (UPSERT all fields) and checkpoint_deleted after DeleteCheckpoint. The
+ // dashboard cross-cell list + the edge's spawn-from-checkpoint routing
+ // both depend on this table being populated.
+ const checkpointUpsert = env.OPENCOMPUTER_DB.prepare(
+ `INSERT INTO checkpoints_index
+ (id, sandbox_id, org_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, '', NULL, ?7)
+ ON CONFLICT(id) DO UPDATE SET
+ sandbox_id = excluded.sandbox_id,
+ owner_cell_id = excluded.owner_cell_id,
+ s3_url = excluded.s3_url,
+ size_bytes = excluded.size_bytes`,
+ );
+ const checkpointDelete = env.OPENCOMPUTER_DB.prepare(
+ `DELETE FROM checkpoints_index WHERE id = ?1`,
+ );
+ const checkpointBatches = fresh
+ .filter((e) => e.type === "checkpoint_ready" || e.type === "checkpoint_deleted")
+ .flatMap((e) => {
+ const p = (e.payload ?? {}) as {
+ checkpoint_id?: string;
+ rootfs_s3_key?: string;
+ workspace_s3_key?: string;
+ size_bytes?: number;
+ };
+ if (!p.checkpoint_id) return [];
+ if (e.type === "checkpoint_deleted") {
+ return [checkpointDelete.bind(p.checkpoint_id)];
+ }
+ // checkpoint_ready — use rootfs_s3_key as the canonical s3_url since
+ // it's the rootfs delta the worker pulls at spawn time. The workspace
+ // key is reachable from the rootfs metadata.
+ const tsSec = Math.floor((Date.parse(e.timestamp) || Date.now()) / 1000);
+ return [
+ checkpointUpsert.bind(
+ p.checkpoint_id,
+ e.sandbox_id ?? "",
+ e.org_id ?? "",
+ e.cell_id,
+ p.rootfs_s3_key ?? "",
+ p.size_bytes ?? null,
+ tsSec,
+ ),
+ ];
+ });
+
try {
- await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches]);
+ await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches, ...checkpointBatches]);
} catch (err) {
// Database errors are retryable — return 5xx so the CP forwarder
// leaves the batch in the PEL.
diff --git a/internal/api/checkpoint_events.go b/internal/api/checkpoint_events.go
new file mode 100644
index 00000000..5d7aed96
--- /dev/null
+++ b/internal/api/checkpoint_events.go
@@ -0,0 +1,74 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "log"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/redis/go-redis/v9"
+)
+
+// publishCheckpointEvent XADDs a checkpoint lifecycle event to the cell's
+// local events:{cell_id} Redis stream so the forwarder + events-ingest
+// Worker can keep D1's checkpoints_index in sync. Same envelope shape as
+// the sandbox lifecycle events emitted by the worker per-sandbox SQLite +
+// the cell_capacity events emitted by controlplane.CapacityReporter.
+//
+// Event types:
+// checkpoint_ready — checkpoint upload finished; UPSERT row in D1
+// checkpoint_deleted — checkpoint dropped from cell PG; DELETE row in D1
+//
+// Best-effort: failure to XADD is logged but doesn't fail the caller. The
+// dashboard cross-cell view runs ~seconds behind cell PG truth as a result;
+// per-sandbox listings hit the cell directly via /api/sandboxes/{id}/
+// checkpoints so they're always authoritative.
+func (s *Server) publishCheckpointEvent(
+ ctx context.Context,
+ eventType string,
+ checkpointID uuid.UUID,
+ sandboxID string,
+ orgID uuid.UUID,
+ workerID string,
+ payload map[string]any,
+) {
+ if s.redisClient == nil || s.cellID == "" {
+ return
+ }
+ envelope := map[string]any{
+ "id": uuid.NewString(),
+ "type": eventType,
+ "sandbox_id": sandboxID,
+ "org_id": orgID.String(),
+ "worker_id": workerID,
+ "cell_id": s.cellID,
+ "payload": map[string]any{},
+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
+ }
+ // Merge in the checkpoint-specific payload + always include the
+ // checkpoint ID so events-ingest can key on it.
+ out := envelope["payload"].(map[string]any)
+ out["checkpoint_id"] = checkpointID.String()
+ for k, v := range payload {
+ out[k] = v
+ }
+
+ body, err := json.Marshal(envelope)
+ if err != nil {
+ log.Printf("publishCheckpointEvent: marshal: %v", err)
+ return
+ }
+
+ streamKey := "events:" + s.cellID
+ xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+ if err := s.redisClient.XAdd(xaddCtx, &redis.XAddArgs{
+ Stream: streamKey,
+ MaxLen: 100000,
+ Approx: true,
+ Values: map[string]any{"event": string(body)},
+ }).Err(); err != nil {
+ log.Printf("publishCheckpointEvent: XADD %s: %v", eventType, err)
+ }
+}
diff --git a/internal/api/dashboard.go b/internal/api/dashboard.go
index 1a609754..811480d0 100644
--- a/internal/api/dashboard.go
+++ b/internal/api/dashboard.go
@@ -1262,9 +1262,15 @@ func (s *Server) dashboardDeleteCheckpoint(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})
}
+ // Read the row first so we can include sandbox_id in the deletion event
+ // — events-ingest needs both to scope the D1 update.
+ cp, getErr := s.store.GetCheckpoint(c.Request().Context(), cpID)
if err := s.store.DeleteCheckpoint(c.Request().Context(), orgID, cpID); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
+ if getErr == nil && cp != nil {
+ s.publishCheckpointEvent(c.Request().Context(), "checkpoint_deleted", cpID, cp.SandboxID, orgID, "", nil)
+ }
return c.NoContent(http.StatusNoContent)
}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 22190eb3..4879e397 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -2150,6 +2150,11 @@ func (s *Server) createCheckpoint(c echo.Context) error {
// Pre-fix this was hardcoded to 0, leaving size_bytes meaningless.
_ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, grpcResp.SizeBytes)
log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, grpcResp.SizeBytes)
+ s.publishCheckpointEvent(context.Background(), "checkpoint_ready", checkpointID, sandboxID, orgID, session.WorkerID, map[string]any{
+ "rootfs_s3_key": grpcResp.RootfsS3Key,
+ "workspace_s3_key": grpcResp.WorkspaceS3Key,
+ "size_bytes": grpcResp.SizeBytes,
+ })
}()
} else if s.manager != nil {
go func() {
@@ -2169,6 +2174,11 @@ func (s *Server) createCheckpoint(c echo.Context) error {
}
_ = s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, sizeBytes)
log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, sizeBytes)
+ s.publishCheckpointEvent(context.Background(), "checkpoint_ready", checkpointID, sandboxID, orgID, session.WorkerID, map[string]any{
+ "rootfs_s3_key": rootfsKey,
+ "workspace_s3_key": workspaceKey,
+ "size_bytes": sizeBytes,
+ })
}()
} else {
s.pendingCreates.Delete(sandboxID)
@@ -2717,6 +2727,8 @@ func (s *Server) deleteCheckpoint(c echo.Context) error {
if err := s.store.DeleteCheckpoint(ctx, orgID, checkpointID); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
+ // Mirror the deletion to D1 checkpoints_index via events-ingest.
+ s.publishCheckpointEvent(ctx, "checkpoint_deleted", checkpointID, sandboxID, orgID, "", nil)
// Best-effort: delete S3 objects if checkpoint store is configured
if s.checkpointStore != nil && cp.RootfsS3Key != nil && cp.WorkspaceS3Key != nil {