diff --git a/AGENTS.md b/AGENTS.md index 833e6b7..95204b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ Guidance for agents working in this repository. Prefer the checked-in code and t ## 1. Project - Published on npm as one package, `serverless-objects` (0.13.x, pre-alpha). It contains the `sobjects` CLI, the native engine, and the `serverless-objects/hotcell` and `serverless-objects/autopilot` modules. There is no `@serverless-objects` npm scope; ship new modules as subpath exports of this package. -- Two engines: celld (external, pinned 0.6.2) and the native engine (`sobjects dev --engine native`: in-process, trusted code, node:sqlite per object). Conformance: Cloudflare 17/17 (`test:cloudflare`, deploys to the logged-in account and deletes afterwards), Wrangler 4.150.0 21/21, celld 0.6.2 24/24, native 23/23 (hibernation runs everywhere but Wrangler; facets pass on Wrangler and celld but not the native engine; a schedule across restart runs on celld and native; the PartyServer suite runs on Wrangler, celld and native but not Cloudflare). +- Two engines: celld (external, pinned 0.6.2) and the native engine (`sobjects dev --engine native`: in-process, trusted code, node:sqlite per object). Conformance: Cloudflare 17/17 (`test:cloudflare`, deploys to the logged-in account and deletes afterwards), Wrangler 4.150.0 21/21, celld 0.6.2 24/24, native 23/23 (hibernation runs everywhere but Wrangler; facets pass on Wrangler and celld but not the native engine; a schedule across restart runs on celld and native; the PartyServer suite runs on Wrangler, celld and native but not Cloudflare). The Agents app also passes 6/6 through `sobjects deploy`/`up` (`test:product`, not in CI). - ACME HTTP-01 is verified only against a local Pebble server. Point-in-time restore is not available on celld 0.6. The native engine has bucket backups (`--backup-bucket`; `--backup-mode durable` holds each result until its writes are in the bucket and adds Cloudflare's point-in-time recovery API, back `--backup-retention-days`), several nodes per bucket (`--node-name`, `--peer-listen`), and optional worker threads (`--threads`; fault and CPU isolation, not a security boundary). A `[native]` table in `sobjects.toml` (instead of `[celld]`) makes `sobjects up` run it as `sobjects dev --engine native` in a child process; `[admin]` isn't supported with it yet. Roadmap targets are not guarantees. Serverless Objects is a self-hostable operating layer for Cloudflare Workers and Durable Objects applications, aimed at coding-agent infrastructure. It is JavaScript (ES modules) on Node.js >=22, managed with npm workspaces; the product is the `sobjects` CLI (workspace package `serverless-objects`). The CLI supervises the external celld runtime (pinned v0.6.2) for production nodes and also ships a Node-native engine for trusted code. Cloudflare Workers/Wrangler APIs are the compatibility contract. The dashboard is plain HTML/CSS/JS; there is no application framework or TypeScript codebase. Status: pre-alpha. @@ -24,6 +24,7 @@ Run from the repository root unless a command says otherwise. Node.js 22+ is req | Benchmark | `npm run bench --workspace=sobjects-conformance -- --target native` (or `celld`, `wrangler`, `--url URL`) | Runs `bench-app/` and prints latency/throughput; not run in CI. Results and durability caveats in `docs/benchmarks.md`. | | Conformance (Cloudflare) | `npm run test:cloudflare --workspace=sobjects-conformance` | Deploys both apps with `wrangler deploy` to the account Wrangler is logged in to, runs every check, then deletes the Workers (`--keep-deployment` keeps them). Outward-facing: needs the account owner's OK; not run in CI. | | Conformance (native) | `npm run test:native --workspace=sobjects-conformance` (add `-- --native-threads 3` for threads) | Runs them against the native engine from this checkout; CI runs both. | +| Product path (Agents app) | `npm run test:product --workspace=sobjects-conformance -- --local-s3` | Deploys `agents-app` with `sobjects deploy` and serves it with `sobjects up --detach` behind TLS ingress, then runs the Agents SDK checks against the ingress. `--local-s3` starts a disposable SeaweedFS bucket; needs Docker and celld, not run in CI. | | Native engine | `npm exec --workspace=serverless-objects -- sobjects dev [project] --engine native` | Runs a project in Node with no celld; state under `/.sobjects/native`. | | Portability check | `npm exec --workspace=serverless-objects -- sobjects build [project] --strict` | Fails if the app imports Node.js built-ins that don't work on Cloudflare Workers. | | CLI help | `npm exec --workspace=serverless-objects -- sobjects --help` | Uses the workspace CLI entry point. | @@ -54,7 +55,7 @@ CI: `.github/workflows/ci.yml` runs `npm ci`, `npm test`, and the Wrangler and n | `packages/cli/autopilot/` | `serverless-objects/autopilot` (and `/autopilot/cell`): `RunObject`/`RunRegistry`/`AutopilotCellRun`. Runtime-independent logic in `run-store.js`, `run-host.js`, `registry-store.js` and `cell-executor.js` over an `{exec, transaction}` SQL adapter; tests (`test/autopilot-*.test.js`) use `node:sqlite`. | | `deploy/compose/` | Dockerfile and Compose bundle for a single node; pins the npm CLI version via `SOBJECTS_VERSION`. | | `examples/` | Runnable Wrangler projects (not workspaces) that import the packages through the root `node_modules`. | -| `packages/conformance/` | Private workspace: conformance apps (`app/` core, `agents-app/` Agents SDK, `party-app/` PartyServer), runner (`src/run.js`) for Wrangler, celld and native, and runner tests. | +| `packages/conformance/` | Private workspace: conformance apps (`app/` core, `agents-app/` Agents SDK, `party-app/` PartyServer), runners (`src/run.js` for Wrangler, celld and native; `src/product.js` for `sobjects deploy`/`up`), and runner tests. | | `sobjects.example.toml` | Safe starter configuration; copy to the ignored, machine-specific `sobjects.toml`. | | `docs/conformance/` | Recorded Workers/celld compatibility findings (`m0-celld.md`) and conformance results (`results.md`); consult before changing runtime assumptions. | | `docs/install.md`, `docs/porting-from-cloudflare.md`, `docs/compatibility.md` | User guides and the supported/unsupported table; keep them in step with conformance results. | diff --git a/README.md b/README.md index a096e39..42663ba 100644 --- a/README.md +++ b/README.md @@ -90,11 +90,11 @@ State survives `down` and `up` because it lives in the bucket. The [install guid - **A loopback dashboard and admin API.** Node load, the objects in each namespace, a key-value browser and read-only SQL console per object, eviction, logical JSON export, and Prometheus `/metrics`. - **A Hotcell `Sandbox` binding** ([`serverless-objects/hotcell`](docs/hotcell-binding.md)). It has the Cloudflare Sandbox SDK 0.x call shape and reattaches to its sandbox after the object is evicted. With egress enabled, sandboxes get gateway tokens, never real provider keys. - **Autopilot runs as objects** ([`serverless-objects/autopilot`](docs/autopilot.md)). One Durable Object per run holds its state machine, budgets, hash-only tool records, durable wake timers and a Camouflage session log that streams from a cursor. A registry per workspace lists and reconciles runs. `AutopilotCellRun` executes the task with Autopilot in a Hotcell cell. Stop the node mid-run, and after restart the object resumes from its saved cursor while the cell keeps working. -- **A conformance suite** ([`packages/conformance`](packages/conformance)) that runs the same apps under `wrangler dev` and celld, so engine differences show up as failing checks. +- **A conformance suite** ([`packages/conformance`](packages/conformance)) that runs the same apps under `wrangler dev` and celld, so engine differences show up as failing checks, and runs the Agents app through `sobjects deploy`/`up` behind TLS ingress. ## Compatibility -Cloudflare's APIs are the contract. The current [conformance results](docs/conformance/results.md) pass every check on real Cloudflare (17/17), Wrangler 4.150.0 (21/21), celld 0.6.2 (24/24) and the native engine (23/23): the same apps, unchanged. They cover Durable Object IDs, KV and SQL storage, transactions, input gates, RPC, alarms (including across a restart), WebSockets with hibernation on celld, facets on Wrangler and celld, an Agents SDK suite (state, SQL, schedules including one across a restart, addressing and `@callable()` RPC), and a PartyServer suite (storage, alarms, room routing, broadcast and hibernation). The Cloudflare run predates the PartyServer suite. +Cloudflare's APIs are the contract. The current [conformance results](docs/conformance/results.md) pass every check on real Cloudflare (17/17), Wrangler 4.150.0 (21/21), celld 0.6.2 (24/24) and the native engine (23/23): the same apps, unchanged. They cover Durable Object IDs, KV and SQL storage, transactions, input gates, RPC, alarms (including across a restart), WebSockets with hibernation on celld, facets on Wrangler and celld, an Agents SDK suite (state, SQL, schedules including one across a restart, addressing and `@callable()` RPC), and a PartyServer suite (storage, alarms, room routing, broadcast and hibernation). The Cloudflare run predates the PartyServer suite. The Agents app also passes 6/6 through `sobjects deploy` and `sobjects up` behind TLS ingress (`test:product`). Not covered yet: sockets across a cell move between nodes, PartyServer on Cloudflare or through `sobjects deploy`, Agents SDK chat, MCP and Workflows, and Cloudflare-hosted production behavior. Facets pass on Wrangler and celld but are not implemented by the native engine. Point-in-time restore isn't available on celld 0.6; the native engine has Cloudflare's point-in-time recovery API in durable mode. The [compatibility table](docs/compatibility.md) has the details, including Containers and `@cloudflare/sandbox` 1.0 on celld. The [porting guide](docs/porting-from-cloudflare.md) covers moving an existing project. @@ -104,7 +104,7 @@ Not covered yet: sockets across a cell move between nodes, PartyServer on Cloudf |---|---| | [`packages/cli`](packages/cli) | The `serverless-objects` npm package: the `sobjects` CLI (`src/`), the Hotcell Sandbox binding (`hotcell/`, imported as `serverless-objects/hotcell`) and Autopilot run objects (`autopilot/`, imported as `serverless-objects/autopilot`). Its README is the CLI reference. | | [`examples/autopilot-runs`](examples/autopilot-runs) | An HTTP demo of run objects: wake after restart, event streams, reconcile. | -| [`packages/conformance`](packages/conformance) | Conformance apps and the Wrangler and celld runners. | +| [`packages/conformance`](packages/conformance) | Conformance apps and the Wrangler, celld, native and product-path runners. | | [`deploy/compose`](deploy/compose) | Dockerfile and Compose bundle for a single node, with an optional local SeaweedFS bucket. | | [`docs/`](docs) | Install, porting and compatibility guides, and recorded conformance results. | diff --git a/docs/compatibility.md b/docs/compatibility.md index da523f5..eec3a81 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -18,7 +18,7 @@ This table distinguishes behavior exercised by the project from functionality de | WebSocket hibernation/eviction | Tested on celld | Same-node hibernation passed on celld 0.6.2: the object was evicted with a socket open, and the next message reached a new instance with tags and attachment intact. Not run on Wrangler (no eviction control). celld documents that sockets may close when a cell moves between nodes; that is not tested. | | Facets | Tested on Wrangler and celld | `ctx.facets.get` with a class taken from `ctx.exports` passed on Wrangler 4.150.0 and celld 0.6.2: state by name, isolation between facets, storage separate from the parent, and alarms refused. The native engine does not implement `ctx.facets`, so the check is skipped there. | | Durable Object migrations | Limited upstream support | celld 0.6.2 accepts `tag` and `new_sqlite_classes`; rename/delete/transfer migrations are rejected. | -| Agents SDK | Partial | A minimal `agents` 0.28.1 app was deployed through `sobjects deploy` and served by `sobjects up` behind TLS ingress (celld 0.6.2, SeaweedFS): routing, `setState`, `this.sql`, `schedule()` (including one pending across a node restart), and the WebSocket identity/state protocol matched `wrangler dev`. Callable RPC passes in the conformance suite on celld and the native engine (Agents SDK client protocol), and a delayed schedule now survives a process restart there, but neither has been exercised through `sobjects deploy`/`up`; chat agents, MCP, Workflows and the official samples have not been run through the CLI. | +| Agents SDK | Partial | A minimal `agents` 0.28.1 app was deployed through `sobjects deploy` and served by `sobjects up` behind TLS ingress (celld 0.6.2, SeaweedFS): routing, `setState`, `this.sql`, `schedule()` (including one pending across a node restart), the WebSocket identity/state protocol, and `@callable()` RPC over WebSocket matched `wrangler dev`. `npm run test:product` repeats the state, SQL, schedules, addressing, callable RPC and schedule checks against that deployment (6/6). Chat agents, MCP, Workflows and the official samples have not been run through the CLI. | | PartyServer | Tested on Wrangler, celld and the native engine | `partyserver` 0.5.10 in its own conformance app: `getServerByName` and `this.name` from `ctx.id.name`, `onStart`, `this.sql`, alarms, `/parties//` routing, `broadcast()` to two connections, connection attachments, and hibernation across idle eviction (celld and native only; Wrangler's local runtime gives the runner no eviction control). Not run on Cloudflare, and not through `sobjects deploy`/`up`. The native engine needed workerd's `READY_STATE_*` ready-state constants on the global `WebSocket` for PartyServer's connection manager. See [results](conformance/results.md). | | Cloudflare-hosted production behavior | Not tested | Local Wrangler and celld results do not certify production Cloudflare behavior. | diff --git a/docs/conformance/results.md b/docs/conformance/results.md index ab358eb..41dcec2 100644 --- a/docs/conformance/results.md +++ b/docs/conformance/results.md @@ -43,12 +43,17 @@ The native engine column is from `npm run test:native` on the same host (29 Oct Every column above is one local run on macOS arm64. CI runs the Wrangler and native suites on Ubuntu x64 (Node 22) on every change, and builds the linux/amd64 Docker image and checks that `sobjects` and `celld` start in it; it does not run `test:celld` or `test:cloudflare`, and it records no results. Linux arm64 has no conformance evidence beyond the Compose stack on Docker Desktop. Treat the table as macOS arm64 evidence plus unrecorded Ubuntu x64 CI coverage, not as a cross-platform claim. +## Product path + +`npm run test:product --workspace=sobjects-conformance` deploys `agents-app` with `sobjects deploy` and serves it with `sobjects up --detach` behind TLS ingress, then runs the Agents SDK checks against the ingress rather than a runner's local server. One run on 2 Nov 2026 (macOS arm64, celld 0.6.2, SeaweedFS started with `--local-s3`) passed 6/6: state, SQL, schedules, addressing, the WebSocket client protocol with `@callable()` RPC, and a delayed schedule. It is not in CI because it needs Docker, a bucket and celld. + ## Not covered This v0 run does not test hibernation on Wrangler, the alarm-across-restart check on Cloudflare or Wrangler, sockets across a cell move between nodes, all compatibility flags, or Agents SDK chat agents, MCP, Workflows and streaming RPC. PartyServer is covered by its own suite on Wrangler, celld and the native engine, but not on Cloudflare, -and not through `sobjects deploy`. These runners use `wrangler dev` and `celld dev` directly; they do not -go through `sobjects deploy`. Those remain separate +and not through `sobjects deploy`. The Wrangler, celld and native runners use +`wrangler dev` and `celld dev` directly; only `test:product` goes through +`sobjects deploy`/`up`, and only for the Agents app. Those remain separate conformance and product-level gates. diff --git a/docs/porting-from-cloudflare.md b/docs/porting-from-cloudflare.md index bca4623..8601338 100644 --- a/docs/porting-from-cloudflare.md +++ b/docs/porting-from-cloudflare.md @@ -55,6 +55,6 @@ Before switching traffic, check for: - Assumptions about production networking, service bindings, outbound connections, Cache, or global coordination. - Durable Object migration operations beyond adding SQLite classes. - WebSocket hibernation, facets, cross-isolate RPC, or behavior across a cell move. Hibernation and the Agents SDK client protocol (including `@callable()` RPC over WebSocket) pass in conformance on celld and the native engine; facets pass on Wrangler and celld but not on the native engine; cell moves are not covered. -- Whether the app has been run through the actual `sobjects` CLI. A minimal Agents SDK app (state, SQL, schedules, WebSocket protocol) has run through `sobjects deploy` and `sobjects up`; the official samples, chat agents, MCP and Workflows have not. Callable RPC passes in the conformance suite but has not been exercised through `sobjects deploy`/`up`. +- Whether the app has been run through the actual `sobjects` CLI. A minimal Agents SDK app (state, SQL, schedules, addressing, WebSocket protocol and `@callable()` RPC) has run through `sobjects deploy` and `sobjects up`, and `npm run test:product` repeats those checks against that deployment; the official samples, chat agents, MCP and Workflows have not. Do not infer production Cloudflare behavior from local Wrangler results, or infer full celld compatibility from one passing sample. Record any mismatch as a conformance case and keep unsupported behavior visible. diff --git a/packages/conformance/README.md b/packages/conformance/README.md index 4a41b1b..7428c3d 100644 --- a/packages/conformance/README.md +++ b/packages/conformance/README.md @@ -36,3 +36,23 @@ with the documented Workers contract. See [the recorded results](../../docs/conformance/results.md) for tested versions and coverage boundaries. A green result is evidence for these cases and versions only; it is not a claim of complete Workers compatibility. + +## Product path + +The runners above start `wrangler dev` or `celld dev` directly. `src/product.js` +instead exercises the product path for the Agents app: it copies `agents-app/`, +writes an `sobjects.toml` with a self-signed TLS certificate, deploys with +`sobjects deploy`, starts the node with `sobjects up --detach`, and runs the +state, SQL, schedules, addressing, callable RPC and schedule checks against the +TLS ingress. + +```sh +npm run test:product --workspace=sobjects-conformance -- --local-s3 +``` + +`--local-s3` starts a disposable SeaweedFS container and creates the bucket; +without it, pass `--bucket`, `--endpoint` and credentials in the environment. +The ingress listens on `--port` (default 18443), with celld, its operator +listener and the admin API on the next three ports. `--keep` leaves the node, +bucket and scratch directory running. It is not in CI because it needs Docker, +a bucket and celld. diff --git a/packages/conformance/package.json b/packages/conformance/package.json index 304aabf..af1bca9 100644 --- a/packages/conformance/package.json +++ b/packages/conformance/package.json @@ -8,6 +8,7 @@ "test:wrangler": "node src/run.js --target wrangler", "test:celld": "node src/run.js --target celld", "test:native": "node src/run.js --target native", + "test:product": "node src/product.js", "bench": "node src/bench.js", "test:cloudflare": "node src/run.js --target cloudflare" }, diff --git a/packages/conformance/src/product.js b/packages/conformance/src/product.js new file mode 100644 index 0000000..d4b2695 --- /dev/null +++ b/packages/conformance/src/product.js @@ -0,0 +1,310 @@ +import { spawn } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { request as httpsRequest } from "node:https"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { runAgentsClientCheck, runAgentsScheduleCheck, runCases } from "./run.js"; + +const PACKAGE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const AGENTS_APP = path.join(PACKAGE_DIR, "agents-app"); +const SOBJECTS_BIN = path.resolve(PACKAGE_DIR, "..", "cli", "bin", "sobjects.mjs"); +const DEFAULT_CELLD_BIN = path.join(os.homedir(), ".local/share/serverless-objects/engines/celld-0.6.2/celld"); +const LOCAL_S3_IMAGE = "chrislusf/seaweedfs:4.48"; +const LOCAL_S3_ACCESS_KEY = "sobjects"; +const LOCAL_S3_SECRET_KEY = "sobjects-secret"; + +export function parseArgs(args) { + const options = { + bucket: "s3://sobjects-product", + endpoint: undefined, + region: "us-east-1", + port: 18_443, + timeoutMs: 60_000, + celldBin: process.env.CELLD_BIN ?? DEFAULT_CELLD_BIN, + localS3: false, + keep: false, + check: false, + url: undefined, + }; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (arg === "--bucket") options.bucket = args[++index]; + else if (arg === "--endpoint") options.endpoint = args[++index]; + else if (arg === "--region") options.region = args[++index]; + else if (arg === "--port") options.port = Number(args[++index]); + else if (arg === "--timeout") options.timeoutMs = Number(args[++index]); + else if (arg === "--celld-bin") options.celldBin = args[++index]; + else if (arg === "--local-s3") options.localS3 = true; + else if (arg === "--keep") options.keep = true; + else if (arg === "--check") options.check = true; + else if (arg === "--url") options.url = args[++index]; + else if (arg === "--help" || arg === "-h") options.help = true; + else throw new Error(`Unknown option: ${arg}`); + } + + if (options.help) return options; + if (!/^s3:\/\/[^/\s]+(?:\/[^\s]*)?$/.test(options.bucket)) throw new Error("--bucket must be an s3:// URI with a bucket name"); + if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65_532) throw new Error("--port must be an integer from 1 to 65532"); + if (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1_000) throw new Error("--timeout must be at least 1000 milliseconds"); + if (options.check && !options.url) throw new Error("--check requires --url"); + if (options.endpoint !== undefined) { + let url; + try { + url = new URL(options.endpoint); + } catch { + throw new Error("--endpoint must be a valid http(s) URL"); + } + if (!["http:", "https:"].includes(url.protocol)) throw new Error("--endpoint must use http or https"); + } + return options; +} + +function usage() { + return [ + "Usage: node src/product.js [options]", + "", + "Deploys the Agents app with 'sobjects deploy' and serves it with", + "'sobjects up' behind TLS ingress, then runs the Agents SDK checks against", + "that deployment. Needs a bucket and celld; --local-s3 starts SeaweedFS.", + "", + "Options:", + " --bucket URI Bucket to deploy to (default: s3://sobjects-product)", + " --endpoint URL S3-compatible endpoint (default: --local-s3's SeaweedFS)", + " --region REGION Bucket region (default: us-east-1)", + " --port PORT Ingress port (default: 18443; celld, operator and admin use +1 to +3)", + " --timeout MS Startup timeout (default: 60000)", + " --celld-bin PATH celld executable (or set CELLD_BIN)", + " --local-s3 Start a disposable SeaweedFS container and create the bucket", + " --keep Leave the node, bucket and scratch directory running", + " --check --url URL Internal: run the checks against URL and print JSON", + ].join("\n"); +} + +function run(command, args, { env = process.env, cwd = PACKAGE_DIR, capture = false } = {}) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + cwd, + env, + stdio: capture ? ["ignore", "pipe", "pipe"] : "inherit", + }); + let output = ""; + if (capture) { + child.stdout.on("data", (chunk) => (output += chunk)); + child.stderr.on("data", (chunk) => (output += chunk)); + } + child.on("error", reject); + child.on("close", (code) => { + if (code === 0) resolve(output); + else reject(new Error(`${path.basename(command)} ${args.join(" ")} exited ${code}${output ? `:\n${output}` : ""}`)); + }); + }); +} + +function sobjects(args, env) { + return run(process.execPath, [SOBJECTS_BIN, ...args], { env: { ...process.env, ...env } }); +} + +async function startLocalS3(options) { + const name = `sobjects-product-s3-${process.pid}`; + const bucket = options.bucket.replace(/^s3:\/\//, "").split("/")[0]; + const script = [ + 'printf \'{"identities":[{"name":"sobjects","credentials":[{"accessKey":"%s","secretKey":"%s"}],"actions":["Admin","Read","Write","List","Tagging"]}]}\'', + '"$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" > /tmp/s3.json', + "&& exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json", + ].join(" "); + await run("docker", [ + "run", "-d", "--name", name, "--entrypoint", "/bin/sh", + "-p", "127.0.0.1:18333:8333", "-p", "127.0.0.1:19333:9333", + "-e", `AWS_ACCESS_KEY_ID=${LOCAL_S3_ACCESS_KEY}`, + "-e", `AWS_SECRET_ACCESS_KEY=${LOCAL_S3_SECRET_KEY}`, + LOCAL_S3_IMAGE, "-c", script, + ], { capture: true }); + + const endpoint = "http://127.0.0.1:18333"; + const deadline = Date.now() + options.timeoutMs; + while (Date.now() < deadline) { + try { + // SeaweedFS answers an unauthenticated request with 403 once S3 is up. + await fetch(endpoint, { signal: AbortSignal.timeout(1_000) }); + break; + } catch { + await new Promise((resolve) => setTimeout(resolve, 250)); + } + } + await run("docker", ["exec", name, "sh", "-c", `echo "s3.bucket.create -name ${bucket}" | weed shell -master=127.0.0.1:9333`], { capture: true }); + return { name, endpoint }; +} + +async function generateCertificate(directory) { + await mkdir(directory, { recursive: true, mode: 0o700 }); + const cert = path.join(directory, "fullchain.pem"); + const key = path.join(directory, "privkey.pem"); + await run("openssl", [ + "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-days", "30", + "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost", + "-keyout", key, "-out", cert, + ], { capture: true }); + return { cert, key }; +} + +function configSource({ bucket, endpoint, region, port, cert, key }) { + const lines = [ + "[celld]", + `bucket = "${bucket}"`, + ]; + if (endpoint) lines.push(`endpoint = "${endpoint}"`); + if (region) lines.push(`region = "${region}"`); + lines.push( + `listen = "127.0.0.1:${port + 1}"`, + `internal_listen = "127.0.0.1:${port + 2}"`, + "", + "[ingress]", + `listen = "127.0.0.1:${port}"`, + 'access_log = "-"', + "", + "[ingress.tls]", + `cert = "${cert}"`, + `key = "${key}"`, + "", + "[[ingress.routes]]", + 'hostname = "localhost"', + "", + "[admin]", + `listen = "127.0.0.1:${port + 3}"`, + "", + ); + return lines.join("\n"); +} + +async function waitForIngress(baseUrl, cert, timeoutMs) { + const url = new URL("/.well-known/sobjects/health", baseUrl); + const ca = readFileSync(cert); + const deadline = Date.now() + timeoutMs; + let lastError; + while (Date.now() < deadline) { + try { + const status = await new Promise((resolve, reject) => { + const request = httpsRequest({ + host: url.hostname, + port: url.port, + path: url.pathname, + ca, + servername: url.hostname, + timeout: 2_000, + }, (response) => { + response.resume(); + resolve(response.statusCode); + }); + request.on("timeout", () => request.destroy(new Error("health request timed out"))); + request.on("error", reject); + request.end(); + }); + if (status === 200) return; + lastError = new Error(`health returned HTTP ${status}`); + } catch (error) { + lastError = error; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error(`Ingress did not become healthy within ${timeoutMs}ms${lastError ? `: ${lastError.message}` : ""}`); +} + +// The checks run in a child process so NODE_EXTRA_CA_CERTS trusts the +// self-signed certificate from the moment Node starts. +async function runChecks(baseUrl, cert) { + const output = await run(process.execPath, [fileURLToPath(import.meta.url), "--check", "--url", baseUrl], { + env: { ...process.env, NODE_EXTRA_CA_CERTS: cert }, + capture: true, + }); + const line = output.trim().split("\n").at(-1); + return JSON.parse(line); +} + +async function check(baseUrl) { + const results = await runCases(baseUrl); + const record = async (name, fn) => { + try { + results.push({ name, ...await fn() }); + } catch (error) { + results.push({ name, pass: false, detail: String(error?.message ?? error) }); + } + }; + await record("client-protocol", () => runAgentsClientCheck(baseUrl)); + await record("schedule-fires", () => runAgentsScheduleCheck(baseUrl)); + return results; +} + +async function main(args) { + let options; + try { + options = parseArgs(args); + } catch (error) { + console.error(error.message); + console.error(usage()); + process.exitCode = 2; + return; + } + if (options.help) { + console.log(usage()); + return; + } + if (options.check) { + const results = await check(options.url); + console.log(JSON.stringify(results)); + if (results.some((result) => !result.pass)) process.exitCode = 1; + return; + } + + await mkdir(path.join(PACKAGE_DIR, ".runs"), { recursive: true }); + const scratchDir = await mkdtemp(path.join(PACKAGE_DIR, ".runs", "product-")); + const stateDirectory = path.join(scratchDir, "state"); + const projectDir = path.join(scratchDir, "agents"); + let localS3; + let started = false; + const env = { + SOBJECTS_STATE_DIR: stateDirectory, + AWS_REGION: options.region, + }; + if (options.celldBin) env.SOBJECTS_CELLD_BIN = options.celldBin; + + try { + if (options.localS3) { + localS3 = await startLocalS3(options); + options.endpoint ??= localS3.endpoint; + env.AWS_ACCESS_KEY_ID ??= process.env.AWS_ACCESS_KEY_ID ?? LOCAL_S3_ACCESS_KEY; + env.AWS_SECRET_ACCESS_KEY ??= process.env.AWS_SECRET_ACCESS_KEY ?? LOCAL_S3_SECRET_KEY; + } + await cp(AGENTS_APP, projectDir, { recursive: true }); + const { cert, key } = await generateCertificate(path.join(projectDir, "tls")); + await writeFile(path.join(projectDir, "sobjects.toml"), configSource({ ...options, cert, key })); + + console.log(`Deploying ${projectDir} to ${options.bucket}`); + await sobjects(["deploy", projectDir], env); + + console.log("Starting the node with sobjects up --detach"); + await sobjects(["up", "--config", path.join(projectDir, "sobjects.toml"), "--detach"], env); + started = true; + + const baseUrl = `https://localhost:${options.port}`; + await waitForIngress(baseUrl, cert, options.timeoutMs); + const results = await runChecks(baseUrl, cert); + + console.log("\nProduct-path results — sobjects deploy + sobjects up"); + for (const result of results) console.log(`${result.pass ? "PASS" : "FAIL"} ${result.name}: ${result.detail}`); + const failed = results.filter((result) => !result.pass); + console.log(`${results.length - failed.length}/${results.length} checks passed`); + if (failed.length) process.exitCode = 1; + } finally { + if (started && !options.keep) await sobjects(["down"], env).catch((error) => console.error(`Could not stop the node: ${error.message}`)); + if (localS3 && !options.keep) await run("docker", ["rm", "-f", localS3.name], { capture: true }).catch(() => {}); + if (options.keep) console.log(`Kept ${scratchDir}${localS3 ? ` and container ${localS3.name}` : ""}.`); + else await rm(scratchDir, { recursive: true, force: true }); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + await main(process.argv.slice(2)); +} diff --git a/packages/conformance/src/run.js b/packages/conformance/src/run.js index 200672f..a45c734 100644 --- a/packages/conformance/src/run.js +++ b/packages/conformance/src/run.js @@ -151,7 +151,7 @@ export async function waitForServer(child, baseUrl, timeoutMs) { throw new Error(`Target did not become ready within ${timeoutMs}ms${lastError ? `: ${lastError.message}` : ""}`); } -async function runCases(baseUrl) { +export async function runCases(baseUrl) { const listResponse = await fetch(`${baseUrl}/cases`, { signal: AbortSignal.timeout(5_000) }); if (!listResponse.ok) throw new Error(`/cases returned HTTP ${listResponse.status}`); const names = await listResponse.json(); @@ -241,7 +241,7 @@ async function runWebSocketCheck(baseUrl) { } } -async function runAgentsClientCheck(baseUrl) { +export async function runAgentsClientCheck(baseUrl) { if (typeof WebSocket !== "function") throw new Error("This Node.js version does not provide the WebSocket client API"); const name = `client-${Date.now()}`; const url = new URL(`/agents/probe/${name}`, baseUrl); @@ -289,7 +289,7 @@ async function runAgentsClientCheck(baseUrl) { } } -async function runAgentsScheduleCheck(baseUrl) { +export async function runAgentsScheduleCheck(baseUrl) { const response = await fetch(`${baseUrl}/schedule/arm?seconds=2`, { signal: AbortSignal.timeout(5_000) }); if (!response.ok) throw new Error(`/schedule/arm returned HTTP ${response.status}`); const deadline = Date.now() + 20_000; diff --git a/packages/conformance/test/product.test.js b/packages/conformance/test/product.test.js new file mode 100644 index 0000000..6b12c51 --- /dev/null +++ b/packages/conformance/test/product.test.js @@ -0,0 +1,35 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { parseArgs } from "../src/product.js"; + +test("product runner defaults to a local ingress and the pinned celld", () => { + const options = parseArgs([]); + assert.equal(options.bucket, "s3://sobjects-product"); + assert.equal(options.port, 18_443); + assert.equal(options.timeoutMs, 60_000); + assert.equal(options.localS3, false); + assert.equal(options.keep, false); + assert.equal(options.check, false); +}); + +test("product runner validates the bucket, port, timeout and endpoint", () => { + assert.throws(() => parseArgs(["--bucket", "sobjects-product"]), /s3:\/\/ URI/); + assert.throws(() => parseArgs(["--port", "0"]), /--port/); + assert.throws(() => parseArgs(["--port", "65534"]), /--port/); + assert.throws(() => parseArgs(["--timeout", "5"]), /--timeout/); + assert.throws(() => parseArgs(["--endpoint", "ftp://example.com"]), /http or https/); + assert.throws(() => parseArgs(["--endpoint", "not a url"]), /valid http\(s\) URL/); +}); + +test("product runner accepts a bucket endpoint and local S3", () => { + const options = parseArgs(["--local-s3", "--endpoint", "http://127.0.0.1:18333", "--bucket", "s3://other", "--port", "19000"]); + assert.equal(options.localS3, true); + assert.equal(options.endpoint, "http://127.0.0.1:18333"); + assert.equal(options.bucket, "s3://other"); + assert.equal(options.port, 19_000); +}); + +test("check mode requires a URL", () => { + assert.throws(() => parseArgs(["--check"]), /--check requires --url/); + assert.equal(parseArgs(["--check", "--url", "https://localhost:18443"]).url, "https://localhost:18443"); +});