From e6b77ec864cb34a734fa0b54b6510b2da1f9b870 Mon Sep 17 00:00:00 2001 From: Nathan Flurry Date: Wed, 4 Nov 2026 21:48:39 -0800 Subject: [PATCH] feat: run RivetKit apps as always-on envoys on Rivet v3 Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- benchmarks/dynamic-apps/package.json | 4 +- benchmarks/dynamic-apps/src/fixture.ts | 5 +- docs/content/docs/connect.mdx | 3 +- docs/content/docs/routing.mdx | 8 +- .../content/guides/host-ai-generated-apps.mdx | 2 +- examples/apps-ai-builder/src/server.ts | 4 + examples/apps-hello-world/src/server.ts | 7 +- .../fixtures/app/package.json | 2 +- .../fixtures/app/src/index.ts | 1 - examples/apps-multiplayer/package.json | 2 +- examples/apps-multiplayer/src/server.ts | 9 +- .../apps-sqlite/fixtures/app/package.json | 2 +- .../apps-sqlite/fixtures/app/src/index.ts | 1 - examples/apps-sqlite/package.json | 2 +- examples/apps-sqlite/src/server.ts | 9 +- examples/apps-static-website/src/server.ts | 9 +- .../apps-workflows/fixtures/app/package.json | 2 +- .../apps-workflows/fixtures/app/src/index.ts | 1 - examples/apps-workflows/package.json | 2 +- examples/apps-workflows/src/server.ts | 9 +- packages/dynamic-apps-builder/package.json | 4 +- .../dynamic-apps-builder/test/builder.test.ts | 1 - packages/dynamic-apps-core/src/internal.ts | 1 + packages/dynamic-apps-core/src/runtime.ts | 66 ++- packages/dynamic-apps/README.md | 67 +-- packages/dynamic-apps/package.json | 2 +- packages/dynamic-apps/src/actor-runtime.ts | 338 ++++++++------ packages/dynamic-apps/src/actors.ts | 425 ++++++++++++------ packages/dynamic-apps/src/control-plane.ts | 80 +--- packages/dynamic-apps/src/control-request.ts | 53 ++- packages/dynamic-apps/src/envoy-reconciler.ts | 117 +++++ packages/dynamic-apps/src/envoy-supervisor.ts | 340 ++++++++++++++ packages/dynamic-apps/src/index.ts | 1 + packages/dynamic-apps/src/registry.ts | 40 +- packages/dynamic-apps/src/release-store.ts | 13 +- packages/dynamic-apps/src/runtime.ts | 136 +++--- packages/dynamic-apps/src/skills.ts | 5 +- packages/dynamic-apps/src/types.ts | 2 +- packages/dynamic-apps/tests/direct.test.ts | 20 - .../dynamic-apps/tests/release-store.test.ts | 21 +- pnpm-lock.yaml | 281 ++++++------ pnpm-workspace.yaml | 10 +- scripts/check-boundaries.mjs | 4 +- scripts/test-packed.mjs | 1 + tests/e2e/dynamic-apps/package.json | 5 +- .../e2e/dynamic-apps/src/failover-fixture.ts | 38 ++ tests/e2e/dynamic-apps/src/failover-host.ts | 20 + tests/e2e/dynamic-apps/src/failover.ts | 87 ++++ tests/e2e/dynamic-apps/src/run.ts | 52 ++- tests/e2e/dynamic-apps/src/sanity.ts | 5 +- tests/e2e/dynamic-apps/src/verify.ts | 116 ++++- 52 files changed, 1676 insertions(+), 763 deletions(-) create mode 100644 packages/dynamic-apps/src/envoy-reconciler.ts create mode 100644 packages/dynamic-apps/src/envoy-supervisor.ts create mode 100644 tests/e2e/dynamic-apps/src/failover-fixture.ts create mode 100644 tests/e2e/dynamic-apps/src/failover-host.ts create mode 100644 tests/e2e/dynamic-apps/src/failover.ts diff --git a/README.md b/README.md index cac738c66..f33fd14b4 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Rivet Dynamic Apps > [!WARNING] -> Dynamic Apps currently supports only Rivet 2.x. Rivet 3.x support is coming -> soon. +> Dynamic Apps requires Rivet 3.x. Apps that use RivetKit run as an always-on +> envoy per app and do not scale to zero. Build user-generated request handlers in a sandboxed deployment VM, keep their release state in a Rivet actor, and serve cache-hit requests from bounded local diff --git a/benchmarks/dynamic-apps/package.json b/benchmarks/dynamic-apps/package.json index f8b4ce26a..0d592e751 100644 --- a/benchmarks/dynamic-apps/package.json +++ b/benchmarks/dynamic-apps/package.json @@ -21,10 +21,10 @@ "@rivet-dev/dynamic-apps": "workspace:*", "@rivet-dev/dynamic-apps-core": "workspace:*", "hono": "^4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { - "@rivetkit/engine-cli": "2.3.29", + "@rivetkit/engine-cli": "3.0.2", "@types/node": "^22.19.15", "get-port": "^7.1.0", "tsx": "^4.20.6", diff --git a/benchmarks/dynamic-apps/src/fixture.ts b/benchmarks/dynamic-apps/src/fixture.ts index 79d634c9e..b0b6a46f1 100644 --- a/benchmarks/dynamic-apps/src/fixture.ts +++ b/benchmarks/dynamic-apps/src/fixture.ts @@ -61,7 +61,7 @@ export async function deployActorBenchmarkFixture( main: "index.js", dependencies: { hono: "4.13.5", - rivetkit: "2.3.29", + rivetkit: "3.0.2", }, }), "index.js": ` @@ -100,9 +100,8 @@ const counter = actor({ }, }); -const registry = setup({ use: { counter } }); +export const registry = setup({ use: { counter } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.all("*", () => Response.json({ ok: true, workload: "actor-and-direct-http" })); export default app; `, diff --git a/docs/content/docs/connect.mdx b/docs/content/docs/connect.mdx index 47eb855d9..52d92c06f 100644 --- a/docs/content/docs/connect.mdx +++ b/docs/content/docs/connect.mdx @@ -21,7 +21,8 @@ Each app gets its own Rivet namespace, which provides it: - Complete per-tenant isolation - Per-user billing -- Infrastructure that costs nothing when idle +- Its own node pool. Apps that define actors keep one agentOS VM running while + deployed, so they do not scale to zero. ## Connecting to Rivet diff --git a/docs/content/docs/routing.mdx b/docs/content/docs/routing.mdx index fec83f82e..757292757 100644 --- a/docs/content/docs/routing.mdx +++ b/docs/content/docs/routing.mdx @@ -8,16 +8,20 @@ skill: true ## Getting started -Mount it at any prefix and forward the private `/api/rivet/*` callback to it: +Mount it at any prefix. Forwarding `/api/rivet/*` to it exposes the host's +Rivet health, metadata, and metrics routes: ```ts -import { appsRouter } from "@rivet-dev/dynamic-apps"; +import { appsRouter, startDynamicAppsHost } from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); server.all("/api/rivet/*", (c) => appsRouter.fetch(c.req.raw)); server.route("/apps", appsRouter); + +// Start running deployed apps' actors when the host boots. +await startDynamicAppsHost(); ``` A request to `/apps/example/api/items` reaches that app's handler as diff --git a/docs/content/guides/host-ai-generated-apps.mdx b/docs/content/guides/host-ai-generated-apps.mdx index 3d5162ce2..5d6b60b45 100644 --- a/docs/content/guides/host-ai-generated-apps.mdx +++ b/docs/content/guides/host-ai-generated-apps.mdx @@ -125,7 +125,7 @@ The server has a route that deploys apps and a router that serves them: - `POST /deploy/:name` checks that the prompt is a string of at most 4,000 characters, then returns what `deployApp` returns: the app's release, endpoint, namespace, pool, and a token when one is needed. - `server.route("/apps", appsRouter)` serves every app under its own path. A request to `/apps/team-board/api/items` reaches the `team-board` app's fetch handler as `/api/items`. See [Route](/dynamic-apps/docs/routing). -- `/api/rivet/*` is a private callback that lets Rivet reach your server to manage deployments. Forward it to `appsRouter` as shown. +- `/api/rivet/*` exposes the host's Rivet health, metadata, and metrics routes. Forward it to `appsRouter` as shown. - Requests run in a cached agentOS VM inside the same process, so there is no extra network hop between your server and the app. diff --git a/examples/apps-ai-builder/src/server.ts b/examples/apps-ai-builder/src/server.ts index bfa503933..baae080a0 100644 --- a/examples/apps-ai-builder/src/server.ts +++ b/examples/apps-ai-builder/src/server.ts @@ -5,6 +5,7 @@ import { appsRouter, deployApp, rivetActorsSkill, + startDynamicAppsHost, webServerSkill, } from "@rivet-dev/dynamic-apps"; import { generateObject } from "ai"; @@ -133,6 +134,9 @@ server.post("/deploy/:name", async (context) => { server.route("/apps", appsRouter); // docs:end routes +// Start running deployed apps' actors as soon as the host boots. +await startDynamicAppsHost(); + serve({ fetch: server.fetch, port: 3000, diff --git a/examples/apps-hello-world/src/server.ts b/examples/apps-hello-world/src/server.ts index b42544187..0b2a59dc7 100644 --- a/examples/apps-hello-world/src/server.ts +++ b/examples/apps-hello-world/src/server.ts @@ -1,15 +1,18 @@ import { serve } from "@hono/node-server"; -import { appsRouter } from "@rivet-dev/dynamic-apps"; +import { appsRouter, startDynamicAppsHost } from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); -// This is how the Rivet control plane communicates with your backend. +// Exposes the host's Rivet health, metadata, and metrics routes. server.all("/api/rivet/*", (c) => appsRouter.fetch(c.req.raw)); // Mount every deployed application at /apps/:appId. server.route("/apps", appsRouter); +// Start running deployed apps' actors as soon as the host boots. +await startDynamicAppsHost(); + // Serve the host router over HTTP. serve({ fetch: server.fetch, diff --git a/examples/apps-multiplayer/fixtures/app/package.json b/examples/apps-multiplayer/fixtures/app/package.json index bd5763242..7372469b4 100644 --- a/examples/apps-multiplayer/fixtures/app/package.json +++ b/examples/apps-multiplayer/fixtures/app/package.json @@ -6,6 +6,6 @@ "main": "src/index.ts", "dependencies": { "hono": "4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" } } diff --git a/examples/apps-multiplayer/fixtures/app/src/index.ts b/examples/apps-multiplayer/fixtures/app/src/index.ts index 6debf3686..d3ea5771f 100644 --- a/examples/apps-multiplayer/fixtures/app/src/index.ts +++ b/examples/apps-multiplayer/fixtures/app/src/index.ts @@ -24,7 +24,6 @@ const room = actor({ export const registry = setup({ use: { room } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.get("/", (c) => c.json({ message: "Use the RivetKit client to join a room." }), ); diff --git a/examples/apps-multiplayer/package.json b/examples/apps-multiplayer/package.json index 0275765af..bc5c82830 100644 --- a/examples/apps-multiplayer/package.json +++ b/examples/apps-multiplayer/package.json @@ -12,7 +12,7 @@ "@hono/node-server": "^2.1.1", "@rivet-dev/dynamic-apps": "workspace:*", "hono": "^4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { "@types/node": "^22.20.1", diff --git a/examples/apps-multiplayer/src/server.ts b/examples/apps-multiplayer/src/server.ts index 32e26acca..8d7957213 100644 --- a/examples/apps-multiplayer/src/server.ts +++ b/examples/apps-multiplayer/src/server.ts @@ -1,5 +1,9 @@ import { serve } from "@hono/node-server"; -import { appsRouter, deployApp } from "@rivet-dev/dynamic-apps"; +import { + appsRouter, + deployApp, + startDynamicAppsHost, +} from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); @@ -18,4 +22,7 @@ server.post("/deploy/:name", async (c) => server.route("/apps", appsRouter); +// Start running deployed apps' actors as soon as the host boots. +await startDynamicAppsHost(); + serve({ fetch: server.fetch, port: Number(process.env.PORT ?? 3000) }); diff --git a/examples/apps-sqlite/fixtures/app/package.json b/examples/apps-sqlite/fixtures/app/package.json index 3bb430c3a..a3bfe296f 100644 --- a/examples/apps-sqlite/fixtures/app/package.json +++ b/examples/apps-sqlite/fixtures/app/package.json @@ -6,6 +6,6 @@ "main": "src/index.ts", "dependencies": { "hono": "4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" } } diff --git a/examples/apps-sqlite/fixtures/app/src/index.ts b/examples/apps-sqlite/fixtures/app/src/index.ts index bb9069195..d731dc666 100644 --- a/examples/apps-sqlite/fixtures/app/src/index.ts +++ b/examples/apps-sqlite/fixtures/app/src/index.ts @@ -27,7 +27,6 @@ const notes = actor({ export const registry = setup({ use: { notes } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.get("/", (c) => c.json({ message: "Use the RivetKit client to add notes." }), ); diff --git a/examples/apps-sqlite/package.json b/examples/apps-sqlite/package.json index aaab4be89..50b49f72a 100644 --- a/examples/apps-sqlite/package.json +++ b/examples/apps-sqlite/package.json @@ -12,7 +12,7 @@ "@hono/node-server": "^2.1.1", "@rivet-dev/dynamic-apps": "workspace:*", "hono": "^4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { "@types/node": "^22.20.1", diff --git a/examples/apps-sqlite/src/server.ts b/examples/apps-sqlite/src/server.ts index 32e26acca..8d7957213 100644 --- a/examples/apps-sqlite/src/server.ts +++ b/examples/apps-sqlite/src/server.ts @@ -1,5 +1,9 @@ import { serve } from "@hono/node-server"; -import { appsRouter, deployApp } from "@rivet-dev/dynamic-apps"; +import { + appsRouter, + deployApp, + startDynamicAppsHost, +} from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); @@ -18,4 +22,7 @@ server.post("/deploy/:name", async (c) => server.route("/apps", appsRouter); +// Start running deployed apps' actors as soon as the host boots. +await startDynamicAppsHost(); + serve({ fetch: server.fetch, port: Number(process.env.PORT ?? 3000) }); diff --git a/examples/apps-static-website/src/server.ts b/examples/apps-static-website/src/server.ts index d08f4a02a..6bf2dd468 100644 --- a/examples/apps-static-website/src/server.ts +++ b/examples/apps-static-website/src/server.ts @@ -1,5 +1,9 @@ import { serve } from "@hono/node-server"; -import { appsRouter, deployApp } from "@rivet-dev/dynamic-apps"; +import { + appsRouter, + deployApp, + startDynamicAppsHost, +} from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); @@ -14,5 +18,8 @@ await deployApp({ }); // docs:end deploy +// Start running deployed apps' actors as soon as the host boots. +await startDynamicAppsHost(); + serve({ fetch: server.fetch, port: Number(process.env.PORT ?? 3000) }); console.log("Open http://localhost:3000/apps/static-website/"); diff --git a/examples/apps-workflows/fixtures/app/package.json b/examples/apps-workflows/fixtures/app/package.json index b666c45e9..133d3a6c4 100644 --- a/examples/apps-workflows/fixtures/app/package.json +++ b/examples/apps-workflows/fixtures/app/package.json @@ -6,6 +6,6 @@ "main": "src/index.ts", "dependencies": { "hono": "4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" } } diff --git a/examples/apps-workflows/fixtures/app/src/index.ts b/examples/apps-workflows/fixtures/app/src/index.ts index b1b24032a..ce372e048 100644 --- a/examples/apps-workflows/fixtures/app/src/index.ts +++ b/examples/apps-workflows/fixtures/app/src/index.ts @@ -28,7 +28,6 @@ const order = actor({ export const registry = setup({ use: { order } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.get("/", (c) => c.json({ message: "Use the RivetKit client to read orders." }), ); diff --git a/examples/apps-workflows/package.json b/examples/apps-workflows/package.json index 7d77a9d67..1a463697c 100644 --- a/examples/apps-workflows/package.json +++ b/examples/apps-workflows/package.json @@ -12,7 +12,7 @@ "@hono/node-server": "^2.1.1", "@rivet-dev/dynamic-apps": "workspace:*", "hono": "^4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { "@types/node": "^22.20.1", diff --git a/examples/apps-workflows/src/server.ts b/examples/apps-workflows/src/server.ts index 32e26acca..8d7957213 100644 --- a/examples/apps-workflows/src/server.ts +++ b/examples/apps-workflows/src/server.ts @@ -1,5 +1,9 @@ import { serve } from "@hono/node-server"; -import { appsRouter, deployApp } from "@rivet-dev/dynamic-apps"; +import { + appsRouter, + deployApp, + startDynamicAppsHost, +} from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); @@ -18,4 +22,7 @@ server.post("/deploy/:name", async (c) => server.route("/apps", appsRouter); +// Start running deployed apps' actors as soon as the host boots. +await startDynamicAppsHost(); + serve({ fetch: server.fetch, port: Number(process.env.PORT ?? 3000) }); diff --git a/packages/dynamic-apps-builder/package.json b/packages/dynamic-apps-builder/package.json index 2ed56f522..30f159367 100644 --- a/packages/dynamic-apps-builder/package.json +++ b/packages/dynamic-apps-builder/package.json @@ -35,10 +35,10 @@ }, "dependencies": { "@hono/node-server": "2.1.1", - "@rivetkit/rivetkit-wasm": "2.3.29", + "@rivetkit/rivetkit-wasm": "3.0.2", "esbuild-wasm": "0.27.4", "hono": "4.13.5", - "rivetkit": "2.3.29", + "rivetkit": "3.0.2", "secure-exec": "0.2.1" }, "devDependencies": { diff --git a/packages/dynamic-apps-builder/test/builder.test.ts b/packages/dynamic-apps-builder/test/builder.test.ts index 9a1da8b46..8ea99b11a 100644 --- a/packages/dynamic-apps-builder/test/builder.test.ts +++ b/packages/dynamic-apps-builder/test/builder.test.ts @@ -356,7 +356,6 @@ describe("apps-builder", () => { PORT: String(port), DYNAMIC_APPS_READY_NONCE: "builder-test", RIVETKIT_RUNTIME: "wasm", - RIVETKIT_RUNTIME_MODE: "serverless", }, }); let stderr = ""; diff --git a/packages/dynamic-apps-core/src/internal.ts b/packages/dynamic-apps-core/src/internal.ts index b2cb67c7d..95f9066e8 100644 --- a/packages/dynamic-apps-core/src/internal.ts +++ b/packages/dynamic-apps-core/src/internal.ts @@ -30,6 +30,7 @@ export { DIRECT_ENTRYPOINT, DIRECT_RUNTIME_FORMAT, directRunnerSource, + ENVOY_SHUTDOWN_PATH, GUEST_FORMAT_ERROR_SOURCE, normalizeAppPath, } from "./runtime.js"; diff --git a/packages/dynamic-apps-core/src/runtime.ts b/packages/dynamic-apps-core/src/runtime.ts index f01193f71..c94914ae0 100644 --- a/packages/dynamic-apps-core/src/runtime.ts +++ b/packages/dynamic-apps-core/src/runtime.ts @@ -39,7 +39,7 @@ export function canonicalDeploymentHash(input: { deploymentIdentity?: string; }): string { const hash = createHash("sha256"); - hash.update("dynamic-apps-release-v19-mounted-hono-router\0"); + hash.update("dynamic-apps-release-v20-rivet-v3-envoy\0"); const field = (value: string | Uint8Array) => { const bytes = typeof value === "string" ? Buffer.from(value) : value; const length = Buffer.allocUnsafe(8); @@ -154,7 +154,17 @@ export const GUEST_FORMAT_ERROR_SOURCE = `function formatError(error) { return lines.join("\\n"); }`; -/** Initializes RivetKit WASM and hosts the application's exported fetch handler. */ +/** Path of the envoy runner's control endpoint that drains its registry. */ +export const ENVOY_SHUTDOWN_PATH = "/.dynamic-apps/envoy/shutdown"; + +/** + * Initializes RivetKit WASM and runs the application in one of two modes. + * + * The default mode hosts the application's exported fetch handler for direct + * HTTP traffic. With `DYNAMIC_APPS_RUNNER_MODE=envoy` it instead starts the + * exported registry as a long-lived envoy that hosts the application's actors, + * and serves only a control endpoint that drains that envoy. + */ export function actorRunnerSource(entrypointInput: string): string { const entrypoint = `./${normalizeAppPath(entrypointInput)}`; return `import { readFile } from "node:fs/promises"; @@ -164,23 +174,45 @@ import initializeRivetKit from "@rivetkit/rivetkit-wasm"; const wasmUrl = new URL(__AGENTOS_RIVETKIT_WASM_PATH__, import.meta.url); await initializeRivetKit({ module_or_path: await readFile(wasmUrl) }); const applicationModule = await import(${JSON.stringify(entrypoint)}); -const application = applicationModule.default; -const fetch = typeof application === "function" - ? application - : typeof application?.fetch === "function" - ? application.fetch.bind(application) - : undefined; -if (!fetch) { - throw new TypeError("Dynamic App entrypoint default export must be a fetch handler"); -} ${GUEST_FORMAT_ERROR_SOURCE} -async function handle(request, ...rest) { - try { - return await fetch(request, ...rest); - } catch (error) { - console.error(formatError(error)); - return new Response("Internal Server Error", { status: 500 }); +let handle; +if (process.env.DYNAMIC_APPS_RUNNER_MODE === "envoy") { + const registry = applicationModule.registry; + if (typeof registry?.start !== "function" || typeof registry?.shutdown !== "function") { + throw new TypeError( + "Dynamic Apps using RivetKit must export the registry from the entrypoint: export const registry = setup(...)", + ); + } + registry.start(); + let shutdown; + handle = async (request) => { + const url = new URL(request.url); + if (request.method !== "POST" || url.pathname !== ${JSON.stringify(ENVOY_SHUTDOWN_PATH)}) { + return new Response("Not Found", { status: 404 }); + } + // The guest exits once drained so the host can dispose its VM cleanly. + shutdown ??= registry.shutdown().finally(() => setTimeout(() => process.exit(0), 0)); + await shutdown; + return new Response("drained"); + }; +} else { + const application = applicationModule.default; + const fetch = typeof application === "function" + ? application + : typeof application?.fetch === "function" + ? application.fetch.bind(application) + : undefined; + if (!fetch) { + throw new TypeError("Dynamic App entrypoint default export must be a fetch handler"); } + handle = async (request, ...rest) => { + try { + return await fetch(request, ...rest); + } catch (error) { + console.error(formatError(error)); + return new Response("Internal Server Error", { status: 500 }); + } + }; } await new Promise((resolve, reject) => { const server = serve({ diff --git a/packages/dynamic-apps/README.md b/packages/dynamic-apps/README.md index bcce61dc2..5aa6c111d 100644 --- a/packages/dynamic-apps/README.md +++ b/packages/dynamic-apps/README.md @@ -37,9 +37,8 @@ bodies are not supported. ## App-defined actors -An app that declares `rivetkit` mounts the registry handler in its exported -fetch router. Dynamic Apps owns the HTTP listener and uses the same cached -agentOS process for ordinary routes and Rivet callbacks: +An app that declares `rivetkit` exports its registry as `registry` next to its +default fetch handler: ```ts import { actor, setup } from "rivetkit"; @@ -54,16 +53,14 @@ const counter = actor({ }, }); -const registry = setup({ use: { counter } }); +export const registry = setup({ use: { counter } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.all("*", () => new Response("ok")); export default app; ``` -Do not call `serve()`, `registry.start()`, or bind a port in application code. -Dynamic Apps starts the platform listener and waits for its listening callback; -it does not poll an application health route. +Do not call `serve()`, `registry.start()`, `registry.handler()`, or bind a port +in application code. Dynamic Apps runs the registry and the HTTP listener. Use the unchanged `deployApp` result to create the app client: @@ -95,37 +92,35 @@ npx @rivetkit/cli deploy \ --env RIVET_CLOUD_TOKEN="$RIVET_CLOUD_TOKEN" ``` -By default, the app actor callback enters through the host app actor's Rivet -gateway and authenticates with the publishable credential from -`RIVET_PUBLIC_ENDPOINT`. This keeps the child app namespace separate from the -host registry namespace. `DYNAMIC_APPS_CALLBACK_URL` is only for a custom -receiver that accepts child-namespace lifecycle callbacks; Dynamic Apps appends -`/api/rivet` to that origin. - -Actor requests follow the normal Rivet Engine path. The app's serverless -callback mounts its verified artifact in agentOS and runs the bundled RivetKit -WebAssembly runtime in serverless mode. State, actions, events, connections, -and streaming actor responses are handled by RivetKit inside the sandbox. The -same listener serves the app's ordinary HTTP routes without importing the app a -second time. - -Rivet Engine requires `/api/rivet/start` to return a long-lived SSE control -stream containing the real runner-init packet and keepalive pings. Actor traffic -does not travel in this response; it uses RivetKit's outbound WebSocket. Dynamic -Apps forwards the server's response with agentOS's native VM HTTP stream, -including backpressure and cancellation. No app code executes in the host. - -Dynamic Apps does not impose a separate actor-callback concurrency gate. The -configured actor runtime count controls retained idle entries only; active -AgentOS runtimes are not rejected or evicted because that target is full. +Actors run on Rivet v3. When a RivetKit release is activated, the app's +private actor boots the release's artifact in an agentOS VM and starts the +exported registry as a long-lived envoy in the app's namespace and pool. The +release only becomes active once that envoy has connected. The VM stays running +while the release is active, so it does not scale to zero or out: each RivetKit +app holds one VM on one host process. Deploying a new release starts its envoy +first, then drains the previous one so its actors move to the new release. + +If the guest process exits, the host restarts it with backoff. If a host +process stops gracefully, the app actor moves to another host and starts the +envoy there. Every host also wakes each RivetKit app once a minute, which +restarts the envoy of an app whose host process died without a graceful +shutdown. + +Envoys authenticate with the credentials in `RIVET_PUBLIC_ENDPOINT`, or with +the namespace secret token that Dynamic Apps provisions on Rivet Cloud. App +code receives that credential, so on a self-hosted Engine give +`RIVET_PUBLIC_ENDPOINT` a token scoped to app namespaces, not an admin token. + +Ordinary HTTP routes of a RivetKit app run in separate cached agentOS VMs that +do not start an envoy. No app code executes in the host. ## Host integration -Mount application traffic and the private Rivet callback separately: +Mount application traffic and the host registry's Rivet routes separately: ```ts import { serve } from "@hono/node-server"; -import { appsRouter } from "@rivet-dev/dynamic-apps"; +import { appsRouter, startDynamicAppsHost } from "@rivet-dev/dynamic-apps"; import { Hono } from "hono"; const server = new Hono(); @@ -133,9 +128,15 @@ const server = new Hono(); server.all("/api/rivet/*", (c) => appsRouter.fetch(c.req.raw)); server.route("/apps", appsRouter); +await startDynamicAppsHost(); serve({ fetch: server.fetch, port: 3000 }); ``` +Call `startDynamicAppsHost()` once when the host boots. It starts the host's +private actors and the loop that restarts app envoys after a host dies. Without +it a host only joins after its first request, so after every host restarts, +apps that serve only actor traffic would stay offline. + Run Node 22 or newer normally: ```sh diff --git a/packages/dynamic-apps/package.json b/packages/dynamic-apps/package.json index d126ce282..609708178 100644 --- a/packages/dynamic-apps/package.json +++ b/packages/dynamic-apps/package.json @@ -34,7 +34,7 @@ "@rivet-dev/agentos-core": "0.4.3", "@rivet-dev/dynamic-apps-core": "workspace:0.3.0", "hono": "^4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { "@rivet-dev/agentos-toolchain": "0.4.3", diff --git a/packages/dynamic-apps/src/actor-runtime.ts b/packages/dynamic-apps/src/actor-runtime.ts index 17c336d50..6b5e95ac2 100644 --- a/packages/dynamic-apps/src/actor-runtime.ts +++ b/packages/dynamic-apps/src/actor-runtime.ts @@ -1,4 +1,4 @@ -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -14,7 +14,7 @@ import { import { DynamicAppsLogLineDecoder, emitDynamicAppsLog } from "./logging.js"; import { getDynamicAppsVmOptions } from "./vm-options.js"; -const ACTOR_HTTP_PORT = 3000; +export const ACTOR_HTTP_PORT = 3000; const HOP_BY_HOP_HEADERS = [ "connection", "keep-alive", @@ -65,9 +65,8 @@ interface RuntimeEntry { key: string; appId: string; release: string; - directory: string; + launched: LaunchedActorVm; vm: AgentOs; - pid: number; active: number; lastUsedAt: number; disposed: boolean; @@ -314,111 +313,31 @@ export class DynamicActorRuntime implements ApplicationServerRuntime { } async #createEntry(input: ActorRuntimeRequest): Promise { - const directory = await mkdtemp( - join(tmpdir(), "dynamic-app-actor-agentos-"), - ); - const artifactPath = join(directory, "release.aospkg"); - let vm: AgentOs | undefined; - try { - const environment = resolveWorkerEnvironment(input); - await chmod(directory, 0o700); - await writeFile(artifactPath, await input.loadArtifact(), { - mode: 0o600, - }); - vm = await AgentOs.create( - resolveActorAgentOsOptions( - await resolveVmOptions(getDynamicAppsVmOptions(), { - appId: input.appId ?? "unknown", - release: input.release ?? "unknown", - }), - artifactPath, - this.config.heapLimitMb, - environment.RIVET_ENDPOINT, - ), - ); - const pendingLogs: Array<[GuestLogLine["stream"], string, boolean]> = []; - const readyNonce = randomUUID(); - const readyMarker = `DYNAMIC_APPS_SERVER_READY:${readyNonce}`; - let readyBuffer = ""; - let resolveReady = () => {}; - let rejectReady = (_error: unknown) => {}; - const ready = new Promise((resolve, reject) => { - resolveReady = resolve; - rejectReady = reject; - }); - let entry: RuntimeEntry | undefined; - const logLine = - (stream: GuestLogLine["stream"]) => - (message: string, truncated: boolean) => { - // The readiness marker is a platform handshake, not application output. - if (message === readyMarker) return; - if (entry) this.#logGuest(entry, { stream, message, truncated }); - else pendingLogs.push([stream, message, truncated]); - }; - const stdoutLines = new DynamicAppsLogLineDecoder(logLine("stdout")); - const stderrLines = new DynamicAppsLogLineDecoder(logLine("stderr")); - const process = await vm.process.spawn("node", ["/app/actor/main.mjs"], { - cwd: "/app/actor", - env: stringEnvironment({ - ...environment, - PORT: String(ACTOR_HTTP_PORT), - DYNAMIC_APPS_READY_NONCE: readyNonce, - }), - onStdout: (data) => { - readyBuffer = `${readyBuffer}${new TextDecoder().decode(data)}`.slice( - -4_096, - ); - if (readyBuffer.includes(readyMarker)) resolveReady(); - stdoutLines.write(data); - }, - onStderr: (data) => stderrLines.write(data), - }); - entry = { - key: input.key, - appId: input.appId ?? "unknown", - release: input.release ?? "unknown", - directory, - vm, - pid: process.pid, - active: 0, - lastUsedAt: Date.now(), - disposed: false, - }; - for (const [stream, message, truncated] of pendingLogs) - this.#logGuest(entry, { stream, message, truncated }); - const processExit = vm.process.wait(process.pid); - const onProcessEnd = (error: Error) => { - stdoutLines.end(); - stderrLines.end(); - rejectReady(error); - if (!entry || entry.disposed) return; - this.#failEntry(entry, error); - }; - // agentOS rejects the wait when the VM is disposed before it observes the - // exit, which is the normal outcome of disposing a running entry. - void processExit.then( - (exit) => - onProcessEnd( - new Error( - `Dynamic App agentOS actor process exited with ${exit.exitCode ?? 1}`, - ), - ), - (error: unknown) => - onProcessEnd( - error instanceof Error ? error : new Error(String(error)), - ), - ); - await withTimeout( - ready, - this.config.startTimeoutMs, - `Dynamic App agentOS actor startup exceeded ${this.config.startTimeoutMs}ms`, - ); - return entry; - } catch (error) { - await vm?.dispose().catch(() => {}); - await rm(directory, { recursive: true, force: true }).catch(() => {}); - throw error; - } + const appId = input.appId ?? "unknown"; + const release = input.release ?? "unknown"; + let entry: RuntimeEntry | undefined; + const launched = await launchActorVm({ + appId, + release, + artifact: await input.loadArtifact(), + environment: resolveWorkerEnvironment(input), + heapLimitMb: this.config.heapLimitMb, + startTimeoutMs: this.config.startTimeoutMs, + onExit: (error) => { + if (entry && !entry.disposed) this.#failEntry(entry, error); + }, + }); + entry = { + key: input.key, + appId, + release, + launched, + vm: launched.vm, + active: 0, + lastUsedAt: Date.now(), + disposed: false, + }; + return entry; } #failEntry(entry: RuntimeEntry, error: unknown): void { @@ -434,21 +353,6 @@ export class DynamicActorRuntime implements ApplicationServerRuntime { void this.#disposeEntry(entry); } - #logGuest( - entry: Pick, - line: GuestLogLine, - ): void { - emitDynamicAppsLog({ - level: line.stream === "stdout" ? "info" : "error", - source: "actor", - message: line.message, - appId: entry.appId, - release: entry.release, - stream: line.stream, - ...(line.truncated ? { metadata: { truncated: true } } : {}), - }); - } - async #prune(protectedKey?: string): Promise { if (this.#disposed) return; const now = Date.now(); @@ -497,22 +401,174 @@ export class DynamicActorRuntime implements ApplicationServerRuntime { async #disposeEntry(entry: RuntimeEntry): Promise { if (entry.disposed) return; entry.disposed = true; - const results = await Promise.allSettled([ - entry.vm.dispose(), - rm(entry.directory, { recursive: true, force: true }), - ]); - if (results.some((result) => result.status === "rejected")) { - emitDynamicAppsLog({ - level: "error", - source: "runtime", - message: "Dynamic App agentOS actor disposal failed", - appId: entry.appId, - release: entry.release, - }); + await entry.launched.dispose(); + } +} + +/** One running agentOS VM hosting a release's actor runner process. */ +export interface LaunchedActorVm { + vm: AgentOs; + pid: number; + /** Settles once the guest process ends, with the reason it ended. */ + exited: Promise; + /** Whether the guest process has already ended. */ + hasExited(): boolean; + /** Why the guest process ended; only meaningful once it has. */ + exitError(): Error; + /** Disposes the VM and its artifact directory; safe to call repeatedly. */ + dispose(): Promise; +} + +/** + * Boots an agentOS VM over a release artifact and starts its actor runner, + * resolving once the runner reports readiness. `onExit` runs once when the + * guest process ends for any reason, including disposal. + */ +export async function launchActorVm(input: { + appId: string; + release: string; + artifact: Uint8Array; + environment: Record; + heapLimitMb: number; + startTimeoutMs: number; + onExit?: (error: Error) => void; +}): Promise { + const directory = await mkdtemp(join(tmpdir(), "dynamic-app-actor-agentos-")); + const artifactPath = join(directory, "release.aospkg"); + let vm: AgentOs | undefined; + try { + await chmod(directory, 0o700); + await writeFile(artifactPath, input.artifact, { mode: 0o600 }); + vm = await AgentOs.create( + resolveActorAgentOsOptions( + await resolveVmOptions(getDynamicAppsVmOptions(), { + appId: input.appId, + release: input.release, + }), + artifactPath, + input.heapLimitMb, + input.environment.RIVET_ENDPOINT, + ), + ); + const createdVm = vm; + const readyNonce = randomUUID(); + const readyMarker = `DYNAMIC_APPS_SERVER_READY:${readyNonce}`; + let readyBuffer = ""; + let resolveReady = () => {}; + let rejectReady = (_error: unknown) => {}; + const ready = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + const logLine = + (stream: GuestLogLine["stream"]) => + (message: string, truncated: boolean) => { + // The readiness marker is a platform handshake, not application output. + if (message === readyMarker) return; + logGuest(input, { stream, message, truncated }); + }; + const stdoutLines = new DynamicAppsLogLineDecoder(logLine("stdout")); + const stderrLines = new DynamicAppsLogLineDecoder(logLine("stderr")); + const process = await vm.process.spawn("node", ["/app/actor/main.mjs"], { + cwd: "/app/actor", + env: stringEnvironment({ + ...input.environment, + PORT: String(ACTOR_HTTP_PORT), + DYNAMIC_APPS_READY_NONCE: readyNonce, + }), + onStdout: (data) => { + readyBuffer = `${readyBuffer}${new TextDecoder().decode(data)}`.slice( + -4_096, + ); + if (readyBuffer.includes(readyMarker)) resolveReady(); + stdoutLines.write(data); + }, + onStderr: (data) => stderrLines.write(data), + }); + // agentOS rejects the wait when the VM is disposed before it observes the + // exit, which is the normal outcome of disposing a running VM. + const exited = vm.process.wait(process.pid).then( + (exit) => + new Error( + `Dynamic App agentOS actor process exited with ${exit.exitCode ?? 1}`, + ), + (error: unknown) => + error instanceof Error ? error : new Error(String(error)), + ); + let exitError: Error | undefined; + void exited.then((error) => { + exitError = error; + stdoutLines.end(); + stderrLines.end(); + rejectReady(error); + input.onExit?.(error); + }); + let disposePromise: Promise | undefined; + const dispose = () => { + disposePromise ??= disposeVm(input, createdVm, directory); + return disposePromise; + }; + try { + await withTimeout( + ready, + input.startTimeoutMs, + `Dynamic App agentOS actor startup exceeded ${input.startTimeoutMs}ms`, + ); + } catch (error) { + await dispose(); + throw error; } + return { + vm, + pid: process.pid, + exited, + hasExited: () => exitError !== undefined, + exitError: () => + exitError ?? new Error("Dynamic App agentOS actor is still running"), + dispose, + }; + } catch (error) { + await vm?.dispose().catch(() => {}); + await rm(directory, { recursive: true, force: true }).catch(() => {}); + throw error; + } +} + +async function disposeVm( + owner: { appId: string; release: string }, + vm: AgentOs, + directory: string, +): Promise { + const results = await Promise.allSettled([ + vm.dispose(), + rm(directory, { recursive: true, force: true }), + ]); + if (results.some((result) => result.status === "rejected")) { + emitDynamicAppsLog({ + level: "error", + source: "runtime", + message: "Dynamic App agentOS actor disposal failed", + appId: owner.appId, + release: owner.release, + }); } } +function logGuest( + owner: { appId: string; release: string }, + line: GuestLogLine, +): void { + emitDynamicAppsLog({ + level: line.stream === "stdout" ? "info" : "error", + source: "actor", + message: line.message, + appId: owner.appId, + release: owner.release, + stream: line.stream, + ...(line.truncated ? { metadata: { truncated: true } } : {}), + }); +} + function proxyResponseHeaders( input: Headers | Iterable, ): Headers { @@ -574,7 +630,6 @@ async function withTimeout( /** @internal */ export function actorWorkerEnvironment(input: { endpoint: string; - key: string; namespace: string; pool: string; }): NodeJS.ProcessEnv { @@ -595,12 +650,10 @@ export function actorWorkerEnvironment(input: { NODE_ENV: "production", PORT: String(ACTOR_HTTP_PORT), RIVETKIT_RUNTIME: "wasm", - RIVETKIT_RUNTIME_MODE: "serverless", RIVET_ENDPOINT: endpoint.toString().replace(/\/$/u, ""), RIVET_NAMESPACE: input.namespace, ...(endpointToken ? { RIVET_TOKEN: endpointToken } : {}), RIVET_POOL: input.pool, - RIVET_ENVOY_VERSION: String(actorEnvoyVersion(input.key)), ...(process.env.AGENTOS_DEBUG_HTTP_BRIDGE ? { AGENTOS_DEBUG_HTTP_BRIDGE: process.env.AGENTOS_DEBUG_HTTP_BRIDGE } : {}), @@ -617,7 +670,6 @@ function resolveWorkerEnvironment( return stringEnvironment( actorWorkerEnvironment({ endpoint: input.endpoint, - key: input.key, namespace: input.namespace, pool: input.pool, }), @@ -721,12 +773,6 @@ function loopbackExemptPorts(endpoint: string | undefined): number[] { return [Number(url.port || (url.protocol === "https:" ? 443 : 80))]; } -function actorEnvoyVersion(key: string): number { - return ( - createHash("sha256").update(key).digest().readUInt32BE(0) & 0x7fffffff || 1 - ); -} - function integerEnv( env: NodeJS.ProcessEnv, name: string, diff --git a/packages/dynamic-apps/src/actors.ts b/packages/dynamic-apps/src/actors.ts index e8b22f39f..f613fce42 100644 --- a/packages/dynamic-apps/src/actors.ts +++ b/packages/dynamic-apps/src/actors.ts @@ -1,4 +1,4 @@ -import { createHash, randomUUID, timingSafeEqual } from "node:crypto"; +import { createHash } from "node:crypto"; import type { BuildArtifactCache } from "@rivet-dev/dynamic-apps-core"; import { buildAppRelease, @@ -8,14 +8,17 @@ import { } from "@rivet-dev/dynamic-apps-core/internal"; import { type AnyActorDefinition, actor, UserError } from "rivetkit"; import { db, type RawAccess } from "rivetkit/db"; -import { getDefaultActorRuntime } from "./actor-runtime.js"; import { - configureAppNamespaceRunner, provisionAppNamespace, resolveDefaultRivetConnection, unprovisionedAppNamespace, } from "./control-plane.js"; -import { APP_CALLBACK_SECRET_HEADER } from "./runtime.js"; +import { + AppEnvoySupervisor, + EnvoySupervisorStoppedError, + type EnvoyTarget, +} from "./envoy-supervisor.js"; +import { ensureEnvoyPool } from "./runtime.js"; import type { AppReleaseInfo, AppRouteResolution, @@ -40,6 +43,12 @@ const SOURCE_CHUNK_BYTES = 512 * 1024; const MAX_SOURCE_CHUNKS = Math.ceil((4 * 1024 * 1024) / SOURCE_CHUNK_BYTES) + 2_000; const RELEASE_PATTERN = /^[a-f0-9]{64}$/; +const ENVOY_RETRY_BASE_DELAY_MS = 1_000; +const ENVOY_RETRY_MAX_DELAY_MS = 30_000; +/** Key of the singleton actor that lists apps running an envoy. */ +export const ENVOY_INDEX_KEY = ["envoys"]; +/** Largest page of app IDs the envoy index returns in one call. */ +export const ENVOY_INDEX_MAX_PAGE = 256; type AnyActorContext = { actorId: string; @@ -48,6 +57,8 @@ type AnyActorContext = { state: unknown; db: RawAccess; keepAwake(promise: Promise): Promise; + abortSignal: AbortSignal; + client(): unknown; broadcast(name: string, ...args: unknown[]): void; log: { info(value: unknown): void; @@ -60,7 +71,6 @@ export interface StoredAppRelease extends AppReleaseInfo { namespace: string; runtimeEndpoint: string; runtimePool: string; - callbackSecret: string; usesRivetKit: boolean; } @@ -74,10 +84,23 @@ export interface AppState { publicToken?: string | null; publishSequence?: number; latestPublishSequence?: number; + /** + * Highest node version reserved for this app's envoy. It only grows, so a + * node left from an earlier attempt can never pass a later connection check. + */ + envoyVersion?: number; + /** Node version that `envoyRelease` runs at; set together with it. */ + envoyActiveVersion?: number; + /** + * Release the app runs as an envoy, or null when it runs none. Undefined in + * state written before Rivet v3 envoys existed. + */ + envoyRelease?: string | null; } export interface DynamicAppsActors { dynamicAppsApp: AnyActorDefinition; + dynamicAppsEnvoyIndex: AnyActorDefinition; } interface BeginReleasePublishInput { @@ -262,6 +285,8 @@ export async function migrateAppsTables(database: RawAccess): Promise { const columns = await database.execute<{ name: string }>( "PRAGMA table_info(dynamic_apps_releases)", ); + // Unused since Rivet v3 removed serverless callbacks; kept so every database + // has the same schema. if (!columns.some((column) => column.name === "callback_secret")) { await database.execute( `ALTER TABLE dynamic_apps_releases @@ -369,7 +394,6 @@ interface ReleaseRow extends Record { namespace: string; runtime_endpoint: string; runtime_pool: string; - callback_secret: string; uses_rivetkit: number; } @@ -387,7 +411,6 @@ function releaseFromRow(row: ReleaseRow): StoredAppRelease { namespace: row.namespace, runtimeEndpoint: row.runtime_endpoint, runtimePool: row.runtime_pool, - callbackSecret: row.callback_secret ?? "", usesRivetKit: Number(row.uses_rivetkit ?? 0) === 1, }; } @@ -476,32 +499,6 @@ async function readStoredArtifact( return artifact; } -function normalizeActorCallbackPath( - request: Request, -): "/api/rivet/metadata" | "/api/rivet/start" | undefined { - if (!request.headers.get("user-agent")?.startsWith("RivetEngine/")) return; - const pathname = new URL(request.url).pathname; - if (request.method === "GET" && pathname.endsWith("/metadata")) { - return "/api/rivet/metadata"; - } - if ( - (request.method === "GET" || request.method === "POST") && - pathname.endsWith("/start") - ) { - return "/api/rivet/start"; - } - return; -} - -function validCallbackSecret(request: Request, expected: string): boolean { - const received = request.headers.get(APP_CALLBACK_SECRET_HEADER); - if (!received || !expected) return false; - return timingSafeEqual( - createHash("sha256").update(received).digest(), - createHash("sha256").update(expected).digest(), - ); -} - function actorPublicEndpoint( release: StoredAppRelease, state: AppState, @@ -625,13 +622,7 @@ async function beginReleasePublishLocked( pool: runtime.pool, usesRivetKit: input.usesRivetKit, }); - const releases = await listStoredReleases(c.db); const existing = await getStoredRelease(c.db, releaseId); - const callbackSecret = input.usesRivetKit - ? existing?.callbackSecret || - releases.find((candidate) => candidate.callbackSecret)?.callbackSecret || - randomUUID() - : ""; const sequence = (state.publishSequence ?? 0) + 1; state.publishSequence = sequence; state.latestPublishSequence = sequence; @@ -660,8 +651,8 @@ async function beginReleasePublishLocked( release_id, created_at, status, entrypoint, artifact_hash, artifact_bytes, build_error, regions_json, scaling_json, namespace, envoy_version, - runtime_endpoint, runtime_pool, callback_secret, uses_rivetkit - ) VALUES (?, ?, 'building', ?, ?, ?, NULL, ?, ?, ?, 1, ?, ?, ?, ?) + runtime_endpoint, runtime_pool, uses_rivetkit + ) VALUES (?, ?, 'building', ?, ?, ?, NULL, ?, ?, ?, 1, ?, ?, ?) ON CONFLICT(release_id) DO UPDATE SET status = 'building', entrypoint = excluded.entrypoint, artifact_hash = excluded.artifact_hash, @@ -671,7 +662,6 @@ async function beginReleasePublishLocked( namespace = excluded.namespace, runtime_endpoint = excluded.runtime_endpoint, runtime_pool = excluded.runtime_pool, - callback_secret = excluded.callback_secret, uses_rivetkit = excluded.uses_rivetkit`, releaseId, existing?.createdAt ?? input.createdAt, @@ -683,7 +673,6 @@ async function beginReleasePublishLocked( runtime.namespace, runtime.endpoint, runtime.pool, - callbackSecret, input.usesRivetKit ? 1 : 0, ); return { @@ -812,7 +801,6 @@ async function commitReleasePublishLocked( state.runnerToken = runtime.runnerToken ?? null; state.publicToken = runtime.publicToken ?? null; if (release.usesRivetKit) { - const publicEndpoint = actorPublicEndpoint(release, state); if ( runtime.endpoint.replace(/\/$/, "") !== release.runtimeEndpoint.replace(/\/$/, "") @@ -822,49 +810,56 @@ async function commitReleasePublishLocked( "the app actor Rivet endpoint does not match the deployment runtime", ); } - state.activatingRelease = release.release; + // Each activation reserves a higher node version so the Engine drains the + // previous release's envoy even if its graceful shutdown is missed. + const version = (state.envoyVersion ?? 0) + 1; + state.envoyVersion = version; try { - const metadataResponse = await getDefaultActorRuntime().request({ - key: `${release.release}:${release.artifactHash}`, - appId, - release: release.release, - loadArtifact: () => readStoredArtifact(c.db, release), - endpoint: publicEndpoint, + await ensureEnvoyPool({ + endpoint: release.runtimeEndpoint, namespace: release.namespace, pool: release.runtimePool, - request: new Request("http://dynamic-app.internal/api/rivet/metadata", { - headers: { "user-agent": "RivetEngine/prewarm" }, - }), + token: runtime.controlToken, }); - if (!metadataResponse.ok) { - throw new Error( - `Dynamic App actor metadata prewarm returned HTTP ${metadataResponse.status}`, - ); - } - await metadataResponse.arrayBuffer(); - await configureAppNamespaceRunner( - c.actorId, - { - endpoint: release.runtimeEndpoint, - namespace: release.namespace, - pool: release.runtimePool, - controlToken: runtime.controlToken, - }, - release.callbackSecret, + // Registering first is safe because the recovery loop only wakes the + // app, which then runs whatever release state names. + await envoyIndex(c).register(appId); + await appEnvoy(c).supervisor.activate( + envoyTarget(c, release, state, version, runtime.controlToken), + { waitForConnection: true }, ); } catch (error) { - state.activatingRelease = null; c.log.error({ - msg: "Dynamic App actor runner configuration failed", + msg: "Dynamic App envoy activation failed", release: release.release, error: error instanceof Error ? error.stack : String(error), }); + // Without a previous envoy, nothing should hold the actor awake. + if (!state.envoyRelease) await stopAppEnvoy(c); throw error; } + state.envoyRelease = release.release; + state.envoyActiveVersion = version; + } + const hadEnvoy = !release.usesRivetKit && Boolean(state.envoyRelease); + if (!release.usesRivetKit) { + await stopAppEnvoy(c); + state.envoyRelease = null; } state.activeRelease = release.release; - state.activatingRelease = null; state.revision += 1; + if (hadEnvoy) { + // A stale index entry is harmless: waking an app without an envoy does + // nothing. So a failed cleanup must not fail the deploy. + await envoyIndex(c) + .unregister(appId) + .catch((error: unknown) => + c.log.error({ + msg: "failed to remove app from the envoy index", + error: error instanceof Error ? error.message : String(error), + }), + ); + } c.broadcast("releaseActivated", { revision: state.revision, release: release.release, @@ -910,53 +905,192 @@ function deploymentForRelease( }; } -export function createAppsActors( - options: { artifactCache?: BuildArtifactCache } = {}, -): DynamicAppsActors { - const forwardActorRequest = async ( - c: AnyActorContext, - request: Request, - ): Promise => { - const callbackPath = normalizeActorCallbackPath(request); - if (!callbackPath) return new Response("Not Found", { status: 404 }); - const state = c.state as AppState; - const routedRelease = state.activatingRelease ?? state.activeRelease; - const release = routedRelease - ? await getStoredRelease(c.db, routedRelease) - : undefined; - if (!release || release.status !== "ready" || !release.usesRivetKit) { - return new Response("Dynamic App has no active actor registry", { - status: 503, - }); - } - if (!validCallbackSecret(request, release.callbackSecret)) { - return new Response("Unauthorized", { status: 401 }); - } - try { - return await getDefaultActorRuntime().request({ - key: `${release.release}:${release.artifactHash}`, - appId: c.key[0], - release: release.release, - loadArtifact: () => readStoredArtifact(c.db, release), - endpoint: actorPublicEndpoint(release, state), - namespace: release.namespace, - pool: release.runtimePool, - request: forwardActorCallbackRequest(request, callbackPath), - }); - } catch (error) { - c.log.error({ - msg: "Dynamic App actor callback failed", - release: release.release, - error: error instanceof Error ? error.stack : String(error), - }); - throw error; +interface AppEnvoy { + supervisor: AppEnvoySupervisor; + /** Lets the owning actor sleep again once it no longer runs an envoy. */ + release(): void; +} + +const appEnvoys = new Map(); + +/** + * Returns the app actor's envoy supervisor, creating it on first use. While + * the supervisor exists it holds the actor awake, and when the actor begins to + * stop it drains the envoy inside the actor's shutdown grace. + */ +function appEnvoy(c: AnyActorContext): AppEnvoy { + const existing = appEnvoys.get(c.actorId); + if (existing) return existing; + const supervisor = new AppEnvoySupervisor(); + let release = () => {}; + const released = new Promise((resolve) => { + release = resolve; + }); + const entry: AppEnvoy = { supervisor, release }; + appEnvoys.set(c.actorId, entry); + const stopping = new Promise((resolve) => { + if (c.abortSignal.aborted) resolve(); + else + c.abortSignal.addEventListener("abort", () => resolve(), { once: true }); + }); + void c.keepAwake( + Promise.race([released, stopping.then(() => supervisor.stop())]).finally( + () => { + if (appEnvoys.get(c.actorId) === entry) appEnvoys.delete(c.actorId); + }, + ), + ); + return entry; +} + +/** Drains the app's envoy, if any, and lets the actor sleep again. */ +async function stopAppEnvoy(c: AnyActorContext): Promise { + const entry = appEnvoys.get(c.actorId); + if (!entry) return; + appEnvoys.delete(c.actorId); + try { + await entry.supervisor.stop(); + } finally { + entry.release(); + } +} + +function envoyTarget( + c: AnyActorContext, + release: StoredAppRelease, + state: AppState, + version: number, + controlToken?: string, +): EnvoyTarget { + const appId = c.key[0]; + if (!appId) + fail("dynamic_apps_invalid_app_id", "application actor key is missing"); + return { + appId, + release: release.release, + version, + endpoint: actorPublicEndpoint(release, state), + namespace: release.namespace, + pool: release.runtimePool, + controlToken, + loadArtifact: () => readStoredArtifact(c.db, release), + }; +} + +/** + * Starts the app's envoy if this actor runs one and is not already running + * it. Called whenever the actor wakes, so an app whose host process went away + * serves actors again as soon as anything wakes its app actor. + */ +function ensureActiveEnvoy(c: AnyActorContext): void { + if (appEnvoys.has(c.actorId)) return; + const state = c.state as AppState; + if (state.envoyRelease === undefined) { + void c.keepAwake(resolveLegacyEnvoyRelease(c)); + return; + } + if (!state.envoyRelease) return; + const entry = appEnvoy(c); + void c.keepAwake( + (async () => { + for (let attempt = 0; ; attempt += 1) { + // Stop once the actor stops or a later activation replaced this envoy. + if (c.abortSignal.aborted || appEnvoys.get(c.actorId) !== entry) { + return; + } + // The running version, never a reservation an activation still holds. + const releaseId = state.envoyRelease; + const version = state.envoyActiveVersion; + if (!releaseId || version === undefined) { + await stopAppEnvoy(c); + return; + } + try { + const release = await getStoredRelease(c.db, releaseId); + if (!release?.usesRivetKit || release.status !== "ready") { + throw new Error( + `envoy release ${releaseId} is not a ready RivetKit release`, + ); + } + // Nothing else serves the pool yet, so the guest's own startup is + // enough; waiting for the Engine would only delay recovery. + await entry.supervisor.activate( + envoyTarget(c, release, state, version), + { waitForConnection: false }, + ); + return; + } catch (error) { + if (error instanceof EnvoySupervisorStoppedError) return; + const delay = Math.min( + ENVOY_RETRY_BASE_DELAY_MS * 2 ** attempt, + ENVOY_RETRY_MAX_DELAY_MS, + ); + c.log.error({ + msg: "Dynamic App envoy failed to start; retrying", + release: releaseId, + delayMs: delay, + error: error instanceof Error ? error.stack : String(error), + }); + await abortableDelay(delay, c.abortSignal); + } + } + })(), + ); +} + +/** + * Settles `envoyRelease` for state written before Rivet v3 envoys. Their + * artifacts were built for serverless callbacks and cannot run as an envoy, so + * a RivetKit app must be redeployed; any other app simply runs no envoy. + */ +async function resolveLegacyEnvoyRelease(c: AnyActorContext): Promise { + const state = c.state as AppState; + const release = state.activeRelease + ? await getStoredRelease(c.db, state.activeRelease) + : undefined; + if (release?.usesRivetKit) { + c.log.error({ + msg: "Dynamic App release was built before Rivet v3 envoys; redeploy the app to run its actors", + release: release.release, + }); + return; + } + state.envoyRelease = null; +} + +function abortableDelay(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve) => { + const timer = setTimeout(done, ms); + function done() { + clearTimeout(timer); + signal.removeEventListener("abort", done); + resolve(); } + signal.addEventListener("abort", done, { once: true }); + }); +} + +interface EnvoyIndexHandle { + register(appId: string): Promise; + unregister(appId: string): Promise; +} + +function envoyIndex(c: AnyActorContext): EnvoyIndexHandle { + const client = c.client() as { + dynamicAppsEnvoyIndex: { + getOrCreate(key: string[]): EnvoyIndexHandle; + }; }; + return client.dynamicAppsEnvoyIndex.getOrCreate(ENVOY_INDEX_KEY); +} +export function createAppsActors( + options: { artifactCache?: BuildArtifactCache } = {}, +): DynamicAppsActors { const dynamicAppsApp = actor({ options: { actionTimeout: 16 * 60_000 }, db: db({ onMigrate: migrateAppsTables }), - onRequest: forwardActorRequest, + onWake: (c: AnyActorContext) => ensureActiveEnvoy(c), createState: (): AppState => ({ activeRelease: null, namespace: null, @@ -966,8 +1100,16 @@ export function createAppsActors( publicToken: null, publishSequence: 0, latestPublishSequence: 0, + envoyRelease: null, }), actions: { + /** + * Wakes the app so it restarts its envoy after its host process went + * away. The Engine only notices a lost actor when something touches it. + */ + ensureEnvoy: (c: AnyActorContext) => { + ensureActiveEnvoy(c); + }, beginReleasePublish: ( c: AnyActorContext, input: BeginReleasePublishInput, @@ -1112,7 +1254,7 @@ export function createAppsActors( usesRivetKit: release.usesRivetKit, ...(release.usesRivetKit ? { - serverlessEndpoint: actorPublicEndpoint(release, state), + actorEndpoint: actorPublicEndpoint(release, state), runtimePool: release.runtimePool, } : {}), @@ -1210,27 +1352,40 @@ export function createAppsActors( }, }, }); - return { dynamicAppsApp }; + const dynamicAppsEnvoyIndex = actor({ + createState: (): EnvoyIndexState => ({ apps: {} }), + actions: { + register: (c: { state: EnvoyIndexState }, appId: string) => { + c.state.apps[appId] = true; + }, + unregister: (c: { state: EnvoyIndexState }, appId: string) => { + delete c.state.apps[appId]; + }, + /** One page of app IDs after `after`, in sorted order. */ + list: ( + c: { state: EnvoyIndexState }, + after: string | null, + limit: number, + ): { appIds: string[]; next: string | null } => { + const pageSize = Math.min( + Math.max(1, Math.floor(limit)), + ENVOY_INDEX_MAX_PAGE, + ); + const appIds = Object.keys(c.state.apps) + .filter((appId) => after === null || appId > after) + .sort() + .slice(0, pageSize); + return { + appIds, + next: appIds.length === pageSize ? (appIds.at(-1) ?? null) : null, + }; + }, + }, + }); + return { dynamicAppsApp, dynamicAppsEnvoyIndex }; } -/** @internal Preserves callback streaming until runtime admission. */ -export function forwardActorCallbackRequest( - request: Request, - callbackPath: string, -): Request { - const url = new URL(request.url); - url.pathname = callbackPath; - const headers = new Headers(request.headers); - headers.delete(APP_CALLBACK_SECRET_HEADER); - const body = - request.method === "GET" || request.method === "HEAD" - ? undefined - : request.body; - return new Request(url, { - method: request.method, - headers, - body, - signal: request.signal, - ...(body ? { duplex: "half" } : {}), - } as RequestInit & { duplex?: "half" }); +/** Apps whose active release runs an envoy, so hosts can wake them after a crash. */ +interface EnvoyIndexState { + apps: Record; } diff --git a/packages/dynamic-apps/src/control-plane.ts b/packages/dynamic-apps/src/control-plane.ts index bd214b37a..643d5017a 100644 --- a/packages/dynamic-apps/src/control-plane.ts +++ b/packages/dynamic-apps/src/control-plane.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { DynamicAppsError } from "@rivet-dev/dynamic-apps-core/internal"; import { controlFetch } from "./control-request.js"; -import { appRunnerPool, ensureServerlessRunnerConfig } from "./runtime.js"; +import { appRunnerPool } from "./runtime.js"; const DEFAULT_ENDPOINT = "http://localhost:6420"; const DEFAULT_CLOUD_ENDPOINT = "https://cloud-api.rivet.dev"; @@ -281,10 +281,7 @@ export async function provisionAppNamespace( { method: "POST", headers, - body: JSON.stringify({ - name: namespace, - display_name: `Dynamic App ${appId}`, - }), + body: JSON.stringify({ name: namespace }), }, ); if (!response.ok && !(await lookup())) { @@ -316,76 +313,3 @@ export function unprovisionedAppNamespace( controlToken: connection.token, }; } - -function serverlessAppCallback( - appActorId: string, - connection: ResolvedRivetConnection, -): { url: string; token?: string } { - const configured = process.env.DYNAMIC_APPS_CALLBACK_URL; - if (configured) { - return { url: new URL("/api/rivet", configured).toString() }; - } - - const publicEndpoint = process.env.RIVET_PUBLIC_ENDPOINT; - const callbackConnection = publicEndpoint - ? resolveRivetConnection(publicEndpoint) - : connection; - return { - url: new URL( - `/gateway/${encodeURIComponent(appActorId)}/request/.agentos/apps/rivet`, - callbackConnection.endpoint, - ).toString(), - ...(callbackConnection.token ? { token: callbackConnection.token } : {}), - }; -} - -function resolveRivetConnection(rawEndpoint: string): ResolvedRivetConnection { - const url = new URL(rawEndpoint); - const namespace = url.username - ? decodeURIComponent(url.username) - : (process.env.RIVET_NAMESPACE ?? "default"); - const token = url.password ? decodeURIComponent(url.password) : undefined; - url.username = ""; - url.password = ""; - return { - endpoint: url.toString().replace(/\/$/, ""), - namespace, - ...(token ? { token } : {}), - }; -} - -/** Configure the nested actor pool only after its release is ready. */ -export async function configureAppNamespaceRunner( - appActorId: string, - runtime: { - endpoint: string; - namespace: string; - pool: string; - controlToken?: string; - }, - callbackSecret: string, - callbackConnection = resolveDefaultRivetConnection(), -): Promise { - try { - const callback = serverlessAppCallback(appActorId, callbackConnection); - await ensureServerlessRunnerConfig({ - endpoint: runtime.endpoint, - namespace: runtime.namespace, - url: callback.url, - pool: runtime.pool, - token: runtime.controlToken, - callbackToken: callback.token, - callbackSecret, - }); - } catch (error) { - throw new DynamicAppsError( - "dynamic_apps_runner_config_failed", - `Rivet runner configuration failed for namespace ${runtime.namespace} and pool ${runtime.pool}`, - { - namespace: runtime.namespace, - pool: runtime.pool, - error: error instanceof Error ? error.message : String(error), - }, - ); - } -} diff --git a/packages/dynamic-apps/src/control-request.ts b/packages/dynamic-apps/src/control-request.ts index 03cb2132b..af809914c 100644 --- a/packages/dynamic-apps/src/control-request.ts +++ b/packages/dynamic-apps/src/control-request.ts @@ -1,13 +1,51 @@ const CONTROL_TIMEOUT_MS = 15_000; -const MAX_CONTROL_ATTEMPTS = 4; +const MAX_CONTROL_ATTEMPTS = 6; const BASE_RETRY_DELAY_MS = 50; -const MAX_RETRY_DELAY_MS = 1_000; +const MAX_RETRY_DELAY_MS = 2_000; +const MAX_REFUSAL_BODY_BYTES = 4 * 1024; function retryableStatus(status: number): boolean { return status === 409 || status === 429 || status >= 500; } -function retryDelay(response: Response | undefined, attempt: number): number { +/** + * The retry hint of a structured Engine overload refusal, or undefined when the + * response is not one. Rivet v3 sheds load at admission with a typed + * `overloaded` error that some routes return as HTTP 400, so the status code + * alone does not say whether a request may be retried. + */ +async function overloadRetryAfterMs( + response: Response, +): Promise { + if (response.ok || !response.body) return undefined; + const length = Number(response.headers.get("content-length") ?? 0); + if (length > MAX_REFUSAL_BODY_BYTES) return undefined; + try { + const text = await response.clone().text(); + if (text.length > MAX_REFUSAL_BODY_BYTES) return undefined; + const body = JSON.parse(text) as { + code?: unknown; + metadata?: { retry_after_ms?: unknown }; + }; + if (body.code !== "overloaded") return undefined; + const retryAfter = body.metadata?.retry_after_ms; + return typeof retryAfter === "number" && retryAfter >= 0 ? retryAfter : 0; + } catch { + return undefined; + } +} + +function retryDelay( + response: Response | undefined, + attempt: number, + overloadRetryAfter: number | undefined, +): number { + if (overloadRetryAfter !== undefined) { + return Math.min( + Math.max(overloadRetryAfter, BASE_RETRY_DELAY_MS), + MAX_RETRY_DELAY_MS, + ); + } const retryAfter = response?.headers.get("retry-after"); if (retryAfter) { const seconds = Number(retryAfter); @@ -35,13 +73,16 @@ export async function controlFetch( for (let attempt = 1; attempt <= MAX_CONTROL_ATTEMPTS; attempt += 1) { let response: Response | undefined; + let overloadRetryAfter: number | undefined; try { response = await fetch(input, { ...init, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), }); + overloadRetryAfter = await overloadRetryAfterMs(response); if ( - !retryableStatus(response.status) || + (!retryableStatus(response.status) && + overloadRetryAfter === undefined) || attempt === MAX_CONTROL_ATTEMPTS ) { return response; @@ -52,12 +93,12 @@ export async function controlFetch( throw error; } - if (response?.body) await response.body.cancel(); - const delay = retryDelay(response, attempt); + const delay = retryDelay(response, attempt, overloadRetryAfter); if (Date.now() + delay >= deadline) { if (response) return response; throw lastError; } + if (response?.body) await response.body.cancel(); await new Promise((resolve) => setTimeout(resolve, delay)); } diff --git a/packages/dynamic-apps/src/envoy-reconciler.ts b/packages/dynamic-apps/src/envoy-reconciler.ts new file mode 100644 index 000000000..1aee9dcb1 --- /dev/null +++ b/packages/dynamic-apps/src/envoy-reconciler.ts @@ -0,0 +1,117 @@ +import { createClient } from "rivetkit/client"; +import { ENVOY_INDEX_KEY, ENVOY_INDEX_MAX_PAGE } from "./actors.js"; +import { emitDynamicAppsLog } from "./logging.js"; + +// Bounds how long a RivetKit app stays offline after its host process dies +// without a graceful shutdown. +const RECONCILE_INTERVAL_MS = 60_000; +const RECONCILE_CONCURRENCY = 16; +// One unreachable app must not hold up every other app's recovery. +const ENSURE_TIMEOUT_MS = 30_000; + +interface ReconcilerClient { + dynamicAppsEnvoyIndex: { + getOrCreate(key: string[]): { + list( + after: string | null, + limit: number, + ): Promise<{ appIds: string[]; next: string | null }>; + }; + }; + dynamicAppsApp: { + getOrCreate(key: string[]): { ensureEnvoy(): Promise }; + }; +} + +let timer: ReturnType | undefined; +let running = false; + +/** + * Periodically wakes every app whose active release runs an envoy. + * + * This poll is a deliberate last resort. When a host process dies without a + * graceful shutdown, the Engine only notices that the app actors it ran are + * gone once something touches them, and nothing else touches an app that + * serves only actor traffic. Every host runs this loop, so recovery does not + * depend on any single host surviving. Each pass costs one call per app. + */ +export function startEnvoyReconciler(): void { + if (timer) return; + const client = createClient() as unknown as ReconcilerClient; + const tick = () => void reconcile(client); + timer = setInterval(tick, RECONCILE_INTERVAL_MS); + timer.unref?.(); + tick(); +} + +/** @internal */ +export function stopEnvoyReconcilerForTest(): void { + if (timer) clearInterval(timer); + timer = undefined; +} + +async function reconcile(client: ReconcilerClient): Promise { + if (running) return; + running = true; + try { + const index = client.dynamicAppsEnvoyIndex.getOrCreate(ENVOY_INDEX_KEY); + let after: string | null = null; + let total = 0; + let failed = 0; + do { + const page = await index.list(after, ENVOY_INDEX_MAX_PAGE); + total += page.appIds.length; + for ( + let start = 0; + start < page.appIds.length; + start += RECONCILE_CONCURRENCY + ) { + const batch = page.appIds.slice(start, start + RECONCILE_CONCURRENCY); + const results = await Promise.allSettled( + batch.map((appId) => + withTimeout( + client.dynamicAppsApp.getOrCreate([appId]).ensureEnvoy(), + ENSURE_TIMEOUT_MS, + ), + ), + ); + failed += results.filter( + (result) => result.status === "rejected", + ).length; + } + after = page.next; + } while (after !== null); + if (failed > 0) { + emitDynamicAppsLog({ + level: "error", + source: "runtime", + message: `Dynamic Apps envoy reconciliation could not reach ${failed} of ${total} apps; retrying next pass`, + }); + } + } catch (error) { + emitDynamicAppsLog({ + level: "error", + source: "runtime", + message: `Dynamic Apps envoy reconciliation failed: ${error instanceof Error ? error.message : String(error)}`, + }); + } finally { + running = false; + } +} + +async function withTimeout(promise: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`timed out after ${ms}ms`)), + ms, + ); + }), + ]); + } finally { + if (timer) clearTimeout(timer); + } +} diff --git a/packages/dynamic-apps/src/envoy-supervisor.ts b/packages/dynamic-apps/src/envoy-supervisor.ts new file mode 100644 index 000000000..fff0e5229 --- /dev/null +++ b/packages/dynamic-apps/src/envoy-supervisor.ts @@ -0,0 +1,340 @@ +import { ENVOY_SHUTDOWN_PATH } from "@rivet-dev/dynamic-apps-core/internal"; +import { + ACTOR_HTTP_PORT, + actorWorkerEnvironment, + type LaunchedActorVm, + launchActorVm, +} from "./actor-runtime.js"; +import { emitDynamicAppsLog } from "./logging.js"; +import { poolHasConnectedNode } from "./runtime.js"; + +const HEAP_LIMIT_MB = 256; +const START_TIMEOUT_MS = 60_000; +const CONNECT_TIMEOUT_MS = 60_000; +const CONNECT_POLL_MS = 250; +// Stays inside the Engine's default 30 second actor stop threshold, which bounds +// the owning actor's shutdown grace. +const SHUTDOWN_TIMEOUT_MS = 20_000; +const STOP_TIMEOUT_MS = 25_000; +const RESTART_BASE_DELAY_MS = 1_000; +const RESTART_MAX_DELAY_MS = 30_000; +// A guest that stayed up this long crashed for a new reason, so its restart +// starts from the base delay again. +const STABLE_UPTIME_MS = 60_000; + +/** Everything needed to run one release of an app as an envoy. */ +export interface EnvoyTarget { + appId: string; + release: string; + /** Node version; higher versions drain lower ones in the same pool. */ + version: number; + /** Endpoint the guest connects with, carrying its namespace and token. */ + endpoint: string; + namespace: string; + pool: string; + /** Token for reading the pool's nodes during activation. */ + controlToken?: string; + loadArtifact(): Promise; +} + +/** The supervisor was stopped; it will not run another envoy. */ +export class EnvoySupervisorStoppedError extends Error { + constructor() { + super("app envoy supervisor is stopped"); + } +} + +interface RunningEnvoy { + target: EnvoyTarget; + launched: LaunchedActorVm; + startedAt: number; +} + +/** + * Keeps one app's active release running as an envoy in an agentOS VM. + * + * The owning app actor creates one supervisor while it runs and stops it when + * the actor stops. A guest that exits on its own is restarted with backoff, so + * the app keeps hosting actors without any request having to arrive first. + */ +export class AppEnvoySupervisor { + #current?: RunningEnvoy; + #target?: EnvoyTarget; + #stopped = false; + #restartAttempt = 0; + #restartTimer?: ReturnType; + #transition: Promise = Promise.resolve(); + + /** + * Runs `target`, replacing any other release, then drains the previous + * release's envoy. With `waitForConnection`, resolves only once the new + * envoy has connected to the Engine and rejects, leaving the previous + * release serving, if it never does. A target older than the running one is + * ignored, so a late wake cannot roll back a newer activation. + */ + activate( + target: EnvoyTarget, + options: { waitForConnection: boolean }, + ): Promise { + return this.#serialize(async () => { + this.#throwIfStopped(); + const current = this.#target; + // Each version belongs to one release, so an older or conflicting + // target is a stale request. + if ( + current && + (target.version < current.version || + (target.version === current.version && + target.release !== current.release)) + ) { + return; + } + if ( + this.#current && + current?.release === target.release && + current.version === target.version + ) { + return; + } + const launched = await this.#launch(target); + try { + this.#throwIfStopped(); + if (options.waitForConnection) { + await this.#waitForConnectedNode(target, launched); + } + } catch (error) { + await launched.dispose(); + throw error; + } + const previous = this.#current; + this.#target = target; + this.#current = { target, launched, startedAt: Date.now() }; + this.#restartAttempt = 0; + if (previous) await drainEnvoy(previous); + // The guest may have exited before it became current, when its exit was + // still ignored. + if (launched.hasExited()) this.#onExit(launched, launched.exitError()); + }); + } + + /** + * Drains the running envoy and stops restarting it, within one deadline + * that fits the owning actor's stop grace. Work still queued past the + * deadline sees the stop and disposes what it launched. Safe to call + * repeatedly. + */ + async stop(): Promise { + this.#stopped = true; + if (this.#restartTimer) clearTimeout(this.#restartTimer); + this.#restartTimer = undefined; + const drained = this.#serialize(async () => { + const current = this.#current; + this.#current = undefined; + if (current) await drainEnvoy(current); + }); + try { + await withDeadline(drained, STOP_TIMEOUT_MS); + } catch (error) { + const current = this.#current; + this.#current = undefined; + emitDynamicAppsLog({ + level: "error", + source: "actor", + message: `Dynamic App envoy did not stop in time; disposing it: ${error instanceof Error ? error.message : String(error)}`, + appId: this.#target?.appId, + release: this.#target?.release, + }); + await current?.launched.dispose(); + } + } + + #throwIfStopped(): void { + if (this.#stopped) throw new EnvoySupervisorStoppedError(); + } + + #serialize(run: () => Promise): Promise { + const next = this.#transition.then(run); + this.#transition = next.catch(() => {}); + return next; + } + + async #launch(target: EnvoyTarget): Promise { + const launched = await launchActorVm({ + appId: target.appId, + release: target.release, + artifact: await target.loadArtifact(), + environment: envoyEnvironment(target), + heapLimitMb: HEAP_LIMIT_MB, + startTimeoutMs: START_TIMEOUT_MS, + }); + void launched.exited.then((error) => this.#onExit(launched, error)); + return launched; + } + + /** + * Waits until the Engine lists `target`'s node as connected. Fails early if + * the guest exits or the supervisor stops, since neither can lead to a + * connection. + */ + async #waitForConnectedNode( + target: EnvoyTarget, + launched: LaunchedActorVm, + ): Promise { + const deadline = Date.now() + CONNECT_TIMEOUT_MS; + let lastError: unknown; + for (;;) { + this.#throwIfStopped(); + if (launched.hasExited()) { + throw new Error( + `Dynamic App envoy for release ${target.release} exited before connecting: ${launched.exitError().message}`, + ); + } + try { + const connected = await poolHasConnectedNode({ + endpoint: new URL(target.endpoint).origin, + namespace: target.namespace, + pool: target.pool, + token: target.controlToken, + version: target.version, + }); + if (connected) return; + lastError = undefined; + } catch (error) { + // A failed listing says nothing about the envoy; keep waiting. + lastError = error; + } + if (Date.now() >= deadline) { + const listing = lastError + ? ` The last node listing failed: ${lastError instanceof Error ? lastError.message : String(lastError)}.` + : ""; + throw new Error( + `Dynamic App envoy for release ${target.release} did not connect to the Engine within ${CONNECT_TIMEOUT_MS}ms. Check that RIVET_PUBLIC_ENDPOINT, or the namespace token on Rivet Cloud, carries a token the Engine accepts for envoys.${listing}`, + ); + } + await new Promise((resolve) => setTimeout(resolve, CONNECT_POLL_MS)); + } + } + + #onExit(launched: LaunchedActorVm, error: Error): void { + const current = this.#current; + if (this.#stopped || current?.launched !== launched) return; + this.#current = undefined; + void launched.dispose(); + if (Date.now() - current.startedAt >= STABLE_UPTIME_MS) { + this.#restartAttempt = 0; + } + this.#scheduleRestart(error); + } + + #scheduleRestart(error: Error): void { + if (this.#stopped) return; + const delay = Math.min( + RESTART_BASE_DELAY_MS * 2 ** this.#restartAttempt, + RESTART_MAX_DELAY_MS, + ); + this.#restartAttempt += 1; + const target = this.#target; + emitDynamicAppsLog({ + level: "error", + source: "actor", + message: `Dynamic App envoy stopped unexpectedly; restarting in ${delay}ms: ${error.message}`, + appId: target?.appId, + release: target?.release, + }); + this.#restartTimer = setTimeout(() => { + this.#restartTimer = undefined; + void this.#restart(); + }, delay); + this.#restartTimer.unref?.(); + } + + #restart(): Promise { + return this.#serialize(async () => { + const target = this.#target; + if (this.#stopped || this.#current || !target) return; + let launched: LaunchedActorVm; + try { + // A restart needs no connection check: no other release waits on it. + launched = await this.#launch(target); + } catch (error) { + this.#scheduleRestart( + error instanceof Error ? error : new Error(String(error)), + ); + return; + } + if (this.#stopped) { + await launched.dispose(); + return; + } + this.#current = { target, launched, startedAt: Date.now() }; + if (launched.hasExited()) this.#onExit(launched, launched.exitError()); + }); + } +} + +/** Environment for a guest that runs the release's registry as an envoy. */ +function envoyEnvironment(target: EnvoyTarget): Record { + const environment = actorWorkerEnvironment({ + endpoint: target.endpoint, + namespace: target.namespace, + pool: target.pool, + }); + const strings: Record = {}; + for (const [name, value] of Object.entries(environment)) { + if (typeof value === "string") strings[name] = value; + } + return { + ...strings, + DYNAMIC_APPS_RUNNER_MODE: "envoy", + RIVET_NODE_VERSION: String(target.version), + }; +} + +/** + * Asks the guest registry to stop its actors so the Engine reallocates them, + * then disposes the VM. A guest that does not finish in time is disposed + * anyway; the Engine then recovers its actors after the node lost threshold. + */ +async function drainEnvoy(envoy: RunningEnvoy): Promise { + const { launched, target } = envoy; + try { + // The guest exits once its registry has drained, which can race the + // reply, so its exit is the drain signal. + void launched.vm + .fetch( + ACTOR_HTTP_PORT, + new Request(`http://dynamic-app.internal${ENVOY_SHUTDOWN_PATH}`, { + method: "POST", + }), + ) + .catch(() => {}); + await withDeadline(launched.exited, SHUTDOWN_TIMEOUT_MS); + } catch (error) { + emitDynamicAppsLog({ + level: "error", + source: "actor", + message: `Dynamic App envoy did not drain cleanly: ${error instanceof Error ? error.message : String(error)}`, + appId: target.appId, + release: target.release, + }); + } finally { + await launched.dispose(); + } +} + +async function withDeadline(promise: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`timed out after ${ms}ms`)), + ms, + ); + }), + ]); + } finally { + if (timer) clearTimeout(timer); + } +} diff --git a/packages/dynamic-apps/src/index.ts b/packages/dynamic-apps/src/index.ts index 7899db6d7..f714787f0 100644 --- a/packages/dynamic-apps/src/index.ts +++ b/packages/dynamic-apps/src/index.ts @@ -10,6 +10,7 @@ export { type DynamicAppsLogSource, setDynamicAppsLogHandler, } from "./logging.js"; +export { startDynamicAppsHost } from "./registry.js"; export { appsRouter } from "./router.js"; export { rivetActorsSkill, webServerSkill } from "./skills.js"; export { setDynamicAppsVmOptions } from "./vm-options.js"; diff --git a/packages/dynamic-apps/src/registry.ts b/packages/dynamic-apps/src/registry.ts index 24fe84979..bafc855a8 100644 --- a/packages/dynamic-apps/src/registry.ts +++ b/packages/dynamic-apps/src/registry.ts @@ -2,6 +2,10 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { setup } from "rivetkit"; import { createAppsActors } from "./actors.js"; +import { + startEnvoyReconciler, + stopEnvoyReconcilerForTest, +} from "./envoy-reconciler.js"; const artifactCacheDirectory = process.env.DYNAMIC_APPS_E2E_ARTIFACT_CACHE; @@ -44,25 +48,36 @@ export const privateAppsRegistry = setup({ let startPromise: Promise | undefined; -export function isServerlessRuntime(): boolean { - return process.env.RIVETKIT_RUNTIME_MODE === "serverless"; -} - -/** Ensure the private app-state actor is registered with a local/envoy Engine. */ +/** + * Registers the private app-state actors with the Engine and starts the loop + * that restarts app envoys after a host process dies. + */ export async function ensurePrivateAppsRegistry(): Promise { - if (isServerlessRuntime()) return; - startPromise ??= privateAppsRegistry.startAndWait().catch((error) => { - startPromise = undefined; - throw error; - }); + startPromise ??= privateAppsRegistry.startAndWait().then( + () => startEnvoyReconciler(), + (error) => { + startPromise = undefined; + throw error; + }, + ); await startPromise; } -/** Handle the host's explicit root /api/rivet callback routes. */ +/** + * Starts this host's part of Dynamic Apps: the private actors that run each + * app's envoy and the loop that restarts envoys after a host dies. Call it once + * when the host process boots. Without it a host joins only after its first + * request, so apps that serve only actor traffic can stay offline after every + * host restarts. + */ +export async function startDynamicAppsHost(): Promise { + await ensurePrivateAppsRegistry(); +} + +/** Handle the host's explicit root /api/rivet routes. */ export async function handlePrivateAppsRegistry( request: Request, ): Promise { - if (isServerlessRuntime()) return privateAppsRegistry.handler(request); await ensurePrivateAppsRegistry(); const path = new URL(request.url).pathname.replace(/\/+$/, "") || "/"; if (request.method === "GET" && path === "/api/rivet/health") { @@ -79,6 +94,7 @@ export async function handlePrivateAppsRegistry( /** @internal */ export async function shutdownPrivateAppsRegistryForTest(): Promise { + stopEnvoyReconcilerForTest(); await privateAppsRegistry.shutdown(); startPromise = undefined; } diff --git a/packages/dynamic-apps/src/release-store.ts b/packages/dynamic-apps/src/release-store.ts index 721ae64d9..023b8df84 100644 --- a/packages/dynamic-apps/src/release-store.ts +++ b/packages/dynamic-apps/src/release-store.ts @@ -140,12 +140,16 @@ export function createRivetReleaseStore( const drivers = new Map(); const getClient = () => (client ??= createClient() as unknown as ReleaseStoreClient); + // An injected client already reaches a running host registry. + const ensureHostRegistry = clientInput + ? async () => {} + : ensurePrivateAppsRegistry; const publishRelease = async ( input: PublishReleaseInput, options?: RivetDeployOptions, ): Promise => { - await ensurePrivateAppsRegistry(); + await ensureHostRegistry(); const group = getClient().dynamicAppsApp; const driver = drivers.get(input.appId); let handle: AppReleaseHandle; @@ -274,14 +278,13 @@ export function createRivetReleaseStore( maxRequestBytes: resolution.maxRequestBytes, maxResponseBytes: resolution.maxResponseBytes, ...(resolution.usesRivetKit && - resolution.serverlessEndpoint && + resolution.actorEndpoint && resolution.runtimePool ? { server: { environment: definedEnvironment( actorWorkerEnvironment({ - endpoint: resolution.serverlessEndpoint, - key: `${resolution.release}:${resolution.artifactHash}`, + endpoint: resolution.actorEndpoint, namespace: resolution.namespace, pool: resolution.runtimePool, }), @@ -296,7 +299,7 @@ export function createRivetReleaseStore( appId: string, invalidate: ReleaseInvalidation, ): Promise => { - await ensurePrivateAppsRegistry(); + await ensureHostRegistry(); const existing = drivers.get(appId); if (existing) { await existing.ready; diff --git a/packages/dynamic-apps/src/runtime.ts b/packages/dynamic-apps/src/runtime.ts index 3e0aeb5c8..94cc5b5e5 100644 --- a/packages/dynamic-apps/src/runtime.ts +++ b/packages/dynamic-apps/src/runtime.ts @@ -2,11 +2,9 @@ import { createHash } from "node:crypto"; import { controlFetch } from "./control-request.js"; const MAX_ENGINE_RESPONSE_BYTES = 1024 * 1024; -const MAX_ENGINE_DATACENTERS = 128; +const MAX_POOL_NODE_PAGES = 64; -export const APP_CALLBACK_SECRET_HEADER = "x-agentos-app-callback-token"; - -/** Stable compatibility pool retained in deployApp's result. */ +/** Stable node pool that hosts one app's actors. */ export function appRunnerPool(appId: string): string { const suffix = createHash("sha256").update(appId).digest("hex").slice(0, 16); return `dynamic-apps-${suffix}`; @@ -42,91 +40,83 @@ function engineUrl(endpoint: string, path: string[], namespace: string): URL { return url; } -/** Point an app namespace's stable pool at its authenticated callback URL. */ -export async function ensureServerlessRunnerConfig(input: { +interface EngineControl { endpoint: string; namespace: string; - url: string; - pool: string; token?: string; - callbackToken?: string; - callbackSecret: string; -}): Promise { - const headers = { +} + +function controlHeaders(token?: string): Record { + return { accept: "application/json", "content-type": "application/json", - ...(input.token ? { authorization: `Bearer ${input.token}` } : {}), - }; - const datacentersResponse = await controlFetch( - engineUrl(input.endpoint, ["datacenters"], input.namespace), - { headers }, - ); - const datacentersText = await readBoundedText(datacentersResponse); - if (!datacentersResponse.ok) { - throw new Error( - `Rivet datacenter lookup failed with HTTP ${datacentersResponse.status}: ${datacentersText}`, - ); - } - const parsed = JSON.parse(datacentersText) as { - datacenters?: Array<{ name?: unknown }>; + ...(token ? { authorization: `Bearer ${token}` } : {}), }; - if ( - !Array.isArray(parsed.datacenters) || - parsed.datacenters.length === 0 || - parsed.datacenters.length > MAX_ENGINE_DATACENTERS - ) { - throw new Error("Rivet datacenter lookup returned an invalid count"); - } - const datacenters: Record = {}; - for (const datacenter of parsed.datacenters) { - if (typeof datacenter.name !== "string" || !datacenter.name) { - throw new Error("Rivet datacenter lookup returned an invalid name"); - } - datacenters[datacenter.name] = { - serverless: { - url: input.url, - headers: { - [APP_CALLBACK_SECRET_HEADER]: input.callbackSecret, - ...(input.callbackToken - ? { "x-rivet-token": input.callbackToken } - : {}), - }, - request_lifespan: 60 * 60, - metadata_poll_interval: 1_000, - max_runners: 1_024, - min_runners: 0, - runners_margin: 0, - slots_per_runner: 1, - }, - metadata: {}, - drain_on_version_upgrade: true, - }; - } +} + +/** + * Creates or updates the node pool an app's envoy connects to. The pool must + * exist before the envoy connects, because the Engine rejects connections to + * unknown pools. Newer node versions drain older ones so a missed graceful + * shutdown still moves actors to the active release. + */ +export async function ensureEnvoyPool( + input: EngineControl & { pool: string }, +): Promise { const response = await controlFetch( - engineUrl(input.endpoint, ["runner-configs", input.pool], input.namespace), - { method: "PUT", headers, body: JSON.stringify({ datacenters }) }, + engineUrl(input.endpoint, ["pools", input.pool], input.namespace), + { + method: "PUT", + headers: controlHeaders(input.token), + body: JSON.stringify({ drain_on_version_upgrade: true }), + }, ); const body = await readBoundedText(response); if (!response.ok) { throw new Error( - `Rivet runner config upsert failed with HTTP ${response.status}: ${body}`, + `Rivet pool upsert failed with HTTP ${response.status}: ${body}`, ); } +} - // Publish the registry protocol synchronously so the first actor allocation - // cannot race the background metadata poller into the legacy runner path. - const refreshResponse = await controlFetch( - engineUrl( +/** Whether a connected, non-draining node of `version` serves `pool`. */ +export async function poolHasConnectedNode( + input: EngineControl & { pool: string; version: number }, +): Promise { + let cursor: string | undefined; + for (let page = 0; page < MAX_POOL_NODE_PAGES; page += 1) { + const url = engineUrl( input.endpoint, - ["runner-configs", input.pool, "refresh-metadata"], + ["pools", input.pool, "nodes"], input.namespace, - ), - { method: "POST", headers, body: "{}" }, - ); - const refreshBody = await readBoundedText(refreshResponse); - if (!refreshResponse.ok) { - throw new Error( - `Rivet runner metadata refresh failed with HTTP ${refreshResponse.status}: ${refreshBody}`, ); + if (cursor) url.searchParams.set("cursor", cursor); + const response = await controlFetch(url, { + headers: controlHeaders(input.token), + }); + const body = await readBoundedText(response); + if (!response.ok) { + throw new Error( + `Rivet pool node listing failed with HTTP ${response.status}: ${body}`, + ); + } + const parsed = JSON.parse(body) as { + nodes?: Array<{ + version?: unknown; + connected?: unknown; + stopping?: unknown; + }>; + pagination?: { cursor?: string | null }; + }; + const found = parsed.nodes?.some( + (node) => + node.version === input.version && + node.connected === true && + node.stopping !== true, + ); + if (found) return true; + cursor = parsed.pagination?.cursor ?? undefined; + if (!cursor) return false; } + return false; } diff --git a/packages/dynamic-apps/src/skills.ts b/packages/dynamic-apps/src/skills.ts index 3b5524d0e..990e57525 100644 --- a/packages/dynamic-apps/src/skills.ts +++ b/packages/dynamic-apps/src/skills.ts @@ -70,7 +70,7 @@ package.json }, "dependencies": { "hono": "4.13.5", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { "@types/node": "22.20.1", @@ -119,7 +119,6 @@ const counter = actor({ export const registry = setup({ use: { counter } }); const app = new Hono(); -app.all("/api/rivet/*", (context) => registry.handler(context.req.raw)); app.get("/", (context) => context.json({ ok: true, message: "Rivet Actors app is running" }), ); @@ -127,7 +126,7 @@ app.get("/", (context) => export default app; ~~~ -Export the fetch handler and do not call serve() or registry.start(); Dynamic Apps owns the HTTP listener. Keep the build script as "tsc" so deployment failures include TypeScript diagnostics. The example above works without reading external documentation. +Export the fetch handler as the default export and the RivetKit registry as "registry". Do not call serve(), registry.start(), or registry.handler(); Dynamic Apps owns the HTTP listener and runs the registry for you. Keep the build script as "tsc" so deployment failures include TypeScript diagnostics. The example above works without reading external documentation. Optional reference links: - Rivet Actors: https://rivet.dev/actors/docs/ diff --git a/packages/dynamic-apps/src/types.ts b/packages/dynamic-apps/src/types.ts index cf0754e8c..dec2c0fb3 100644 --- a/packages/dynamic-apps/src/types.ts +++ b/packages/dynamic-apps/src/types.ts @@ -52,6 +52,6 @@ export interface AppRouteResolution { maxRequestBytes: number; maxResponseBytes: number; usesRivetKit: boolean; - serverlessEndpoint?: string; + actorEndpoint?: string; runtimePool?: string; } diff --git a/packages/dynamic-apps/tests/direct.test.ts b/packages/dynamic-apps/tests/direct.test.ts index 29371b311..b7282dd05 100644 --- a/packages/dynamic-apps/tests/direct.test.ts +++ b/packages/dynamic-apps/tests/direct.test.ts @@ -28,7 +28,6 @@ import { DynamicActorRuntime, resolveActorAgentOsOptions, } from "../src/actor-runtime.js"; -import { forwardActorCallbackRequest } from "../src/actors.js"; import { resolveDefaultRivetConnection } from "../src/control-plane.js"; import { deployApp } from "../src/deploy.js"; import { @@ -264,7 +263,6 @@ describe("retained public surface", () => { expect( actorWorkerEnvironment({ endpoint: "https://app-namespace:pk_example@api.rivet.dev", - key: "release:hash", namespace: "app-namespace", pool: "app-pool", }), @@ -871,24 +869,6 @@ export default { } }, 60_000); - test("forwards actor callback bodies without eager buffering", async () => { - let pulls = 0; - const source = streamingRequest("http://example.test/api/rivet/start", { - pull(controller) { - pulls += 1; - controller.enqueue(Uint8Array.of(1, 2, 3)); - controller.close(); - }, - }); - const forwarded = forwardActorCallbackRequest(source, "/start"); - expect(pulls).toBe(0); - expect(new URL(forwarded.url).pathname).toBe("/start"); - expect(new Uint8Array(await forwarded.arrayBuffer())).toEqual( - Uint8Array.of(1, 2, 3), - ); - expect(pulls).toBe(1); - }); - test("logs actor server error stacks and causes", async () => { const events: Readonly[] = []; setDynamicAppsLogHandler((event) => events.push(event)); diff --git a/packages/dynamic-apps/tests/release-store.test.ts b/packages/dynamic-apps/tests/release-store.test.ts index cf18a6f61..b3ac8500e 100644 --- a/packages/dynamic-apps/tests/release-store.test.ts +++ b/packages/dynamic-apps/tests/release-store.test.ts @@ -1,23 +1,12 @@ import { createHash } from "node:crypto"; -import { afterEach, describe, expect, test } from "vitest"; +import { describe, expect, test } from "vitest"; import { ARTIFACT_CHUNK_BYTES, createRivetReleaseStore, } from "../src/release-store.js"; -const previousRuntimeMode = process.env.RIVETKIT_RUNTIME_MODE; - -afterEach(() => { - if (previousRuntimeMode === undefined) { - delete process.env.RIVETKIT_RUNTIME_MODE; - } else { - process.env.RIVETKIT_RUNTIME_MODE = previousRuntimeMode; - } -}); - describe("Rivet release store", () => { test("publishes sequential chunks and returns only Deployment fields", async () => { - process.env.RIVETKIT_RUNTIME_MODE = "serverless"; const bytes = Uint8Array.from( { length: ARTIFACT_CHUNK_BYTES + 7 }, (_, index) => index % 251, @@ -83,7 +72,6 @@ describe("Rivet release store", () => { }); test("subscribes, downloads, verifies, and releases a driver", async () => { - process.env.RIVETKIT_RUNTIME_MODE = "serverless"; const bytes = new Uint8Array([1, 2, 3, 4]); const hash = createHash("sha256").update(bytes).digest("hex"); let disposed = 0; @@ -114,7 +102,7 @@ describe("Rivet release store", () => { maxRequestBytes: 1024, maxResponseBytes: 1024, usesRivetKit: true, - serverlessEndpoint: "https://demo:runtime-token@example.test", + actorEndpoint: "https://demo:runtime-token@example.test", runtimePool: "actor-pool", }; }, @@ -149,8 +137,10 @@ describe("Rivet release store", () => { RIVET_POOL: "actor-pool", RIVET_TOKEN: "runtime-token", RIVETKIT_RUNTIME: "wasm", - RIVETKIT_RUNTIME_MODE: "serverless", }); + expect(release?.server?.environment).not.toHaveProperty( + "RIVETKIT_RUNTIME_MODE", + ); expect(timings).toEqual([ "actor-connect", "actor-resolve", @@ -163,7 +153,6 @@ describe("Rivet release store", () => { }); test("cleans up a failed connection and allows a later retry", async () => { - process.env.RIVETKIT_RUNTIME_MODE = "serverless"; let attempts = 0; let disposed = 0; let listenersRemoved = 0; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6a4ba5195..72542d490 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,10 +6,10 @@ settings: overrides: '@rivet-dev/agentos-core': 0.4.3 - '@rivetkit/engine-cli': 2.3.29 - '@rivetkit/react': 2.3.29 - '@rivetkit/rivetkit-wasm': 2.3.29 - rivetkit: 2.3.29 + '@rivetkit/engine-cli': 3.0.2 + '@rivetkit/react': 3.0.2 + '@rivetkit/rivetkit-wasm': 3.0.2 + rivetkit: 3.0.2 importers: @@ -49,12 +49,12 @@ importers: specifier: ^4.13.5 version: 4.13.5 rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) devDependencies: '@rivetkit/engine-cli': - specifier: 2.3.29 - version: 2.3.29 + specifier: 3.0.2 + version: 3.0.2 '@types/node': specifier: ^22.19.15 version: 22.20.1 @@ -155,8 +155,8 @@ importers: specifier: ^4.13.5 version: 4.13.5 rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) devDependencies: '@types/node': specifier: ^22.20.1 @@ -180,8 +180,8 @@ importers: specifier: ^4.13.5 version: 4.13.5 rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) devDependencies: '@types/node': specifier: ^22.20.1 @@ -227,8 +227,8 @@ importers: specifier: ^4.13.5 version: 4.13.5 rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) devDependencies: '@types/node': specifier: ^22.20.1 @@ -252,8 +252,8 @@ importers: specifier: ^4.13.5 version: 4.13.5 rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) devDependencies: '@rivet-dev/agentos-toolchain': specifier: 0.4.3 @@ -280,8 +280,8 @@ importers: specifier: 2.1.1 version: 2.1.1(hono@4.13.5) '@rivetkit/rivetkit-wasm': - specifier: 2.3.29 - version: 2.3.29 + specifier: 3.0.2 + version: 3.0.2 esbuild-wasm: specifier: 0.27.4 version: 0.27.4 @@ -289,8 +289,8 @@ importers: specifier: 4.13.5 version: 4.13.5 rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) secure-exec: specifier: 0.2.1 version: 0.2.1 @@ -348,15 +348,15 @@ importers: specifier: workspace:* version: link:../../../packages/dynamic-apps-builder rivetkit: - specifier: 2.3.29 - version: 2.3.29(better-sqlite3@12.11.1)(ws@8.21.3) + specifier: 3.0.2 + version: 3.0.2(better-sqlite3@12.11.1)(ws@8.21.3) devDependencies: '@rivet-dev/agentos-toolchain': specifier: 0.4.3 version: 0.4.3 '@rivetkit/engine-cli': - specifier: 2.3.29 - version: 2.3.29 + specifier: 3.0.2 + version: 3.0.2 '@types/node': specifier: ^22.19.15 version: 22.20.1 @@ -1040,11 +1040,6 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - '@napi-rs/cli@2.18.4': - resolution: {integrity: sha512-SgJeA4df9DE2iAEpr3M2H0OKl/yjtg1BnRI5/JyowS71tUWhrfSu2LT0V3vlHET+g1hBVlrO60PmEXwUEKp8Mg==} - engines: {node: '>= 10'} - hasBin: true - '@napi-rs/lzma-linux-x64-gnu@1.5.1': resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} engines: {node: ^22.20 || ^24.12 || >=25} @@ -1096,38 +1091,38 @@ packages: resolution: {integrity: sha512-f3aRyVWObvp6cejSXJZutBSrsCwT49D/NWkFv+zRb4EQsRu9fs4gi/jxesez5PQ2jxgy3c7qoNX3MolBD1pY6g==} hasBin: true - '@rivet-dev/services-darwin-arm64@0.2.3': - resolution: {integrity: sha512-rOqSAf+yyUX7k9E5vKyqvUboHKQxBriXTj+vphOVbhTiE2lHX2B78WIowwJQfjLqThasekqiVr7tjLpfA+HSGg==} + '@rivet-dev/services-darwin-arm64@0.2.5': + resolution: {integrity: sha512-/hsHiBrZ810CajMlvGzTYrReGyZi7oMK1LlAI4siFDp3EAmZJt0Ou/S+Kgfsz6H9U1z6fFfztXIpyEAMhK8iUA==} engines: {node: '>=20'} cpu: [arm64] os: [darwin] - '@rivet-dev/services-darwin-x64@0.2.3': - resolution: {integrity: sha512-BZe5Pek1sb3907BHHRKCx70TYOcnyixMWpiBxAe40ybiYjdZyD2H2/IJCpA8hTp5VrQEKgFbP+5xvyBmfeDJGg==} + '@rivet-dev/services-darwin-x64@0.2.5': + resolution: {integrity: sha512-pbGlsYbDSZ6qqddSEITVq5LjS2KTB5k9E9iBo+OzRV9Yhr/C3EqBbJpeCpMYtn0yOnMuw1SbUAwjDYaSdGKJ2g==} engines: {node: '>=20'} cpu: [x64] os: [darwin] - '@rivet-dev/services-linux-arm64-gnu@0.2.3': - resolution: {integrity: sha512-XkJ1hE+FmEoNfZZNe65VqrmpIebgDS2O9j0j13ZeTy2MRP6jAWZfzxZYLMRRWTqTlR5HBrb7pFJQjFWsD1M4lQ==} + '@rivet-dev/services-linux-arm64-gnu@0.2.5': + resolution: {integrity: sha512-enoMQJZh8xHjtnkpxYYPsl2GUvWwHcR/0eg6UTqcbZEHwgVcexdTlrkuXQNZvtZGDkHaTgkOm+wcPdwqWd16IQ==} engines: {node: '>=20'} cpu: [arm64] os: [linux] - '@rivet-dev/services-linux-x64-gnu@0.2.3': - resolution: {integrity: sha512-1XOj6vb4nusU8AzJvhxnUJnW3FrTK5E495gvjKPNbWGnpHR18UOXWoAG0jU8TTggRf3iwYCZi+QSyjd4cCs42w==} + '@rivet-dev/services-linux-x64-gnu@0.2.5': + resolution: {integrity: sha512-TvLGQWjlvhnt2vuTzU6/NgVzYW9/ilahYRRP/3HS8Sg3GEA/613lmrPtsaFyjWgk1MIBdpgn0sl2vhtlRw7dew==} engines: {node: '>=20'} cpu: [x64] os: [linux] - '@rivet-dev/services-win32-x64@0.2.3': - resolution: {integrity: sha512-8xXY5Ic1/DxXA8eMbsHU4QugJS+u2KCPCL/0yb+/47Ogvty8/8wLjZcRBdDD82rzTX32oW+JPdmjg8iVvWBZqA==} + '@rivet-dev/services-win32-x64@0.2.5': + resolution: {integrity: sha512-yNxds5Pdk8w2pwfIgcd+lDaYRvF5qGYZvTUXHH1knk6gecm5UsaGrSCHwqxFKrAGMPEcRWpQ2NbQNdOojYNmDw==} engines: {node: '>=20'} cpu: [x64] os: [win32] - '@rivet-dev/services@0.2.3': - resolution: {integrity: sha512-4aLKlFgykfM4om6Ag6ySKe7UuO4C3JDCHIdKxft+6Sx8tvVqakFu3rQ+5i6rCMrOzOPGOBtSGPs7UJWqVqe38g==} + '@rivet-dev/services@0.2.5': + resolution: {integrity: sha512-RKraXpp6T05qC/+v1NwqWmedkjcD9mkPc3AgzGlNdPWKKhZabTIuEprVpW5a1Qca2v3b2cRwUVXvij7IW02JBw==} engines: {node: '>=20'} hasBin: true @@ -1135,108 +1130,100 @@ packages: resolution: {integrity: sha512-3qndQUQXLdwafMEqfhz24hUtDPcsf1Bu3q52Kb8MqeH8JUh3h6R4HYW3ZJXiQsLcyYyFM68PuIwlLRlg1xDEpg==} engines: {node: ^14.18.0 || >=16.0.0} - '@rivetkit/engine-api-full@2.3.29': - resolution: {integrity: sha512-WGyovx89kusj07v237TcfdUEtuot7ohX76jrkBAU0XuU2XYUp+udqBbu+b5fWXTPdECPMvuplF+dGFnXseApzA==} + '@rivetkit/engine-api-full@3.0.2': + resolution: {integrity: sha512-jnXOQbUszJSZsysuQLO1y9Xl0EfyYa41ouFNoVAlNz8TAUIHG9tnyINapFFS9vwnqfsilgegHBXVUChhbzeuLg==} - '@rivetkit/engine-cli-darwin-arm64@2.3.29': - resolution: {integrity: sha512-RytlngQPBjIiUYKJmVvK0747GpqqcrJPvb9evQkgiNccaRXvgi9FCWrQRVLBBzQfkDZXecQ4wWTswHm2Tb0/+w==} + '@rivetkit/engine-cli-darwin-arm64@3.0.2': + resolution: {integrity: sha512-KQyp+NYxA1rBpgkqYHsBSGN+DWZZ5hFm+1WoRUplmlGUfWiLIQMxfLxrnAJ7SKd5F7E4PzOnCBbrYZv9oseX0g==} engines: {node: '>= 20.0.0'} cpu: [arm64] os: [darwin] + hasBin: true - '@rivetkit/engine-cli-darwin-x64@2.3.29': - resolution: {integrity: sha512-MCdqWJWOA1uMhpmpd5M/rXWWnArjZBfoFuZ9LhHkL6XzvFbwvhyMIs3QOcGNbXWZBIMaQptJdjQkuRAjQ4SyvQ==} + '@rivetkit/engine-cli-darwin-x64@3.0.2': + resolution: {integrity: sha512-XGMEok7+xZSNPpE/vbddw2Uj2ViqLac2GhB1Ld0Rn01WHKS8SxeX8qlxCog1FxYdaS/wSc55yZjN6cywDYwG3g==} engines: {node: '>= 20.0.0'} cpu: [x64] os: [darwin] + hasBin: true - '@rivetkit/engine-cli-linux-arm64-musl@2.3.29': - resolution: {integrity: sha512-2Fb+v0wdA1ZI6xJshDpk94TehlbjQM1FVQUSiOH+1SF2Gse5qmeSkFDmaDvAn3r1KWgJ0n+eU+L4v0fsmKPxBw==} + '@rivetkit/engine-cli-linux-arm64-musl@3.0.2': + resolution: {integrity: sha512-+iHINKYFcVDVeyQhCQ/2CN3W3w7ZznSk6ebe3QL7y7XV47Q0GEocUmEUdfvcaidNrSbhyHLCp89HG6+NEI/1TA==} engines: {node: '>= 20.0.0'} cpu: [arm64] os: [linux] + hasBin: true - '@rivetkit/engine-cli-linux-x64-musl@2.3.29': - resolution: {integrity: sha512-sB5SUPJt24jrXj+7ZbpmWKXAumlWEGez+TpXzomwfIvLi/OJLABX/ZCReuwTHA9EN4Y/BzN7m2JsWJaVYI7jJw==} + '@rivetkit/engine-cli-linux-x64-musl@3.0.2': + resolution: {integrity: sha512-d5zZqJVc75BiGItTmwr50NPgIcuYpSzlVejbQuZgKSlnXkK7+3xTuPrTMKeh2I9QQ3qttA6+jDVDHe+m1Z0LSQ==} engines: {node: '>= 20.0.0'} cpu: [x64] os: [linux] + hasBin: true - '@rivetkit/engine-cli-win32-x64@2.3.29': - resolution: {integrity: sha512-PS1cMGxX1rABQtrNhjKTFATFghQu4b7IIStNLdj1jwy9x8NKGNuVRCzihaR6iqs6z6c2O5Lgeua41QRBX20v0g==} - engines: {node: '>= 20.0.0'} - cpu: [x64] - os: [win32] - - '@rivetkit/engine-cli@2.3.29': - resolution: {integrity: sha512-R7P9h6W3F5misQus8v+aExoahfUhMftmJlCfiauokCHaXFgbQLj/KjeL8nw7stmrslPeBGUVLSd4OcZkl+ynVw==} + '@rivetkit/engine-cli@3.0.2': + resolution: {integrity: sha512-2nu/jrDb4NXE0HCAPkvqwh3EwRtYVm4fDK1nAIcFdD4ikvKzQqVPGVNpNsbp9Ad4Pc8LVWBFLtEa56ZokgFxxw==} engines: {node: '>= 20.0.0'} - '@rivetkit/engine-envoy-protocol@2.3.29': - resolution: {integrity: sha512-nwJHKSJPRi3dxSgiDkMdsuJBeDalr6mCUpWsAMPCkoZ1XKD8zvJk20D4amKFLpp+GdrQzQjfJ6dKBzHIymcDsw==} + '@rivetkit/engine-envoy-protocol@3.0.2': + resolution: {integrity: sha512-wk+dgIrOuf0gRKiik5MhQrMFTjOMCXe4vZQ1ZGGIqDwxVew45vEkoSG2lIkYPSFjBQTmcWqeAKxFc4zvpVbWaw==} '@rivetkit/on-change@6.0.1': resolution: {integrity: sha512-QBN/KRBXLJdCgN4gBTL3XAc/zKm58atSnieXWMOyFSPmo6F1/yIVV/LTRdvAktfCttrGx7W6c32i/lwqCHWnsQ==} engines: {node: '>=20'} - '@rivetkit/rivetkit-napi-darwin-arm64@2.3.29': - resolution: {integrity: sha512-T9Z98GTwfh6grV2VoY02f+oiB3BcRuudTz9D7DB5n0sRC0GqyjTutcfWWjCLexWu1hWsJBp5u89ixoLbsVXw8Q==} + '@rivetkit/rivetkit-napi-darwin-arm64@3.0.2': + resolution: {integrity: sha512-hJbwdj8fUI0T0t2JoB+IH1q26qGNtKzFjGCvUQyLMOeoPL0CbQ13Hg+jlEXU9plIVPNHjBUrQCjftW1gzDufXA==} engines: {node: '>= 20.0.0'} cpu: [arm64] os: [darwin] - '@rivetkit/rivetkit-napi-darwin-x64@2.3.29': - resolution: {integrity: sha512-7nEQDYxpH2Au2+aVdHAjdB4UARh/g1E3tRBRMnKKN7PWYNsnXxvCjyIiUCHXrCDdDxVs1PmstQBE3R7dtLIAhg==} + '@rivetkit/rivetkit-napi-darwin-x64@3.0.2': + resolution: {integrity: sha512-1VEpHbXFabuAw9mLxUtvM1bFpjM1kqmrXhISbSpBepgoOyEqdcWqGTRXzlGAadD/K2eIrrdcemNXSk0k4vfM8w==} engines: {node: '>= 20.0.0'} cpu: [x64] os: [darwin] - '@rivetkit/rivetkit-napi-linux-arm64-gnu@2.3.29': - resolution: {integrity: sha512-KyDTR7/TXGUP/C494Vqyz0PGaf0BbTi13TpO+ZMTlQ+9vWMYFe2BFATIYL+Xv9cd16oyp8D5h5sAYi/muKVlpA==} + '@rivetkit/rivetkit-napi-linux-arm64-gnu@3.0.2': + resolution: {integrity: sha512-JbB9QLHH524Ce6amq+rqsZljjIY2GzALAsIBMW1z4syH9vVgzToVA0CSglZ+YuCYN1mcRveqDuL4qLI3FwEyfQ==} engines: {node: '>= 20.0.0'} cpu: [arm64] os: [linux] - '@rivetkit/rivetkit-napi-linux-arm64-musl@2.3.29': - resolution: {integrity: sha512-3nlw+T3TZT4WoC3nof5gAww4sp9jX/+oHUswW3sGyOg/I8EdCV5lhGNnAOagv3RaCifaYv6eVZ0Ebgg1v4cQlw==} + '@rivetkit/rivetkit-napi-linux-arm64-musl@3.0.2': + resolution: {integrity: sha512-dEBC8dUwYRsmyHcc04HCp5hBhiuV7G6KU2qYw2qeBREYdZjKazqwWbrpH/RMkc8vE3MuAuw0UFDQ7U+YgqedvQ==} engines: {node: '>= 20.0.0'} cpu: [arm64] os: [linux] - '@rivetkit/rivetkit-napi-linux-x64-gnu@2.3.29': - resolution: {integrity: sha512-Op7K9WSpf3paYEFnCgPUZS+l/4ZW1V/ZrYGA2jhY7gFye6QqnVlyYxHCHI4aIa/kk45XRDJJIL03x0TEmbN04Q==} + '@rivetkit/rivetkit-napi-linux-x64-gnu@3.0.2': + resolution: {integrity: sha512-pFX/cAbdowcVFwAzAvLTMoyap+atMCqZXTC61KbeioXPdmTjjRJ9rcjp34ba42wxHKUTtOOrAbMVA2SNVhXH6w==} engines: {node: '>= 20.0.0'} cpu: [x64] os: [linux] - '@rivetkit/rivetkit-napi-linux-x64-musl@2.3.29': - resolution: {integrity: sha512-xLR0IhdsJTHvcOONYQe/QlXMvy8VnT+32WHqS55GWiYu2ufiaSVAOZuJbvfbcXkuaJyVwi4lw7tb97H2XERjnA==} + '@rivetkit/rivetkit-napi-linux-x64-musl@3.0.2': + resolution: {integrity: sha512-ou7B8fr3TXQBOSYkbsHZonRPqt/NDCMPkb2kDZ9DSkcTuZSksMzVLbthHeippHPmTIJgEQeVsLvPYBW6V6P0tQ==} engines: {node: '>= 20.0.0'} cpu: [x64] os: [linux] - '@rivetkit/rivetkit-napi-win32-x64-msvc@2.3.29': - resolution: {integrity: sha512-MGH/32F0vlvjrA4hhceu9QqZ2kA6814/tzHxDb+uwgbzyfWwVlcs60782E9F/uFi92YnjRkBTn4R6GLu/1twMQ==} + '@rivetkit/rivetkit-napi@3.0.2': + resolution: {integrity: sha512-QIPtYh6B7Jlq93kDLqtFGmLW5520nHK34Gb9MPFroqTFoXw7akwloga2nNEeLT3L99uZHCMoINAGp/yCiJRMoA==} engines: {node: '>= 20.0.0'} - cpu: [x64] - os: [win32] - '@rivetkit/rivetkit-napi@2.3.29': - resolution: {integrity: sha512-hTfk7uBqqIxtq7HFMoMH5XJr5tBK4KdggxQBT5D2UYrD7SOcGdQdA1/RsBug2k++woU47mm1PcfD0moqUj1/Nw==} - engines: {node: '>= 20.0.0'} + '@rivetkit/rivetkit-wasm@3.0.2': + resolution: {integrity: sha512-Z6bFb97FPxd9DI/wEHUaArUmDvLD2Xj1lai1NmgPBj7s2nQ6wWwoCBfvoplWqqsz3hRaSLlLf5yOmKBctJR3DA==} - '@rivetkit/rivetkit-wasm@2.3.29': - resolution: {integrity: sha512-Syy961RQVdYQf2MEl+63mywgR2k11EkywqAQbjEpXuFaEHxd7jrJLitP67bkzZYViosplLnxyf+3guocBVXU2Q==} - - '@rivetkit/traces@2.3.29': - resolution: {integrity: sha512-J1mmAeaI1bqDz0jNDB9Wor0N89hKX6WTAxIKk+m7VEUoZPZlHzWY8vOtxVFLl2mGRgVcZkoB45N56eotTDAzbQ==} + '@rivetkit/traces@3.0.2': + resolution: {integrity: sha512-N0Ie4M+mhl7BR/89Tva02NiezE2wMQ6QQxVCxRWoIRRjcXQ0CKRwZyTqVNZTrHKQxduQ4PpB8MrtomkkCKtx+A==} engines: {node: '>=18.0.0'} - '@rivetkit/virtual-websocket@2.3.29': - resolution: {integrity: sha512-QKlJNenKwo4SwMTOo3NsIbDtsGxzPVBq/ft2QIFm7ouHsDHDDZzBj9rY5f/4jv4dVVjpkLVUoy2PN7OGLjcolw==} + '@rivetkit/virtual-websocket@3.0.2': + resolution: {integrity: sha512-vrmN11DsoedQtZz8ABGnnqvTKFcLpKeb/xXmRiU8A9kTNZ6lfv+TvzDJMGRVJn6mqmYLEih8ecIA8OtcdZ975A==} - '@rivetkit/workflow-engine@2.3.29': - resolution: {integrity: sha512-19iZ4t9dURqxz34uhjUb6b0ERiMAJxxvtqg9wGTt9ItNJG8ahuVBMqgYgeJ+G3QPiwqBxQpatQ0gy2KRSFVMYg==} + '@rivetkit/workflow-engine@3.0.2': + resolution: {integrity: sha512-tVMIAl6rWx3NaG0raagjw5JFF6+5xeT/3RRtjQAYbJGEyFfYvIUgCh+1aaqKwgEhc20Rxglh8LvJbLwB4qL9dQ==} engines: {node: '>=18.0.0'} '@rollup/rollup-android-arm-eabi@4.62.4': @@ -2429,8 +2416,8 @@ packages: resolution: {integrity: sha512-5Di9UC0+8h1L6ZD2d7awM7E/T4uA1fJRlx6zk/NvdCCVEoAnFqvHmCuNeIKoCeIixBX/q8uM+6ycDvF8woqosA==} engines: {node: '>= 0.8'} - rivetkit@2.3.29: - resolution: {integrity: sha512-equYPSxPPB3YMUx08M/jIS3L17LkFuxEB9gDV9j0QOh3MOlexEv1EwLJXEyT0n6CHEHV9Jw9Cfo6I0StOdc19g==} + rivetkit@3.0.2: + resolution: {integrity: sha512-bDL3p26DcOcWMaLwtIOAuRSSWl+jKx4tXhX2PfveE1m9IMOZfO1rdM2ee+sMlydBTVj0w4g6339GtPx8wEmspw==} engines: {node: '>=22.0.0'} peerDependencies: drizzle-kit: ^0.31.2 @@ -3326,8 +3313,6 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@napi-rs/cli@2.18.4': {} - '@napi-rs/lzma-linux-x64-gnu@1.5.1': optional: true @@ -3382,32 +3367,33 @@ snapshots: dependencies: '@bare-ts/lib': 0.4.1 - '@rivet-dev/services-darwin-arm64@0.2.3': + '@rivet-dev/services-darwin-arm64@0.2.5': optional: true - '@rivet-dev/services-darwin-x64@0.2.3': + '@rivet-dev/services-darwin-x64@0.2.5': optional: true - '@rivet-dev/services-linux-arm64-gnu@0.2.3': + '@rivet-dev/services-linux-arm64-gnu@0.2.5': optional: true - '@rivet-dev/services-linux-x64-gnu@0.2.3': + '@rivet-dev/services-linux-x64-gnu@0.2.5': optional: true - '@rivet-dev/services-win32-x64@0.2.3': + '@rivet-dev/services-win32-x64@0.2.5': optional: true - '@rivet-dev/services@0.2.3': + '@rivet-dev/services@0.2.5': optionalDependencies: - '@rivet-dev/services-darwin-arm64': 0.2.3 - '@rivet-dev/services-darwin-x64': 0.2.3 - '@rivet-dev/services-linux-arm64-gnu': 0.2.3 - '@rivet-dev/services-linux-x64-gnu': 0.2.3 - '@rivet-dev/services-win32-x64': 0.2.3 + '@rivet-dev/services-darwin-arm64': 0.2.5 + '@rivet-dev/services-darwin-x64': 0.2.5 + '@rivet-dev/services-linux-arm64-gnu': 0.2.5 + '@rivet-dev/services-linux-x64-gnu': 0.2.5 + '@rivet-dev/services-win32-x64': 0.2.5 + optional: true '@rivetkit/bare-ts@0.6.2': {} - '@rivetkit/engine-api-full@2.3.29': + '@rivetkit/engine-api-full@3.0.2': dependencies: form-data: 4.0.6 js-base64: 3.9.4 @@ -3418,81 +3404,72 @@ snapshots: transitivePeerDependencies: - encoding - '@rivetkit/engine-cli-darwin-arm64@2.3.29': - optional: true - - '@rivetkit/engine-cli-darwin-x64@2.3.29': + '@rivetkit/engine-cli-darwin-arm64@3.0.2': optional: true - '@rivetkit/engine-cli-linux-arm64-musl@2.3.29': + '@rivetkit/engine-cli-darwin-x64@3.0.2': optional: true - '@rivetkit/engine-cli-linux-x64-musl@2.3.29': + '@rivetkit/engine-cli-linux-arm64-musl@3.0.2': optional: true - '@rivetkit/engine-cli-win32-x64@2.3.29': + '@rivetkit/engine-cli-linux-x64-musl@3.0.2': optional: true - '@rivetkit/engine-cli@2.3.29': + '@rivetkit/engine-cli@3.0.2': optionalDependencies: - '@rivetkit/engine-cli-darwin-arm64': 2.3.29 - '@rivetkit/engine-cli-darwin-x64': 2.3.29 - '@rivetkit/engine-cli-linux-arm64-musl': 2.3.29 - '@rivetkit/engine-cli-linux-x64-musl': 2.3.29 - '@rivetkit/engine-cli-win32-x64': 2.3.29 + '@rivetkit/engine-cli-darwin-arm64': 3.0.2 + '@rivetkit/engine-cli-darwin-x64': 3.0.2 + '@rivetkit/engine-cli-linux-arm64-musl': 3.0.2 + '@rivetkit/engine-cli-linux-x64-musl': 3.0.2 - '@rivetkit/engine-envoy-protocol@2.3.29': + '@rivetkit/engine-envoy-protocol@3.0.2': dependencies: '@rivetkit/bare-ts': 0.6.2 '@rivetkit/on-change@6.0.1': {} - '@rivetkit/rivetkit-napi-darwin-arm64@2.3.29': - optional: true - - '@rivetkit/rivetkit-napi-darwin-x64@2.3.29': + '@rivetkit/rivetkit-napi-darwin-arm64@3.0.2': optional: true - '@rivetkit/rivetkit-napi-linux-arm64-gnu@2.3.29': + '@rivetkit/rivetkit-napi-darwin-x64@3.0.2': optional: true - '@rivetkit/rivetkit-napi-linux-arm64-musl@2.3.29': + '@rivetkit/rivetkit-napi-linux-arm64-gnu@3.0.2': optional: true - '@rivetkit/rivetkit-napi-linux-x64-gnu@2.3.29': + '@rivetkit/rivetkit-napi-linux-arm64-musl@3.0.2': optional: true - '@rivetkit/rivetkit-napi-linux-x64-musl@2.3.29': + '@rivetkit/rivetkit-napi-linux-x64-gnu@3.0.2': optional: true - '@rivetkit/rivetkit-napi-win32-x64-msvc@2.3.29': + '@rivetkit/rivetkit-napi-linux-x64-musl@3.0.2': optional: true - '@rivetkit/rivetkit-napi@2.3.29': + '@rivetkit/rivetkit-napi@3.0.2': dependencies: - '@napi-rs/cli': 2.18.4 - '@rivetkit/engine-envoy-protocol': 2.3.29 + '@rivetkit/engine-envoy-protocol': 3.0.2 optionalDependencies: - '@rivetkit/rivetkit-napi-darwin-arm64': 2.3.29 - '@rivetkit/rivetkit-napi-darwin-x64': 2.3.29 - '@rivetkit/rivetkit-napi-linux-arm64-gnu': 2.3.29 - '@rivetkit/rivetkit-napi-linux-arm64-musl': 2.3.29 - '@rivetkit/rivetkit-napi-linux-x64-gnu': 2.3.29 - '@rivetkit/rivetkit-napi-linux-x64-musl': 2.3.29 - '@rivetkit/rivetkit-napi-win32-x64-msvc': 2.3.29 + '@rivetkit/rivetkit-napi-darwin-arm64': 3.0.2 + '@rivetkit/rivetkit-napi-darwin-x64': 3.0.2 + '@rivetkit/rivetkit-napi-linux-arm64-gnu': 3.0.2 + '@rivetkit/rivetkit-napi-linux-arm64-musl': 3.0.2 + '@rivetkit/rivetkit-napi-linux-x64-gnu': 3.0.2 + '@rivetkit/rivetkit-napi-linux-x64-musl': 3.0.2 - '@rivetkit/rivetkit-wasm@2.3.29': {} + '@rivetkit/rivetkit-wasm@3.0.2': {} - '@rivetkit/traces@2.3.29': + '@rivetkit/traces@3.0.2': dependencies: '@rivetkit/bare-ts': 0.6.2 cbor-x: 1.6.5 fdb-tuple: 1.0.0 vbare: 0.0.4 - '@rivetkit/virtual-websocket@2.3.29': {} + '@rivetkit/virtual-websocket@3.0.2': {} - '@rivetkit/workflow-engine@2.3.29': + '@rivetkit/workflow-engine@3.0.2': dependencies: '@rivetkit/bare-ts': 0.6.2 cbor-x: 1.6.5 @@ -4757,21 +4734,20 @@ snapshots: hash-base: 3.1.2 inherits: 2.0.4 - rivetkit@2.3.29(better-sqlite3@12.11.1)(ws@8.21.3): + rivetkit@3.0.2(better-sqlite3@12.11.1)(ws@8.21.3): dependencies: '@hono/zod-openapi': 1.6.0(hono@4.13.5)(zod@4.5.4) '@opentelemetry/api': 1.9.1 - '@rivet-dev/services': 0.2.3 '@rivetkit/bare-ts': 0.6.2 - '@rivetkit/engine-api-full': 2.3.29 - '@rivetkit/engine-cli': 2.3.29 - '@rivetkit/engine-envoy-protocol': 2.3.29 + '@rivetkit/engine-api-full': 3.0.2 + '@rivetkit/engine-cli': 3.0.2 + '@rivetkit/engine-envoy-protocol': 3.0.2 '@rivetkit/on-change': 6.0.1 - '@rivetkit/rivetkit-napi': 2.3.29 - '@rivetkit/rivetkit-wasm': 2.3.29 - '@rivetkit/traces': 2.3.29 - '@rivetkit/virtual-websocket': 2.3.29 - '@rivetkit/workflow-engine': 2.3.29 + '@rivetkit/rivetkit-napi': 3.0.2 + '@rivetkit/rivetkit-wasm': 3.0.2 + '@rivetkit/traces': 3.0.2 + '@rivetkit/virtual-websocket': 3.0.2 + '@rivetkit/workflow-engine': 3.0.2 cbor-x: 1.6.5 drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(better-sqlite3@12.11.1) hono: 4.13.5 @@ -4782,6 +4758,7 @@ snapshots: vbare: 0.0.4 zod: 4.5.4 optionalDependencies: + '@rivet-dev/services': 0.2.5 ws: 8.21.3 transitivePeerDependencies: - '@aws-sdk/client-rds-data' diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6d9eaf009..bba902ef0 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -12,11 +12,11 @@ onlyBuiltDependencies: overrides: '@rivet-dev/agentos-core': 0.4.3 - '@rivetkit/engine-cli': 2.3.29 - '@rivetkit/react': 2.3.29 - '@rivetkit/rivetkit-wasm': 2.3.29 - rivetkit: 2.3.29 + '@rivetkit/engine-cli': 3.0.2 + '@rivetkit/react': 3.0.2 + '@rivetkit/rivetkit-wasm': 3.0.2 + rivetkit: 3.0.2 catalogs: rivetkit: - rivetkit: 2.3.29 + rivetkit: 3.0.2 diff --git a/scripts/check-boundaries.mjs b/scripts/check-boundaries.mjs index 6587c13ae..9ab8c5a36 100644 --- a/scripts/check-boundaries.mjs +++ b/scripts/check-boundaries.mjs @@ -114,9 +114,7 @@ for (const identity of [ const runtime = await read("packages/dynamic-apps-core/src/runtime.ts"); assert( - runtime.includes( - 'hash.update("dynamic-apps-release-v19-mounted-hono-router\\0")', - ), + runtime.includes('hash.update("dynamic-apps-release-v20-rivet-v3-envoy\\0")'), "release hash domain changed", ); diff --git a/scripts/test-packed.mjs b/scripts/test-packed.mjs index 4e96b90c9..b69dd4a20 100644 --- a/scripts/test-packed.mjs +++ b/scripts/test-packed.mjs @@ -105,6 +105,7 @@ if ( "rivetActorsSkill", "setDynamicAppsLogHandler", "setDynamicAppsVmOptions", + "startDynamicAppsHost", "webServerSkill", ]) ) { diff --git a/tests/e2e/dynamic-apps/package.json b/tests/e2e/dynamic-apps/package.json index 3e62593c0..596012402 100644 --- a/tests/e2e/dynamic-apps/package.json +++ b/tests/e2e/dynamic-apps/package.json @@ -7,16 +7,17 @@ "test:e2e": "npx tsx src/run.ts", "test:e2e:build": "npx tsx src/run.ts --build-only", "test:e2e:fast": "npx tsx src/run.ts --fast", + "test:e2e:failover": "npx tsx src/run.ts --fast --failover", "check-types": "tsc --noEmit" }, "dependencies": { "@rivet-dev/dynamic-apps": "workspace:*", "@rivet-dev/dynamic-apps-builder": "workspace:*", - "rivetkit": "2.3.29" + "rivetkit": "3.0.2" }, "devDependencies": { "@rivet-dev/agentos-toolchain": "0.4.3", - "@rivetkit/engine-cli": "2.3.29", + "@rivetkit/engine-cli": "3.0.2", "@types/node": "^22.19.15", "get-port": "^7.1.0", "tsx": "^4.20.6", diff --git a/tests/e2e/dynamic-apps/src/failover-fixture.ts b/tests/e2e/dynamic-apps/src/failover-fixture.ts new file mode 100644 index 000000000..1a95a5621 --- /dev/null +++ b/tests/e2e/dynamic-apps/src/failover-fixture.ts @@ -0,0 +1,38 @@ +export const FAILOVER_APP_ID = "dynamic-apps-failover-e2e"; + +export function failoverFixtureFiles(): Record { + return { + "package.json": JSON.stringify({ + name: "dynamic-apps-failover-e2e-fixture", + version: "1.0.0", + private: true, + type: "module", + main: "index.js", + dependencies: { hono: "4.13.5", rivetkit: "3.0.2" }, + }), + "index.js": ` +import { Hono } from "hono"; +import { actor, setup } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + actions: { + async add(c, amount = 1) { + c.state.count += amount; + // The test kills this host right after the call, so persist before replying. + await c.saveState({ immediate: true }); + return c.state.count; + }, + inspect(c) { + return c.state.count; + }, + }, +}); + +export const registry = setup({ use: { counter } }); +const app = new Hono(); +app.all("*", () => Response.json({ ok: true })); +export default app; +`, + }; +} diff --git a/tests/e2e/dynamic-apps/src/failover-host.ts b/tests/e2e/dynamic-apps/src/failover-host.ts new file mode 100644 index 000000000..29cc32928 --- /dev/null +++ b/tests/e2e/dynamic-apps/src/failover-host.ts @@ -0,0 +1,20 @@ +import { deployApp } from "@rivet-dev/dynamic-apps"; +import { createClient } from "rivetkit/client"; +import { FAILOVER_APP_ID, failoverFixtureFiles } from "./failover-fixture.js"; + +// Host A: deploys the app, writes actor state, then waits to be killed. +const deployment = await deployApp({ + appId: FAILOVER_APP_ID, + files: failoverFixtureFiles(), +}); +const client = createClient({ + namespace: deployment.namespace, + poolName: deployment.pool, +}) as unknown as { + counter: { + getOrCreate(key: string[]): { add(amount: number): Promise }; + }; +}; +const count = await client.counter.getOrCreate(["failover"]).add(7); +console.log(`FAILOVER_READY ${JSON.stringify({ deployment, count })}`); +setInterval(() => {}, 60_000); diff --git a/tests/e2e/dynamic-apps/src/failover.ts b/tests/e2e/dynamic-apps/src/failover.ts new file mode 100644 index 000000000..f51462ad6 --- /dev/null +++ b/tests/e2e/dynamic-apps/src/failover.ts @@ -0,0 +1,87 @@ +import { spawn } from "node:child_process"; +import { + setDynamicAppsLogHandler, + startDynamicAppsHost, +} from "@rivet-dev/dynamic-apps"; +import { createClient } from "rivetkit/client"; + +// Host A runs in its own process group so killing it also kills its agentOS +// sidecar and guest VM, as losing a machine would. +const hostA = spawn( + process.execPath, + ["--import", "tsx", "src/failover-host.ts"], + { + cwd: process.cwd(), + env: process.env, + detached: true, + stdio: ["ignore", "pipe", "inherit"], + }, +); +const ready = await new Promise<{ + deployment: { namespace: string; pool: string }; + count: number; +}>((resolve, reject) => { + let output = ""; + hostA.stdout.on("data", (chunk: Buffer) => { + output += chunk.toString(); + const match = output.match(/FAILOVER_READY (.+)\n/); + if (match?.[1]) resolve(JSON.parse(match[1])); + }); + hostA.once("exit", (code) => reject(new Error(`host A exited with ${code}`))); +}); +assert(ready.count === 7, "host A did not write the actor state"); +if (hostA.pid === undefined) throw new Error("host A has no pid"); +process.kill(-hostA.pid, "SIGKILL"); +const killedAt = performance.now(); + +setDynamicAppsLogHandler((event) => { + if (event.level === "error") console.error(JSON.stringify(event)); +}); + +// Host B only starts its registry. Its recovery loop must wake the app actor +// that died with host A, which restarts the app's envoy here. +await startDynamicAppsHost(); + +const client = createClient({ + namespace: ready.deployment.namespace, + poolName: ready.deployment.pool, +}) as unknown as { + counter: { getOrCreate(key: string[]): { inspect(): Promise } }; + dispose(): Promise; +}; +const deadline = Date.now() + 150_000; +let recovered: number | undefined; +let last: unknown; +let attempts = 0; +while (Date.now() < deadline) { + attempts += 1; + try { + recovered = await Promise.race([ + client.counter.getOrCreate(["failover"]).inspect(), + new Promise((_, reject) => + setTimeout(() => reject(new Error("inspect timed out")), 15_000), + ), + ]); + if (recovered === 7) break; + } catch (error) { + last = error; + } + // Recovery is driven by the Engine's lost threshold and the recovery loop. + await new Promise((resolve) => setTimeout(resolve, 1_000)); +} +await client.dispose(); +assert( + recovered === 7, + `actor did not recover after host A died after ${attempts} attempts; last: ${String(last)}`, +); +console.log( + JSON.stringify({ + event: "dynamic_apps_failover_passed", + recoveredCount: recovered, + recoveryMs: Math.round(performance.now() - killedAt), + }), +); + +function assert(condition: unknown, message: string): asserts condition { + if (!condition) throw new Error(message); +} diff --git a/tests/e2e/dynamic-apps/src/run.ts b/tests/e2e/dynamic-apps/src/run.ts index 67ffec5cb..edf1a3865 100644 --- a/tests/e2e/dynamic-apps/src/run.ts +++ b/tests/e2e/dynamic-apps/src/run.ts @@ -9,6 +9,7 @@ import getPort from "get-port"; const fast = process.argv.includes("--fast"); const buildOnly = process.argv.includes("--build-only"); const sanity = process.argv.includes("--sanity"); +const failover = process.argv.includes("--failover"); const root = await mkdtemp(join(tmpdir(), "dynamic-apps-e2e-")); const databasePath = join(root, "db"); await mkdir(databasePath, { recursive: true }); @@ -24,14 +25,11 @@ const peerEndpoint = `http://127.0.0.1:${peerPort}`; const configPath = join(root, "engine.json"); // Rivet Engine requires an admin token to start. const adminToken = randomBytes(32).toString("hex"); +const logDirectory = join(root, "log"); +await mkdir(logDirectory, { recursive: true }); await writeFile( configPath, JSON.stringify({ - file_system: { path: databasePath }, - auth: { admin_token: adminToken }, - guard: { host: "127.0.0.1", port: guardPort }, - api_peer: { host: "127.0.0.1", port: peerPort }, - metrics: { host: "127.0.0.1", port: metricsPort }, topology: { datacenter_label: 1, datacenters: { @@ -40,23 +38,47 @@ await writeFile( is_leader: true, public_url: endpoint, peer_url: peerEndpoint, - proxy_url: null, }, }, }, - telemetry: { enabled: false }, - runtime: { allow_version_rollback: true }, }), ); -const engine = spawn(getEnginePath(), ["--config", configPath, "start"], { +// Mirrors the single-worker local engine that RivetKit starts for development. +const engine = spawn(getEnginePath(), ["--config", configPath], { stdio: ["ignore", "inherit", "inherit"], + env: { + ...process.env, + RIVET__AUTH__ADMIN_TOKEN: adminToken, + RIVET__GUARD__HOST: "127.0.0.1", + RIVET__GUARD__PORT: String(guardPort), + RIVET__API_PEER__HOST: "127.0.0.1", + RIVET__API_PEER__PORT: String(peerPort), + RIVET__METRICS__HOST: "127.0.0.1", + RIVET__METRICS__PORT: String(metricsPort), + RIVET__STORAGE__LOG_DIRECTORY: logDirectory, + RIVET__OBJECT_STORAGE__PRIMARY__FILE_SYSTEM__PATH: databasePath, + RIVET__STORAGE__BALANCING__ENABLED: "false", + RIVET__STORAGE__AUTO_PROVISION_PARTITIONS: "1", + RIVET__STORAGE__LOG_SHARD__MAX_DISK_BYTES: String(4 * 1024 ** 3), + RIVET__STORAGE__COLD_STORE__DISK_CACHE_BYTES: "0", + RIVET__STORAGE__WRITE_TO_COLD_AFTER_MS: "5000", + RIVET__STORAGE__STOP_TIMEOUT_MS: "6000", + RIVET__STORAGE__STOP_TEARDOWN_MS: "2000", + RIVET__PEGBOARD__NODE_LOST_THRESHOLD: "7000", + RIVET__RUNTIME__WORKER_SHUTDOWN_DURATION: "1", + RIVET__RUNTIME__GUARD_SHUTDOWN_DURATION: "1", + RIVET__RUNTIME__FORCE_SHUTDOWN_DURATION: "10", + }, }); try { await waitUntilHealthy(endpoint, engine); process.env.RIVET_ENDPOINT = endpoint; process.env.RIVET_TOKEN = adminToken; + // App envoys authenticate with the credentials in the public endpoint. The + // local Engine has only an admin token, so the test hands that to guests. + process.env.RIVET_PUBLIC_ENDPOINT = `http://default:${adminToken}@127.0.0.1:${guardPort}`; process.env.DYNAMIC_APPS_E2E_FAST = fast ? "1" : "0"; process.env.DYNAMIC_APPS_E2E_BUILD_ONLY = buildOnly ? "1" : "0"; if (fast) { @@ -69,7 +91,9 @@ try { } delete process.env.RIVET_ENGINE; delete process.env.RIVET_RUN_ENGINE; - await import(sanity ? "./sanity.js" : "./verify.js"); + await import( + sanity ? "./sanity.js" : failover ? "./failover.js" : "./verify.js" + ); } finally { await stopEngine(engine); await rm(root, { recursive: true, force: true }); @@ -95,14 +119,18 @@ async function waitUntilHealthy( endpoint: string, process: ReturnType, ): Promise { - const deadline = Date.now() + 30_000; + const deadline = Date.now() + 60_000; let lastError: unknown; while (Date.now() < deadline) { if (process.exitCode !== null) { throw new Error(`Rivet Engine exited with code ${process.exitCode}`); } try { - const response = await fetch(`${endpoint}/health`); + // Health passes before storage routing is ready, so also wait for an + // authenticated read that goes through storage. + const response = await fetch(`${endpoint}/namespaces?limit=1`, { + headers: { authorization: `Bearer ${adminToken}` }, + }); if (response.ok) return; lastError = new Error(`health returned ${response.status}`); } catch (error) { diff --git a/tests/e2e/dynamic-apps/src/sanity.ts b/tests/e2e/dynamic-apps/src/sanity.ts index 5af58f00b..e4f90d739 100644 --- a/tests/e2e/dynamic-apps/src/sanity.ts +++ b/tests/e2e/dynamic-apps/src/sanity.ts @@ -23,7 +23,7 @@ const deployment = await deployApp({ main: "index.js", dependencies: { hono: "4.13.5", - rivetkit: "2.3.29", + rivetkit: "3.0.2", }, }), "index.js": ` @@ -42,9 +42,8 @@ const counter = actor({ }, }, }); -const registry = setup({ use: { counter } }); +export const registry = setup({ use: { counter } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.all("*", () => Response.json({ ok: true, path: "direct" })); export default app; `, diff --git a/tests/e2e/dynamic-apps/src/verify.ts b/tests/e2e/dynamic-apps/src/verify.ts index beb90adb8..3cd85d06f 100644 --- a/tests/e2e/dynamic-apps/src/verify.ts +++ b/tests/e2e/dynamic-apps/src/verify.ts @@ -1,6 +1,17 @@ -import { appsRouter, deployApp } from "@rivet-dev/dynamic-apps"; +import { + appsRouter, + deployApp, + setDynamicAppsLogHandler, +} from "@rivet-dev/dynamic-apps"; import { createClient } from "rivetkit/client"; +// Guest output is otherwise dropped, which hides why an app fails. +setDynamicAppsLogHandler((event) => { + if (event.level === "error" || event.source === "actor") { + console.error(JSON.stringify(event)); + } +}); + const appId = "dynamic-apps-direct-e2e"; const ACTOR_APP_ID = "dynamic-apps-actor-e2e"; const startedAt = performance.now(); @@ -56,14 +67,13 @@ assert( "load leaked isolate state", ); -const actorDeployment = await deployActorFixture(); +const actorDeployment = await deployActorFixture("v1"); const actorClient = createClient({ namespace: actorDeployment.namespace, poolName: actorDeployment.pool, }) as unknown as ActorApplicationClient; -const actor = await actorClient.counter - .getOrCreate([`e2e-${Date.now()}`]) - .connect(); +const actorKey = [`e2e-${Date.now()}`]; +const actor = await actorClient.counter.getOrCreate(actorKey).connect(); let unsubscribe = () => {}; const observedEvent = new Promise((resolve, reject) => { const timeout = setTimeout( @@ -81,7 +91,6 @@ unsubscribe(); const actorSecond = await actor.add(3); const actorCurrent = await actor.inspect(); await actor.dispose(); -await actorClient.dispose(); assert(actorFirst === 2, "actor action returned the wrong initial state"); assert(actorEvent === 2, "actor event returned the wrong state"); assert(actorSecond === 5, "actor action did not preserve state"); @@ -89,7 +98,10 @@ assert(actorCurrent === 5, "actor inspect returned the wrong state"); const actorHttpResponse = await appsRouter.request( `/${ACTOR_APP_ID}/direct-http`, ); -assert(actorHttpResponse.ok, "actor app direct HTTP request failed"); +assert( + actorHttpResponse.ok, + `actor app direct HTTP request failed with ${actorHttpResponse.status}: ${await actorHttpResponse.clone().text()}`, +); const actorHttp = (await actorHttpResponse.json()) as { ok: boolean; workload: string; @@ -99,6 +111,33 @@ assert( "actor app direct HTTP returned the wrong response", ); +// A guest that exits is restarted by its supervisor, and the Engine moves the +// actor to the new envoy with its state intact. +const counterHandle = actorClient.counter.getOrCreate(actorKey); +await counterHandle.crash().catch(() => {}); +const afterCrash = await eventually( + () => counterHandle.inspect(), + (value) => value === 5, + "actor did not recover after its envoy crashed", +); + +// A new release starts its envoy before the previous one drains, and the +// actor keeps its state across the rollout. +const actorRedeployment = await deployActorFixture("v2"); +const redeployedRelease = await eventually( + () => counterHandle.release(), + (value) => value === "v2", + "actor did not move to the redeployed release", +); +const afterRedeploy = await counterHandle.inspect(); +assert(afterRedeploy === 5, "actor state was lost across the redeploy"); +await eventually( + () => connectedNodeVersions(actorRedeployment), + (versions) => versions.length === 1, + "the previous release's envoy did not drain", +); +await actorClient.dispose(); + console.log( JSON.stringify( { @@ -116,6 +155,9 @@ console.log( current: actorCurrent, observedEvent: actorEvent, directHttp: actorHttp, + afterCrash, + redeployedRelease, + afterRedeploy, }, totalMs: performance.now() - startedAt, }, @@ -133,12 +175,15 @@ interface ActorApplicationClient { inspect(): Promise; dispose(): Promise; }>; + inspect(): Promise; + release(): Promise; + crash(): Promise; }; }; dispose(): Promise; } -async function deployActorFixture() { +async function deployActorFixture(marker: string) { return deployApp({ appId: ACTOR_APP_ID, files: { @@ -150,7 +195,7 @@ async function deployActorFixture() { main: "index.js", dependencies: { hono: "4.13.5", - rivetkit: "2.3.29", + rivetkit: "3.0.2", }, }), "index.js": ` @@ -169,12 +214,17 @@ const counter = actor({ inspect(c) { return c.state.count; }, + release() { + return ${JSON.stringify(marker)}; + }, + crash() { + setTimeout(() => process.exit(1), 10); + }, }, }); -const registry = setup({ use: { counter } }); +export const registry = setup({ use: { counter } }); const app = new Hono(); -app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); app.all("*", () => Response.json({ ok: true, workload: "actor-and-direct-http" })); export default app; `, @@ -227,6 +277,50 @@ async function request(path: string): Promise<{ return response.json(); } +/** Polls until `check` passes; recovery and rollout finish asynchronously. */ +async function eventually( + read: () => Promise, + check: (value: T) => boolean, + message: string, + timeoutMs = 60_000, +): Promise { + const deadline = Date.now() + timeoutMs; + let last: unknown; + while (Date.now() < deadline) { + try { + const value = await read(); + if (check(value)) return value; + last = value; + } catch (error) { + last = error; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error(`${message}; last result: ${String(last)}`); +} + +async function connectedNodeVersions(deployment: { + endpoint: string; + namespace: string; + pool: string; +}): Promise { + const url = new URL( + `/pools/${encodeURIComponent(deployment.pool)}/nodes`, + deployment.endpoint, + ); + url.searchParams.set("namespace", deployment.namespace); + const response = await fetch(url, { + headers: { authorization: `Bearer ${process.env.RIVET_TOKEN}` }, + }); + if (!response.ok) throw new Error(`node listing returned ${response.status}`); + const body = (await response.json()) as { + nodes: Array<{ version: number; connected: boolean; stopping: boolean }>; + }; + return body.nodes + .filter((node) => node.connected && !node.stopping) + .map((node) => node.version); +} + function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); }