diff --git a/.changeset/plain-ports-listen.md b/.changeset/plain-ports-listen.md new file mode 100644 index 000000000..827d6743a --- /dev/null +++ b/.changeset/plain-ports-listen.md @@ -0,0 +1,5 @@ +--- +"@cartesi/mock-verifying-paymaster": patch +--- + +listen on the port given by `PORT`, 3001 by default diff --git a/.changeset/quiet-hosts-run.md b/.changeset/quiet-hosts-run.md new file mode 100644 index 000000000..7ea4fa49f --- /dev/null +++ b/.changeset/quiet-hosts-run.md @@ -0,0 +1,5 @@ +--- +"@cartesi/cli": minor +--- + +run the local environment of `cartesi run` as processes of the host instead of docker containers: anvil, a throwaway postgres (from `@embedded-postgres`), the rollups node, the PRT nodes and the optional services, behind a proxy served by the CLI, with everything they keep removed when the environment stops. The explorer service, which only exists as a docker image, is no longer available, and `--cpus` and `--memory` are ignored diff --git a/CLAUDE.md b/CLAUDE.md index 8a488926e..9019b4e1a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,8 +50,8 @@ The CLI build pipeline (`apps/cli`): `clean` → `codegen` (wagmi ABI generation - **`commands/`** — Each file exports a `create*Command()` function returning a Commander command. Main commands: `build`, `run`, `deploy`, `send`, `deposit`, `create`, `doctor`, `shell`, `clean`, `hash`, `logs`, `status`, `address-book`, `foreclose`, `refund`, `withdraw`. - **`builder/`** — Drive builder implementations (directory, docker, tar, empty, none). Each builder produces ext2 or SquashFS filesystems for Cartesi Machine drives. -- **`compose/`** — Docker Compose service definitions generated as TypeScript objects (anvil, node, bundler, database, paymaster, proxy, explorer, etc.). -- **`exec/`** — Wrappers around subprocess execution (cartesi-machine, rollups) using `execa`. +- **`host/`** — The local environment of `cartesi run`, as processes of the host (no docker): `environment.ts` starts and stops it, `process.ts` runs each service in its own process group with its output in a log file, `state.ts` keeps what other commands read (`environment.json` in a directory of the system temporary directory, removed on stop), `proxy.ts` serves every service behind one port, and `anvil.ts`, `postgres.ts` (the binaries of `@embedded-postgres`), `node.ts`, `prt-node.ts` and `services.ts` describe the services. +- **`exec/`** — Wrappers around subprocess execution (cartesi-machine, rollups) using `execa`. `node-container.ts` runs `cartesi-rollups-cli` and the other node tools with the environment of the running node. - **`config.ts`, `config/`** — `config.ts` is the barrel the rest of the CLI imports; `config/` holds the types, defaults, errors and the parsers. An application is configured by a `cartesi.config.ts` file exporting `defineConfig({ ... })`, or by the same configuration as plain data in `cartesi.config.json`, `cartesi.config.yaml` or `cartesi.config`; `config/load.ts` finds and reads it, `config/normalize.ts` validates it, and `config/toml/` parses the deprecated `cartesi.toml`. - **`contracts.ts`** — Generated contract addresses and ABI bindings (via `@wagmi/cli`). - **`wallet.ts`** — Wallet utilities using `viem` for Ethereum interaction. diff --git a/apps/cli/README.md b/apps/cli/README.md index ea339892c..06e81102b 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -18,6 +18,39 @@ cartesi --help More documentation at [https://docs.cartesi.io](https://docs.cartesi.io). +## Local development environment + +`cartesi run` runs the local environment as processes of the host, with no +docker: anvil for the devnet, a throwaway postgres for the node, the rollups +node, and the PRT nodes and optional services it is asked for, behind a single +port the CLI serves itself. `cartesi build` still uses docker to build the +drives of the machine. + +It needs these tools in the `PATH`. `cartesi doctor` checks each one, and its +version; `cartesi run` names every missing one before it starts anything, and +warns of a version it is not tested with: + +| Tool | Package | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | +| `anvil` | [foundry](https://getfoundry.sh) 1.5.1 | +| `cartesi-rollups-node`, `cartesi-rollups-cli` | [rollups-node](https://github.com/cartesi/rollups-node/releases) 2.0.0-alpha.14 | +| `cartesi-jsonrpc-machine`, `cartesi-rollups-machine-tool` | [machine-emulator](https://github.com/cartesi/machine-emulator/releases) 0.22.0 | +| `cartesi-sling-node` (with `--prt` and a sling node) | [dave](https://github.com/cartesi/dave/releases) 3.0.0-alpha.6 | +| `alto`, `mock-verifying-paymaster`, `passkey-server` (with `--services`) | npm | +| `initdb`, `postgres` (standalone binary only) | postgres 18 | + +The npm package ships postgres, through `@embedded-postgres`; the standalone +binaries use the one of the host. The devnet, a state dump of anvil with the +Cartesi contracts deployed, is downloaded on first use, checked against its +checksum, and cached; `CARTESI_DEVNET_STATE` points at another one. + +Everything else the environment keeps (the database, the logs, the data of the +PRT nodes and of the withdrawals) lives in one directory of the temporary +directory of the system, removed when the environment stops: every process of +the environment is stopped along with the CLI that started it, which owns it. +A CLI that is killed (`kill -9`) can't clean up, and the next `cartesi run` of +the project stops what it left behind. The project itself is only read. + ## Configuration An application is configured by a `cartesi.config.ts` file at its root, which @@ -185,8 +218,9 @@ A few things to keep in mind: `progress: "default"` (or `"verbose"`) to get the same output as the CLI; - functions throw on error, and never terminate the process; - `run` returns a handle of the environment, which keeps running in the - background until `stop()` is called. Use `deploy()` to redeploy the - application after a rebuild; + background until `stop()` is called, and keeps the process up until then. + Its processes are stopped when the process exits, if `stop()` was not + called. Use `deploy()` to redeploy the application after a rebuild; - `send` and the `deposit*` functions resolve the application address, the sender and the RPC URL from the running project, and never prompt for them. Amounts are given in the base unit of the asset as a `bigint`, or in its @@ -194,7 +228,7 @@ A few things to keep in mind: `DepositError` (`InsufficientBalanceError`, `InvalidAmountError` or `TokenNotFoundError`); - `foreclose`, `refund` and `withdraw` send their transaction with - cartesi-rollups-cli in the rollups node container, without asking for + cartesi-rollups-cli, with the environment of the rollups node, without asking for confirmation, and return its JSON output. With `stream: true` they attach it to the terminal instead, as the CLI does. diff --git a/apps/cli/build.ts b/apps/cli/build.ts index 8dc91a454..e2df68e08 100644 --- a/apps/cli/build.ts +++ b/apps/cli/build.ts @@ -7,11 +7,22 @@ const define = { ), }; +// the postgres binaries of the environment come in a package per platform, +// which can't be bundled: they are found at runtime, in node_modules, and are +// not there for the standalone binaries, which use the postgres of the host +const postgres = [ + "@embedded-postgres/darwin-arm64", + "@embedded-postgres/darwin-x64", + "@embedded-postgres/linux-arm64", + "@embedded-postgres/linux-x64", +]; + // build for npm package: the CLI entrypoint (executable) and the library entrypoint await Bun.build({ banner: "#!/usr/bin/env node", define, entrypoints: ["./src/index.ts"], + external: postgres, minify: true, outdir: "dist", sourcemap: true, @@ -23,10 +34,13 @@ await Bun.build({ // instance of the consumer's viem classes, and viem isn't shipped twice. Keep // in sync with the dependencies of package.json. The CLI and the binaries stay // self-contained -const external = ["execa", "semver", "smol-toml", "viem"].flatMap((name) => [ - name, - `${name}/*`, -]); +const external = [ + ...["execa", "semver", "smol-toml", "viem"].flatMap((name) => [ + name, + `${name}/*`, + ]), + ...postgres, +]; await Bun.build({ define, @@ -56,6 +70,7 @@ await Promise.all( }, define, entrypoints: ["./src/index.ts"], + external: postgres, minify: true, sourcemap: "linked", target: "bun", diff --git a/apps/cli/package.json b/apps/cli/package.json index ab753d0c2..95419a19a 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -31,6 +31,12 @@ "smol-toml": "^1.9.0", "viem": "^2.57.3" }, + "optionalDependencies": { + "@embedded-postgres/darwin-arm64": "18.7.0-beta.19", + "@embedded-postgres/darwin-x64": "18.7.0-beta.19", + "@embedded-postgres/linux-arm64": "18.7.0-beta.19", + "@embedded-postgres/linux-x64": "18.7.0-beta.19" + }, "devDependencies": { "@cartesi/wagmi-plugin": "1.0.0-alpha.9", "@commander-js/extra-typings": "^15.0.0", diff --git a/apps/cli/src/api/address-book.ts b/apps/cli/src/api/address-book.ts index 0a1cef5f2..00d38aaf9 100644 --- a/apps/cli/src/api/address-book.ts +++ b/apps/cli/src/api/address-book.ts @@ -2,7 +2,7 @@ import { type AddressBook, getAddressBook, getProjectName } from "../base.js"; export type AddressBookOptions = { /** - * Name of the project (used by docker compose and cartesi-rollups-node). + * Name of the project (used by cartesi-rollups-node). * @default basename of the current working directory */ projectName?: string; diff --git a/apps/cli/src/api/connection.ts b/apps/cli/src/api/connection.ts index 1c136fcfa..e6e508aab 100644 --- a/apps/cli/src/api/connection.ts +++ b/apps/cli/src/api/connection.ts @@ -17,7 +17,7 @@ export type ConnectionOptions = { from?: Address; /** - * Name of the project (used by docker compose and cartesi-rollups-node). + * Name of the project (used by cartesi-rollups-node). * @default basename of the current working directory */ projectName?: string; diff --git a/apps/cli/src/api/doctor.ts b/apps/cli/src/api/doctor.ts index 621143fda..d1d870dfb 100644 --- a/apps/cli/src/api/doctor.ts +++ b/apps/cli/src/api/doctor.ts @@ -2,13 +2,12 @@ import { execa } from "execa"; import semver from "semver"; import { DEFAULT_SDK_IMAGE, DEFAULT_SDK_VERSION } from "../config.js"; import { cartesiMachine } from "../exec/index.js"; +import { findPostgres } from "../host/postgres.js"; +import { checkTool, HOST_TOOLS } from "../host/tools.js"; const MINIMUM_DOCKER_VERSION = "25.0.0"; // Replace with our minimum required Docker version -const MINIMUM_DOCKER_COMPOSE_VERSION = "2.24.0"; // Replace with our minimum required Docker Compose version const MINIMUM_BUILDX_VERSION = "0.13.0"; // Replace with our minimum required Buildx version -const COMPOSE_NOT_INSTALLED = - "Docker Compose is required but not installed or the command execution failed. Please refer to the Docker Compose documentation for installation instructions: https://docs.docker.com/compose/install/"; const BUILDX_NOT_INSTALLED = "Docker Buildx is required but not installed. Please refer to the Docker Desktop documentation for installation instructions: https://docs.docker.com/desktop/"; @@ -17,11 +16,11 @@ export type DoctorCheck = { name: string; /** - * Whether the requirement is satisfied (`ok`), is not (`failed`), or could - * not be checked because a requirement it depends on is not satisfied - * (`skipped`). + * Whether the requirement is satisfied (`ok`), is not (`failed`), is + * optional and not satisfied (`warning`), or could not be checked because + * a requirement it depends on is not satisfied (`skipped`). */ - status: "ok" | "failed" | "skipped"; + status: "ok" | "failed" | "skipped" | "warning"; /** Detail of a satisfied requirement, usually the installed version. */ detail?: string; @@ -31,7 +30,7 @@ export type DoctorCheck = { }; export type DoctorResult = { - /** Whether all requirements are satisfied. */ + /** Whether all requirements are satisfied, the optional ones aside. */ ok: boolean; /** Every requirement checked, satisfied or not. */ @@ -92,21 +91,6 @@ const checkDocker = async (): Promise => { return v?.version; }; -const checkCompose = async (): Promise => { - const dockerComposeVersion = await docker( - ["compose", "version", "--short"], - COMPOSE_NOT_INSTALLED, - ); - - const v = semver.coerce(dockerComposeVersion); - if (v !== null && !semver.gte(v, MINIMUM_DOCKER_COMPOSE_VERSION)) { - throw new Error( - `Unsupported Docker Compose version. Minimum required version is ${MINIMUM_DOCKER_COMPOSE_VERSION}. Installed version is ${v}.`, - ); - } - return dockerComposeVersion; -}; - const checkBuildx = async (): Promise => { const buildxOutput = await docker( ["buildx", "version"], @@ -160,15 +144,43 @@ const checkCartesiMachine = async (): Promise => { return v.format(); }; +/** An optional requirement that is not satisfied. */ +class DoctorWarning extends Error {} + +/** + * Check a tool `cartesi run` runs on the host: installed, and of a supported + * version. A tool not every run needs is only a warning. + */ +const checkHostTool = + (command: string | (() => Promise)) => + async (): Promise => { + const resolved = + typeof command === "string" ? command : await command(); + const check = await checkTool(resolved); + const tool = HOST_TOOLS[check.name]; + const optional = tool?.neededFor !== undefined; + const fail = (message: string) => { + throw optional ? new DoctorWarning(message) : new Error(message); + }; + if (!check.path) { + fail( + `${check.name} not installed, which ${tool?.neededFor ?? "cartesi run"} needs: install ${tool?.install ?? check.name}`, + ); + } + if (check.warning) { + fail(check.warning); + } + return check.version; + }; + +/** The postgres of the environment: the embedded one, or the host's. */ +const postgresBinary = async () => (await findPostgres()).postgres; +const initdbBinary = async () => (await findPostgres()).initdb; + // the Cartesi Machine check requires nothing, as a host cartesi-machine // satisfies it without docker const checks: Check[] = [ { name: "Docker Engine", run: checkDocker }, - { - name: "Docker Compose", - requires: ["Docker Engine"], - run: checkCompose, - }, { name: "Docker Buildx", requires: ["Docker Engine"], @@ -180,6 +192,31 @@ const checks: Check[] = [ run: checkRiscv, }, { name: "Cartesi Machine", run: checkCartesiMachine }, + // cartesi run + { name: "anvil", run: checkHostTool("anvil") }, + { + name: "cartesi-rollups-node", + run: checkHostTool("cartesi-rollups-node"), + }, + { name: "cartesi-rollups-cli", run: checkHostTool("cartesi-rollups-cli") }, + { + name: "cartesi-jsonrpc-machine", + run: checkHostTool("cartesi-jsonrpc-machine"), + }, + { name: "postgres", run: checkHostTool(postgresBinary) }, + { name: "initdb", run: checkHostTool(initdbBinary) }, + // what only some commands, or some runs, need + { + name: "cartesi-rollups-machine-tool", + run: checkHostTool("cartesi-rollups-machine-tool"), + }, + { name: "cartesi-sling-node", run: checkHostTool("cartesi-sling-node") }, + { name: "alto", run: checkHostTool("alto") }, + { + name: "mock-verifying-paymaster", + run: checkHostTool("mock-verifying-paymaster"), + }, + { name: "passkey-server", run: checkHostTool("passkey-server") }, ]; /** @@ -227,7 +264,7 @@ export const doctor = async (): Promise => { } catch (e: unknown) { return { name, - status: "failed", + status: e instanceof DoctorWarning ? "warning" : "failed", message: e instanceof Error ? e.message : String(e), }; } @@ -236,7 +273,9 @@ export const doctor = async (): Promise => { const resolved = skipUnmetRequirements(checks, results); return { - ok: resolved.every((check) => check.status === "ok"), + ok: resolved.every( + (check) => check.status === "ok" || check.status === "warning", + ), checks: resolved, }; }; diff --git a/apps/cli/src/api/logs.ts b/apps/cli/src/api/logs.ts index 7f9eee521..e8d18c885 100644 --- a/apps/cli/src/api/logs.ts +++ b/apps/cli/src/api/logs.ts @@ -1,27 +1,18 @@ -import { execa } from "execa"; +import fs from "node:fs"; import { getProjectName } from "../base.js"; -import { isPrtNodeService } from "../compose/prt-node.js"; +import { NODE_SERVICE } from "../host/node.js"; +import { isPrtNodeService } from "../host/prt-node.js"; +import { readState } from "../host/state.js"; -/** The node's compose service, shown by default and first. */ -export const NODE_SERVICE = "rollups_node"; +export { NODE_SERVICE }; /** - * The services of a running environment, as compose lists them; an exited - * container is still listed, so its last logs can be read. + * The services of an environment, in the order they started; an exited one + * is still listed, so its last logs can be read. */ export const listServices = async (projectName: string): Promise => { - const { stdout } = await execa("docker", [ - "compose", - "--project-name", - projectName, - "ps", - "--services", - "--all", - ]); - return stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0); + const state = readState(projectName); + return [...new Set(state?.processes.map(({ name }) => name) ?? [])]; }; /** @@ -41,7 +32,6 @@ export const selectLogServices = ( } return [NODE_SERVICE, ...services.filter(isPrtNodeService)]; } - // compose shows nothing for an unknown service, without an error const unknown = requested.filter((service) => !services.includes(service)); if (unknown.length > 0) { throw new Error( @@ -52,31 +42,41 @@ export const selectLogServices = ( }; /** - * The `docker compose logs` arguments. One service is shown as it is, like - * `docker container logs`; more than one get compose's per-service prefix, - * which tells the node's lines from the PRT nodes'. + * The last lines of a log, as `--tail` selects them. + * @param tail number of lines, or "all" */ -export const buildLogsArgs = (options: { - follow?: boolean; - projectName: string; - services: string[]; - since?: string; - tail?: string; - until?: string; -}): string[] => { - const { follow, projectName, services, since, tail, until } = options; - const args = ["compose", "--project-name", projectName, "logs"]; - if (follow) args.push("--follow"); - if (since) args.push("--since", since); - if (tail) args.push("--tail", tail); - if (until) args.push("--until", until); - if (services.length === 1) args.push("--no-log-prefix"); - return [...args, ...services]; +export const tailLines = (content: string, tail: string): string[] => { + const lines = content.split("\n"); + // the line a newline ends is not followed by another one + if (lines.at(-1) === "") { + lines.pop(); + } + if (tail === "all") { + return lines; + } + const count = Number.parseInt(tail, 10); + if (Number.isNaN(count) || count < 0) { + throw new Error(`invalid --tail ${tail}, expected a number or "all"`); + } + return count === 0 ? [] : lines.slice(-count); +}; + +/** + * The prefix of each line of a service. One service is shown as it is; more + * than one get a prefix, as compose did, which tells the node's lines from + * the PRT nodes'. + */ +export const linePrefix = (services: string[], service: string): string => { + if (services.length < 2) { + return ""; + } + const width = Math.max(...services.map((name) => name.length)); + return `${service.padEnd(width)} | `; }; export type LogsOptions = { /** - * Name of the project (used by docker compose and cartesi-rollups-node). + * Name of the project (used by cartesi-rollups-node). * @default basename of the current working directory */ projectName?: string; @@ -87,14 +87,11 @@ export type LogsOptions = { */ services?: string[]; - /** Follow log output. */ - follow?: boolean; - /** - * Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative - * (e.g. 42m for 42 minutes). + * Follow log output, until the environment stops or the process gets a + * SIGINT (a Ctrl+C). */ - since?: string; + follow?: boolean; /** * Number of lines to show from the end of the logs. @@ -102,12 +99,6 @@ export type LogsOptions = { */ tail?: string; - /** - * Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative - * (e.g. 42m for 42 minutes). - */ - until?: string; - /** * Write the logs directly to the terminal instead of returning them. * @default false @@ -122,6 +113,9 @@ export type LogsOptions = { onLine?: (line: string) => void; }; +/** How often a followed log is checked for new lines. */ +const FOLLOW_INTERVAL = 200; + /** * Read the logs of a local environment: the rollups node and its PRT nodes, or * the services given. @@ -136,42 +130,96 @@ export type LogsOptions = { export const logs = async ( options: LogsOptions = {}, ): Promise => { - const { - follow, - onLine, - since, - stream = false, - tail = "all", - until, - } = options; + const { follow, onLine, stream = false, tail = "all" } = options; const projectName = getProjectName(options); + const state = readState(projectName); const services = selectLogServices( await listServices(projectName), options.services ?? [], ); - const args = buildLogsArgs({ - follow, - projectName, - services, - since, - tail, - until, + const collected: string[] = []; + const emit = (line: string) => { + if (onLine) { + onLine(line); + } else if (stream) { + process.stdout.write(`${line}\n`); + } else { + collected.push(line); + } + }; + + // a service restarted by a redeploy, a PRT node, keeps writing to its log + const files = services.map((service) => { + const log = state?.processes.find(({ name }) => name === service)?.log; + return { log, prefix: linePrefix(services, service), service }; }); - if (stream) { - await execa("docker", args, { stdio: "inherit" }); - return undefined; + const offsets = new Map(); + for (const { log, prefix } of files) { + if (!log) { + continue; + } + let content = ""; + try { + content = fs.readFileSync(log, "utf-8"); + } catch { + // removed with its environment + } + offsets.set(log, Buffer.byteLength(content)); + for (const line of tailLines(content, tail)) { + emit(`${prefix}${line}`); + } } - // interleave stdout and stderr, as docker logs writes to both - const subprocess = execa("docker", args, { all: true }); - if (onLine) { - for await (const line of subprocess.iterable({ from: "all" })) { - onLine(line); - } + if (follow) { + await new Promise((resolve) => { + const partial = new Map(); + const poll = () => { + for (const { log, prefix } of files) { + if (!log) { + continue; + } + let size: number; + try { + size = fs.statSync(log).size; + } catch { + // the environment stopped and took its logs along + stop(); + return; + } + const offset = offsets.get(log) ?? 0; + if (size <= offset) { + continue; + } + const fd = fs.openSync(log, "r"); + const buffer = Buffer.alloc(size - offset); + fs.readSync(fd, buffer, 0, buffer.length, offset); + fs.closeSync(fd); + offsets.set(log, size); + const text = + (partial.get(log) ?? "") + buffer.toString("utf-8"); + const lines = text.split("\n"); + partial.set(log, lines.pop() ?? ""); + for (const line of lines) { + emit(`${prefix}${line}`); + } + } + }; + const timer = setInterval(poll, FOLLOW_INTERVAL); + const stop = () => { + clearInterval(timer); + process.removeListener("SIGINT", stop); + resolve(); + }; + // a Ctrl+C ends the following, not the process + process.on("SIGINT", stop); + }); + } + + if (stream || onLine) { + return stream ? undefined : ""; } - const { all, stdout } = await subprocess; - return all ?? stdout; + return collected.join("\n"); }; diff --git a/apps/cli/src/api/recovery.ts b/apps/cli/src/api/recovery.ts index fc6b4dd0b..3cbc98e96 100644 --- a/apps/cli/src/api/recovery.ts +++ b/apps/cli/src/api/recovery.ts @@ -22,7 +22,7 @@ export type RecoveryOptions = ProgressOptions & { application?: string; /** - * Name of the project (used by docker compose and cartesi-rollups-node). + * Name of the project (used by cartesi-rollups-node). * @default basename of the current working directory */ projectName?: string; diff --git a/apps/cli/src/api/run.ts b/apps/cli/src/api/run.ts index 1806cbbdd..bb860ba41 100644 --- a/apps/cli/src/api/run.ts +++ b/apps/cli/src/api/run.ts @@ -9,13 +9,14 @@ import { numberToHex, } from "viem"; import fs from "node:fs"; +import { stringify } from "yaml"; import { getCartesiEnvironmentVariables, getContextPath, getMachineHash, getProjectName, } from "../base.js"; -import { nodePrtAuthVariables } from "../compose/node.js"; +import { nodePrtAuthVariables } from "../host/node.js"; import { DEFAULT_SDK_VERSION, type DefaultBlock, @@ -25,16 +26,17 @@ import { } from "../config.js"; import { deployApplication, - type EnvironmentOptions, host, removeApplication, type RollupsDeployment, - startEnvironment, - startPrtNodes, - stopEnvironment, - stopPrtNodes as stopPrtNodeServices, - waitHealthyEnvironment, } from "../exec/rollups.js"; +import { + type Environment, + type EnvironmentOptions, + planEnvironment, + prepareEnvironment, + startEnvironment, +} from "../host/environment.js"; import { checkPrtNodes, describePrtNode, @@ -46,7 +48,11 @@ import { sentriesOf, } from "../prt.js"; import type { ForkConfig } from "../types/chain.js"; -import { assertForkConfig } from "../validations.js"; +import { + assertBlockchainEndpoint, + assertForkConfig, + assertSecretFiles, +} from "../validations.js"; import { connect } from "../wallet.js"; import { DEVNET_GUARDIAN, getWithdrawalConfig } from "../withdrawal.js"; import { @@ -78,7 +84,10 @@ export type RunOptions = ConfigOptions & */ claimStagingPeriod?: number; - /** Number of cpu limits for the rollups-node. */ + /** + * Number of cpu limits for the rollups-node. Ignored: the environment + * runs on the host, where nothing limits a process. + */ cpus?: number; /** @@ -103,8 +112,8 @@ export type RunOptions = ConfigOptions & detach?: boolean; /** - * Do not start the environment, only resolve the docker compose - * configuration, returned as {@link RunResult.config}. + * Do not start the environment, only describe the processes it would + * run, returned as {@link RunResult.config}. * @default false */ dryRun?: boolean; @@ -121,7 +130,7 @@ export type RunOptions = ConfigOptions & /** RPC URL to fork from. */ forkUrl?: string; - /** Memory limit for the rollups-node, in MB. */ + /** Memory limit for the rollups-node, in MB. Ignored, as `cpus`. */ memory?: number; /** @@ -131,7 +140,7 @@ export type RunOptions = ConfigOptions & port?: number; /** - * Name of the project (used by docker compose and cartesi-rollups-node). + * Name of the project (used by cartesi-rollups-node). * @default basename of the current working directory */ projectName?: string; @@ -142,7 +151,10 @@ export type RunOptions = ConfigOptions & */ prt?: boolean; - /** Version of the Cartesi Rollups Runtime to use. */ + /** + * Version of the Cartesi Rollups Runtime to use. Ignored: the + * environment runs the tools installed on the host. + */ runtimeVersion?: string; /** @@ -189,7 +201,7 @@ export type RunResult = { readonly prtServices: string[]; /** - * Docker compose configuration of the environment. Only defined when the + * The processes the environment would run, as YAML. Only defined when the * `dryRun` option is enabled, in which case nothing is started. */ config?: string; @@ -217,7 +229,10 @@ export type RunResult = { */ stopPrtNodes(): Promise; - /** Stop the environment, removing its containers and volumes. */ + /** + * Stop the environment: every process it started, and everything it kept + * on the host, its database and logs included. + */ stop(): Promise; }; @@ -299,15 +314,15 @@ const reportPrtWarnings = (options: { * is up and before the deploy they claim for. */ const fundPrtNodes = async (options: { - environment: EnvironmentOptions; + port: number; prtConfig?: ResolvedPrt; }) => { - const { environment, prtConfig } = options; + const { port, prtConfig } = options; if (!prtConfig || runnableNodes(prtConfig).length === 0) { return; } const client = await connect({ - rpcUrl: `${host}:${environment.port}/anvil`, + rpcUrl: `${host}:${port}/anvil`, }); await checkPrtNodes(client, prtConfig); }; @@ -320,7 +335,7 @@ const fundPrtNodes = async (options: { */ const runPrtNodes = async (options: { application: Address; - environment: EnvironmentOptions; + environment: Environment; progress: Progress; prtConfig?: ResolvedPrt; }): Promise => { @@ -341,10 +356,8 @@ const runPrtNodes = async (options: { `starting ${nodes.length === 1 ? "the PRT node" : `${nodes.length} PRT nodes`}...`, ); try { - services = await startPrtNodes({ - ...environment, + services = await environment.startPrtNodes({ application, - imageTag: environment.runtimeVersion, nodes: prtConfig.nodes, }); spinner.stop(); @@ -387,6 +400,7 @@ const deployMachine = async (options: { prt?: boolean; prtConfig?: ResolvedPrt; salt: Hex; + snapshotPath: string; withdrawalConfig?: WithdrawalConfig; }) => { const { @@ -399,6 +413,7 @@ const deployMachine = async (options: { prt, prtConfig, salt, + snapshotPath, withdrawalConfig, } = options; @@ -419,7 +434,7 @@ const deployMachine = async (options: { sentries: prtConfig && sentriesOf(prtConfig).map(({ address }) => address), sentryManager: prtConfig?.sentryManager, - snapshotPath: "/var/lib/cartesi-rollups-node/snapshots/image", + snapshotPath, withdrawalConfig, }); spinner.succeed( @@ -497,7 +512,6 @@ export const run = async (options: RunOptions = {}): Promise => { epochLength, memory, prt, - runtimeVersion, services, verbose, ...resolved @@ -519,6 +533,8 @@ export const run = async (options: RunOptions = {}): Promise => { const port = resolved.port || (await getPort({ + // the environment listens on the loopback interface only + host: "127.0.0.1", port: portNumbers(PREFERRED_PORT, PREFERRED_PORT + 10), })); @@ -584,39 +600,52 @@ export const run = async (options: RunOptions = {}): Promise => { } } - const environment: EnvironmentOptions = { + // the CARTESI_ variables of the host the node is configured with + const cartesiEnvironmentVariables = getCartesiEnvironmentVariables(); + assertBlockchainEndpoint(cartesiEnvironmentVariables); + assertSecretFiles(cartesiEnvironmentVariables); + + // a container could be limited, a process of the host is not + if (cpus !== undefined || memory !== undefined) { + notify({ + level: "warning", + message: + "the cpus and memory limits are ignored, the environment runs on the host", + }); + } + + const environmentOptions: EnvironmentOptions = { blockTime, + cartesiEnvironmentVariables, claimSubmission, - cpus, defaultBlock, forkConfig, - memory, port, projectName, prt, - runtimeVersion, services, verbose, }; - // run compose environment - const { cmd, config } = await startEnvironment({ - ...environment, - detach, - dryRun, - }); + let environment: Environment | undefined; + const started = (): Environment => { + if (!environment) { + throw new Error(`${projectName} is not running`); + } + return environment; + }; let deployment: RollupsDeployment | undefined; let prtServices: string[] = []; let salt = 0; const stopPrtNodes = async () => { - await stopPrtNodeServices({ projectName, services: prtServices }); + await environment?.stopPrtNodes(prtServices); prtServices = []; }; const stop = async () => { - await stopEnvironment({ projectName }); + await environment?.stop(); prtServices = []; }; @@ -634,6 +663,7 @@ export const run = async (options: RunOptions = {}): Promise => { * instead of resolving and reporting it again */ const deployMachineSnapshot = async (options: { initial: boolean }) => { + const running = started(); const machineHash = await getMachineHash({ sdk: applicationConfig.sdk, }); @@ -662,7 +692,7 @@ export const run = async (options: RunOptions = {}): Promise => { } reportPrtWarnings({ claimStagingPeriod, notify, prtConfig }); } - await fundPrtNodes({ environment, prtConfig }); + await fundPrtNodes({ port, prtConfig }); // keep the consensus of the previous deployment, if there is one; a // PRT deploy ignores it and creates a new one @@ -679,11 +709,12 @@ export const run = async (options: RunOptions = {}): Promise => { prt, prtConfig, salt: numberToHex(salt++, { size: 32 }), + snapshotPath: running.state.templatePath, withdrawalConfig, }); prtServices = await runPrtNodes({ application: deployment.address, - environment, + environment: running, progress, prtConfig, }); @@ -702,8 +733,6 @@ export const run = async (options: RunOptions = {}): Promise => { get prtServices() { return prtServices; }, - cmd, - config, deploy, port, projectName, @@ -714,26 +743,49 @@ export const run = async (options: RunOptions = {}): Promise => { }; if (dryRun) { - // environment was not started, just return the compose configuration + // the environment is not started, only described + result.config = stringify(await planEnvironment(environmentOptions), { + indent: 2, + lineWidth: 0, + }); return result; } + // fail before saying anything is starting, naming every missing tool, + // and say which ones may not work + const { warnings } = await prepareEnvironment({ + ...environmentOptions, + sling: prtConfig?.nodes.some(({ type }) => type === "sling"), + }); + for (const message of warnings) { + notify({ + level: "warning", + message: `${message}, the environment may not work`, + }); + } + ora({ isSilent: progress === "silent" }).succeed( `${chalk.cyan(projectName)} starting at ${chalk.cyan(url)}`, ); - // wait for the environment to be healthy - await waitHealthyEnvironment({ - name: projectName, - port, - projectName, + // start the environment, and wait for it to be healthy + environment = await startEnvironment({ + ...environmentOptions, renderer: listrRenderer(progress), - services, }); + if (!detach) { + result.cmd = environment.exited; + } // deploy the application built at .cartesi/image, if there is one if (deployOnStart) { - await deployMachineSnapshot({ initial: true }); + try { + await deployMachineSnapshot({ initial: true }); + } catch (error: unknown) { + // nothing is left running for a run that failed + await stop(); + throw error; + } } return result; diff --git a/apps/cli/src/api/status.ts b/apps/cli/src/api/status.ts index 955e78f0e..b8c022029 100644 --- a/apps/cli/src/api/status.ts +++ b/apps/cli/src/api/status.ts @@ -3,7 +3,7 @@ import { getDeployments, type RollupsDeployment } from "../exec/rollups.js"; export type StatusOptions = { /** - * Name of the project (used by docker compose and cartesi-rollups-node). + * Name of the project (used by cartesi-rollups-node). * @default basename of the current working directory */ projectName?: string; @@ -16,7 +16,7 @@ export type StatusResult = { /** Whether the rollups node of the environment is running. */ running: boolean; - /** State of the rollups node container, as reported by docker compose. */ + /** State of the rollups node process: `running`, or `exited` once it is gone. */ state?: string; /** Applications deployed to the rollups node. */ diff --git a/apps/cli/src/base.ts b/apps/cli/src/base.ts index 88cba9271..9d8c1cc62 100644 --- a/apps/cli/src/base.ts +++ b/apps/cli/src/base.ts @@ -1,5 +1,4 @@ import { InvalidArgumentError } from "@commander-js/extra-typings"; -import { execa } from "execa"; import fs from "node:fs"; import path from "node:path"; import { loadConfig } from "./config/load.js"; @@ -33,7 +32,7 @@ import { } from "./contracts.js"; import { cartesiMachineStoredHash } from "./exec/index.js"; import { getApplicationAddress, getForkConfig } from "./exec/rollups.js"; -import type { PsResponse } from "./types/docker.js"; +import { readState, serviceState } from "./host/state.js"; import { assertForkConfig } from "./validations.js"; export const getContextPath = (...paths: string[]): string => { @@ -162,42 +161,16 @@ export const getAddressBook = async (options: { return contracts; }; -export const getServiceInfo = async (options: { - projectName: string; - service: string; -}): Promise => { - const { projectName, service } = options; - - // get service information - const { stdout } = await execa("docker", [ - "compose", - "--project-name", - projectName, - "ps", - // --all so an exited container is still reported, instead of the - // service simply vanishing from the output - "--all", - service, - "--format", - "json", - ]); - return stdout ? (JSON.parse(stdout) as PsResponse) : undefined; -}; - +/** + * State of a service of the environment of a project: `running`, `exited` + * once its process is gone, or undefined when it never ran. + */ export const getServiceState = async (options: { projectName: string; service: string; }): Promise => { - const info = await getServiceInfo(options); - return info?.State; -}; - -export const getServiceHealth = async (options: { - projectName: string; - service: string; -}): Promise => { - const info = await getServiceInfo(options); - return info?.Health; + const { projectName, service } = options; + return serviceState(readState(projectName), service); }; export const parseAddress = (value: string): Address | undefined => { diff --git a/apps/cli/src/commands/address-book.ts b/apps/cli/src/commands/address-book.ts index a9b9b9ae1..ace8f4f0b 100755 --- a/apps/cli/src/commands/address-book.ts +++ b/apps/cli/src/commands/address-book.ts @@ -14,7 +14,7 @@ export const createAddressBookCommand = () => { .option("--json", "Format output as json.") .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .action(async (contract, options, command) => { const { json } = options; diff --git a/apps/cli/src/commands/deposit.ts b/apps/cli/src/commands/deposit.ts index e502960d9..02bd106bf 100644 --- a/apps/cli/src/commands/deposit.ts +++ b/apps/cli/src/commands/deposit.ts @@ -19,7 +19,7 @@ export const createDepositCommand = () => { .option("--application
", "application address") .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .option("--rpc-url ", "RPC URL of the Cartesi Devnet") .action(async (_options, command) => { diff --git a/apps/cli/src/commands/doctor.ts b/apps/cli/src/commands/doctor.ts index 8bbc74b70..142b915b1 100755 --- a/apps/cli/src/commands/doctor.ts +++ b/apps/cli/src/commands/doctor.ts @@ -17,6 +17,8 @@ export const createDoctorCommand = () => { ? `${check.name} ${chalk.cyan(check.detail)}` : check.name, ); + } else if (check.status === "warning") { + progress.warn(check.message ?? `${check.name} not found`); } else if (check.status === "failed") { progress.fail(check.message ?? `${check.name} not found`); } diff --git a/apps/cli/src/commands/logs.ts b/apps/cli/src/commands/logs.ts index 8f3b498b5..d1c81664d 100644 --- a/apps/cli/src/commands/logs.ts +++ b/apps/cli/src/commands/logs.ts @@ -12,34 +12,24 @@ export const createLogsCommand = () => { ) .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .option("-f, --follow", "Follow log output") - .option( - "--since ", - "Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)", - ) .option( "-n, --tail ", "Number of lines to show from the end of the logs", "all", ) - .option( - "--until ", - "Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)", - ) .configureHelp({ showGlobalOptions: true }) .action(async (requested, options) => { - const { follow, projectName, since, tail, until } = options; + const { follow, projectName, tail } = options; await logs({ follow, projectName, services: requested, - since, stream: true, tail, - until, }); }); }; diff --git a/apps/cli/src/commands/recovery.ts b/apps/cli/src/commands/recovery.ts index 60ba5474e..41be2c1bb 100644 --- a/apps/cli/src/commands/recovery.ts +++ b/apps/cli/src/commands/recovery.ts @@ -23,7 +23,7 @@ export const addRecoveryOptions = < .option("--application
", "application address") .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .addOption( new Option( diff --git a/apps/cli/src/commands/run.ts b/apps/cli/src/commands/run.ts index 029b5f2c4..a6285fda2 100755 --- a/apps/cli/src/commands/run.ts +++ b/apps/cli/src/commands/run.ts @@ -6,7 +6,7 @@ import ora from "ora"; import { build } from "../api/build.js"; import { logs } from "../api/logs.js"; import { run, type RunNotice, type RunResult } from "../api/run.js"; -import { nodeAllowedEnvironmentVariables } from "../compose/node.js"; +import { nodeAllowedEnvironmentVariables } from "../host/node.js"; import { AVAILABLE_SERVICES, getDeployments, @@ -102,7 +102,7 @@ const shell = async (options: { const controller = new AbortController(); const watcher = setInterval(() => { pollStatus(() => controller.abort()).catch(() => { - // a transient docker failure should not interrupt the session + // a transient failure should not interrupt the session }); }, STATUS_POLL_INTERVAL); @@ -195,7 +195,7 @@ export const createRunCommand = () => { .addOption( new Option( "--cpus ", - "number of cpu limits for the rollups-node", + "number of cpu limits for the rollups-node (ignored, the environment runs on the host)", ).argParser(Number), ) .addOption( @@ -204,7 +204,11 @@ export const createRunCommand = () => { "default block to be used when fetching new blocks. (default: latest)", ).choices(["latest", "safe", "finalized"]), ) - .option("--dry-run", "show the docker compose configuration", false) + .option( + "--dry-run", + "show the processes the environment would run", + false, + ) .option( "--list-supported-variables", "Returns JSON formatted information about the environment variables allowed and which service will use them.", @@ -220,7 +224,7 @@ export const createRunCommand = () => { .addOption( new Option( "--memory ", - "memory limit for the rollups-node in MB", + "memory limit for the rollups-node in MB (ignored, the environment runs on the host)", ).argParser(Number), ) .addOption( @@ -255,7 +259,7 @@ export const createRunCommand = () => { ) .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .option( "--services ", @@ -322,7 +326,7 @@ export const createRunCommand = () => { }); if (dryRun) { - // just show the docker compose configuration and quit + // just show the processes of the environment and quit if (node.config) { process.stdout.write(node.config); } diff --git a/apps/cli/src/commands/send.ts b/apps/cli/src/commands/send.ts index 05a6970ec..a43540be1 100755 --- a/apps/cli/src/commands/send.ts +++ b/apps/cli/src/commands/send.ts @@ -26,7 +26,7 @@ export const createSendCommand = () => { .option("--abi-params ", "input abi params") .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .option("--rpc-url ", "RPC URL of the Cartesi Devnet") .action(async (input, options) => { diff --git a/apps/cli/src/commands/status.ts b/apps/cli/src/commands/status.ts index 80721330d..45cf62828 100644 --- a/apps/cli/src/commands/status.ts +++ b/apps/cli/src/commands/status.ts @@ -27,7 +27,7 @@ export const createStatusCommand = () => { .configureHelp({ showGlobalOptions: true }) .option( "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", + "name of project (used by cartesi-rollups-node)", ) .option("--json", "output in JSON format") .action(async (options) => { diff --git a/apps/cli/src/compose/anvil.ts b/apps/cli/src/compose/anvil.ts deleted file mode 100644 index 696884808..000000000 --- a/apps/cli/src/compose/anvil.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { ForkConfig } from "../types/chain.js"; -import type { ComposeFile, Config, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK, escapeComposeValue } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; - blockTime?: number; - forkConfig?: ForkConfig; -}; - -// Anvil service -const service = (options?: ServiceOptions): Service => { - const blockTime = options?.blockTime ?? 2; - const imageTag = options?.imageTag ?? "latest"; - const forkConfig = options?.forkConfig; - - // command for fork and command for load-state local (non-fork) - const command = forkConfig - ? [ - "anvil", - "--chain-id", - "31337", - "--block-time", - blockTime.toString(), - "--fork-url", - // the URL may hold an API key with a `$`, which compose must not interpolate - escapeComposeValue(forkConfig.url), - ...(forkConfig.blockNumber !== undefined - ? ["--fork-block-number", forkConfig.blockNumber.toString()] - : []), - ] - : ["devnet", "--block-time", blockTime.toString()]; - - // in case of forked network service is ready only when it responds with target block number - const test = forkConfig?.blockNumber - ? ["CMD", "eth_isready", forkConfig.blockNumber?.toString()] - : ["CMD", "eth_isready"]; - - return { - image: `cartesi/sdk:${imageTag}`, - command, - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test, - }, - environment: { - ANVIL_IP_ADDR: "0.0.0.0", - }, - }; -}; - -const proxy = (): Config => ({ - name: "anvil-proxy", - content: `http: - routers: - anvil: - rule: "PathPrefix(\`/anvil\`)" - middlewares: - - "remove-anvil-prefix" - service: anvil - middlewares: - remove-anvil-prefix: - replacePathRegex: - regex: "^/anvil(.*)" - replacement: "$1" - services: - anvil: - loadBalancer: - servers: - - url: "http://anvil:8545"`, -}); - -export default (options?: ServiceOptions): ComposeFile => ({ - configs: { - anvil_proxy: proxy(), - }, - services: { - anvil: service(options), - proxy: { - configs: [ - { - source: "anvil_proxy", - target: "/etc/traefik/conf.d/anvil.yaml", - }, - ], - }, - }, -}); diff --git a/apps/cli/src/compose/builder.ts b/apps/cli/src/compose/builder.ts deleted file mode 100644 index cbea35ae6..000000000 --- a/apps/cli/src/compose/builder.ts +++ /dev/null @@ -1,654 +0,0 @@ -import type { - ComposeFile, - Config, - ConfigReference, - Network, - PortMapping, - Secret, - SecretReference, - Service, - Volume, - VolumeMount, -} from "../../src/types/compose.js"; - -/** - * Merges multiple Compose files according to Docker Compose merge rules. - * See: https://docs.docker.com/reference/compose-file/merge/ - * - * Rules: - * - Mappings: merged by adding missing entries and merging conflicting ones - * - Sequences: merged by appending values from overriding file - * - Exceptions: - * - Shell commands (command, entrypoint, healthcheck.test): overridden, not appended - * - Unique resources (ports, volumes, secrets, configs): merged by unique key - */ -export const concat = (files: ComposeFile[]): ComposeFile => { - if (files.length === 0) { - return {}; - } - - return files.reduce((composed, file) => { - return mergeComposeFiles(composed, file); - }, {}); -}; - -/** - * Merges two Compose files according to Docker Compose merge rules - */ -function mergeComposeFiles( - base: ComposeFile, - override: ComposeFile, -): ComposeFile { - const result: ComposeFile = { ...base }; - - // Merge name (override takes precedence) - if (override.name !== undefined) { - result.name = override.name; - } - - // Merge include (append sequences) - if (override.include) { - result.include = mergeSequences(base.include, override.include); - } - - // Merge services (mapping merge) - if (override.services) { - result.services = mergeMappings( - base.services || {}, - override.services, - (baseService, overrideService) => - mergeService(baseService, overrideService), - ); - } - - // Merge networks (mapping merge) - if (override.networks) { - result.networks = mergeMappings( - base.networks || {}, - override.networks, - (baseNetwork, overrideNetwork) => - mergeNetwork(baseNetwork, overrideNetwork), - ); - } - - // Merge volumes (mapping merge) - if (override.volumes) { - result.volumes = mergeMappings( - base.volumes || {}, - override.volumes, - (baseVolume, overrideVolume) => - mergeVolume(baseVolume, overrideVolume), - ); - } - - // Merge secrets (mapping merge) - if (override.secrets) { - result.secrets = mergeMappings( - base.secrets || {}, - override.secrets, - (baseSecret, overrideSecret) => - mergeSecret(baseSecret, overrideSecret), - ); - } - - // Merge configs (mapping merge) - if (override.configs) { - result.configs = mergeMappings( - base.configs || {}, - override.configs, - (baseConfig, overrideConfig) => - mergeConfig(baseConfig, overrideConfig), - ); - } - - // Merge models (mapping merge) - if (override.models) { - result.models = mergeMappings( - base.models || {}, - override.models, - (baseModel, overrideModel) => ({ ...baseModel, ...overrideModel }), - ); - } - - return result; -} - -/** - * Merges two mappings (objects), recursively merging values for matching keys - */ -function mergeMappings( - base: Record, - override: Record, - mergeValue: (baseValue: T, overrideValue: T) => T, -): Record { - const result: Record = { ...base }; - - for (const [key, overrideValue] of Object.entries(override)) { - const baseValue = result[key]; - if (baseValue !== undefined) { - result[key] = mergeValue(baseValue, overrideValue); - } else { - result[key] = overrideValue; - } - } - - return result; -} - -/** - * Merges two services according to Docker Compose merge rules - */ -function mergeService(base: Service, override: Service): Service { - const result: Service = { ...base }; - - // Shell commands: override (not merge) - if (override.command !== undefined) { - result.command = override.command; - } - if (override.entrypoint !== undefined) { - result.entrypoint = override.entrypoint; - } - if (override.healthcheck?.test !== undefined) { - result.healthcheck = { - ...base.healthcheck, - test: override.healthcheck.test, - }; - } - - // Merge other healthcheck fields normally - if (override.healthcheck) { - result.healthcheck = { - ...base.healthcheck, - ...override.healthcheck, - // test was already handled above - test: override.healthcheck.test ?? base.healthcheck?.test, - }; - } - - // Unique resources: merge by unique key - if (override.ports) { - result.ports = mergeUniquePorts(base.ports || [], override.ports); - } - if (override.volumes) { - result.volumes = mergeUniqueVolumes( - base.volumes || [], - override.volumes, - ); - } - if (override.secrets) { - result.secrets = mergeUniqueSecrets( - base.secrets || [], - override.secrets, - ); - } - if (override.configs) { - result.configs = mergeUniqueConfigs( - base.configs || [], - override.configs, - ); - } - - // Sequences: append - if (override.expose) { - result.expose = mergeSequences(base.expose, override.expose); - } - if (override.depends_on) { - // depends_on can be array or object, handle both - if (Array.isArray(override.depends_on)) { - result.depends_on = mergeSequences( - Array.isArray(base.depends_on) ? base.depends_on : [], - override.depends_on, - ); - } else { - // For object format, merge the objects - result.depends_on = { - ...(typeof base.depends_on === "object" && - !Array.isArray(base.depends_on) - ? base.depends_on - : {}), - ...override.depends_on, - }; - } - } - if (override.dns) { - result.dns = mergeSequences( - Array.isArray(base.dns) ? base.dns : base.dns ? [base.dns] : [], - Array.isArray(override.dns) ? override.dns : [override.dns], - ); - } - if (override.dns_search) { - result.dns_search = mergeSequences( - Array.isArray(base.dns_search) - ? base.dns_search - : base.dns_search - ? [base.dns_search] - : [], - Array.isArray(override.dns_search) - ? override.dns_search - : [override.dns_search], - ); - } - if (override.dns_opt) { - result.dns_opt = mergeSequences(base.dns_opt || [], override.dns_opt); - } - if (override.env_file) { - // env_file can be string, string[], or EnvFile[] - const baseArray = Array.isArray(base.env_file) - ? base.env_file - : base.env_file - ? [base.env_file] - : []; - const overrideArray = Array.isArray(override.env_file) - ? override.env_file - : [override.env_file]; - // Type assertion needed because env_file can be string[] or EnvFile[] - result.env_file = [ - ...baseArray, - ...overrideArray, - ] as typeof override.env_file; - } - if (override.labels) { - // labels can be array or object - if (Array.isArray(override.labels)) { - result.labels = mergeSequences( - Array.isArray(base.labels) ? base.labels : [], - override.labels, - ); - } else { - result.labels = { - ...(typeof base.labels === "object" && - !Array.isArray(base.labels) - ? base.labels - : {}), - ...override.labels, - }; - } - } - if (override.extra_hosts) { - // extra_hosts can be array or object - if (Array.isArray(override.extra_hosts)) { - result.extra_hosts = mergeSequences( - Array.isArray(base.extra_hosts) ? base.extra_hosts : [], - override.extra_hosts, - ); - } else { - result.extra_hosts = { - ...(typeof base.extra_hosts === "object" && - !Array.isArray(base.extra_hosts) - ? base.extra_hosts - : {}), - ...override.extra_hosts, - }; - } - } - if (override.sysctls) { - // sysctls can be array or object - if (Array.isArray(override.sysctls)) { - result.sysctls = mergeSequences( - Array.isArray(base.sysctls) ? base.sysctls : [], - override.sysctls, - ); - } else { - result.sysctls = { - ...(typeof base.sysctls === "object" && - !Array.isArray(base.sysctls) - ? base.sysctls - : {}), - ...override.sysctls, - }; - } - } - - // Mappings: merge recursively - if (override.environment) { - if (Array.isArray(override.environment)) { - // Array format: append - result.environment = mergeSequences( - Array.isArray(base.environment) ? base.environment : [], - override.environment, - ); - } else { - // Object format: merge mappings - result.environment = { - ...(typeof base.environment === "object" && - !Array.isArray(base.environment) - ? base.environment - : {}), - ...override.environment, - }; - } - } - if (override.networks) { - if (Array.isArray(override.networks)) { - result.networks = mergeSequences( - Array.isArray(base.networks) ? base.networks : [], - override.networks, - ); - } else { - result.networks = { - ...(typeof base.networks === "object" && - !Array.isArray(base.networks) - ? base.networks - : {}), - ...override.networks, - }; - } - } - - // Other fields: override takes precedence - const overrideFields: Array = [ - "image", - "build", - "restart", - "container_name", - "hostname", - "network_mode", - "pid", - "ipc", - "deploy", - "develop", - "working_dir", - "user", - "cap_add", - "cap_drop", - "devices", - "external_links", - "gpus", - "group_add", - "mem_limit", - "mem_reservation", - "memswap_limit", - "oom_kill_disable", - "oom_score_adj", - "privileged", - "read_only", - "shm_size", - "stdin_open", - "tty", - "ulimits", - "volumes_from", - "cpus", - "cpuset", - "cpu_shares", - "cpu_quota", - "cpu_period", - "cpu_count", - "cpu_percent", - "annotations", - "cgroup", - "cgroup_parent", - "domainname", - "init", - "isolation", - "links", - "mac_address", - "platform", - "security_opt", - "stop_grace_period", - "stop_signal", - "tmpfs", - "attach", - "extends", - "provider", - "blkio_config", - "credential_spec", - "device_cgroup_rules", - "logging", - ]; - - for (const field of overrideFields) { - if (override[field] !== undefined) { - result[field] = override[field] as never; - } - } - - return result; -} - -/** - * Merges two sequences by appending override to base - */ -function mergeSequences(base: T[] | undefined, override: T[]): T[] { - return [...(base || []), ...override]; -} - -/** - * Merges ports arrays, ensuring uniqueness by {ip, target, published, protocol} - */ -function mergeUniquePorts( - base: Array, - override: Array, -): Array { - const result: Array = [...base]; - const seen = new Set(); - - // Add existing ports to seen set - for (const port of base) { - seen.add(getPortKey(port)); - } - - // Add override ports that don't violate uniqueness - for (const port of override) { - const key = getPortKey(port); - if (!seen.has(key)) { - result.push(port); - seen.add(key); - } else { - // Replace existing port with same key - const index = result.findIndex((p) => getPortKey(p) === key); - if (index !== -1) { - result[index] = port; - } - } - } - - return result; -} - -/** - * Gets a unique key for a port mapping - */ -function getPortKey(port: string | PortMapping): string { - if (typeof port === "string") { - // Parse string format: "host:container", "host:container/protocol", etc. - const parts = port.split(":"); - const containerPart = parts[1] || ""; - const [target, protocol] = containerPart.split("/"); - return `${parts[0] || ""}:${target || ""}:${protocol || "tcp"}`; - } - // Object format - const ip = port.host_ip || ""; - const target = port.target.toString(); - const published = port.published?.toString() || ""; - const protocol = port.protocol || "tcp"; - return `${ip}:${target}:${published}:${protocol}`; -} - -/** - * Merges volumes arrays, ensuring uniqueness by target - */ -function mergeUniqueVolumes( - base: Array, - override: Array, -): Array { - const result: Array = [...base]; - const seen = new Set(); - - // Add existing volumes to seen set - for (const volume of base) { - seen.add(getVolumeKey(volume)); - } - - // Add override volumes that don't violate uniqueness - for (const volume of override) { - const key = getVolumeKey(volume); - if (!seen.has(key)) { - result.push(volume); - seen.add(key); - } else { - // Replace existing volume with same key - const index = result.findIndex((v) => getVolumeKey(v) === key); - if (index !== -1) { - result[index] = volume; - } - } - } - - return result; -} - -/** - * Gets a unique key for a volume mount - */ -function getVolumeKey(volume: string | VolumeMount): string { - if (typeof volume === "string") { - // Parse string format: "source:target", "target", etc. - const parts = volume.split(":"); - return parts[parts.length - 1] || volume; - } - return volume.target; -} - -/** - * Merges secrets arrays, ensuring uniqueness by target - */ -function mergeUniqueSecrets( - base: Array, - override: Array, -): Array { - const result: Array = [...base]; - const seen = new Set(); - - // Add existing secrets to seen set - for (const secret of base) { - seen.add(getSecretKey(secret)); - } - - // Add override secrets that don't violate uniqueness - for (const secret of override) { - const key = getSecretKey(secret); - if (!seen.has(key)) { - result.push(secret); - seen.add(key); - } else { - // Replace existing secret with same key - const index = result.findIndex((s) => getSecretKey(s) === key); - if (index !== -1) { - result[index] = secret; - } - } - } - - return result; -} - -/** - * Gets a unique key for a secret reference - */ -function getSecretKey(secret: string | SecretReference): string { - if (typeof secret === "string") { - return secret; - } - return secret.target || secret.source; -} - -/** - * Merges configs arrays, ensuring uniqueness by target - */ -function mergeUniqueConfigs( - base: Array, - override: Array, -): Array { - const result: Array = [...base]; - const seen = new Set(); - - // Add existing configs to seen set - for (const config of base) { - seen.add(getConfigKey(config)); - } - - // Add override configs that don't violate uniqueness - for (const config of override) { - const key = getConfigKey(config); - if (!seen.has(key)) { - result.push(config); - seen.add(key); - } else { - // Replace existing config with same key - const index = result.findIndex((c) => getConfigKey(c) === key); - if (index !== -1) { - result[index] = config; - } - } - } - - return result; -} - -/** - * Gets a unique key for a config reference - */ -function getConfigKey(config: string | ConfigReference): string { - if (typeof config === "string") { - return config; - } - return config.target || config.source; -} - -/** - * Merges two networks - */ -function mergeNetwork(base: Network, override: Network): Network { - return { - ...base, - ...override, - // Merge nested objects - ipam: override.ipam - ? { - ...base.ipam, - ...override.ipam, - config: override.ipam.config - ? mergeSequences(base.ipam?.config, override.ipam.config) - : base.ipam?.config, - } - : base.ipam, - external: - override.external !== undefined ? override.external : base.external, - }; -} - -/** - * Merges two volumes - */ -function mergeVolume(base: Volume, override: Volume): Volume { - return { - ...base, - ...override, - external: - override.external !== undefined ? override.external : base.external, - }; -} - -/** - * Merges two secrets - */ -function mergeSecret(base: Secret, override: Secret): Secret { - return { - ...base, - ...override, - external: - override.external !== undefined ? override.external : base.external, - }; -} - -/** - * Merges two configs - */ -function mergeConfig(base: Config, override: Config): Config { - return { - ...base, - ...override, - external: - override.external !== undefined ? override.external : base.external, - }; -} diff --git a/apps/cli/src/compose/bundler.ts b/apps/cli/src/compose/bundler.ts deleted file mode 100644 index 7bc3a4484..000000000 --- a/apps/cli/src/compose/bundler.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { ComposeFile, Config, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; -}; - -const service = (options: ServiceOptions): Service => { - const imageTag = options.imageTag ?? "latest"; - - return { - image: `cartesi/sdk:${imageTag}`, - command: [ - "alto", - "--entrypoints", - "0x5ff137d4b0fdcd49dca30c7cf57e578a026d2789,0x0000000071727De22E5E9d8BAf0edAc6f37da032", - "--log-level", - "info", - "--rpc-url", - "http://anvil:8545", - "--min-executor-balance", - "0", - "--utility-private-key", - "0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97", - "--executor-private-keys", - "0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6,0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356,0x92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e,0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba,0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a", - "--safe-mode", - "false", - "--port", - "4337", - "--public-client-log-level", - "error", - "--wallet-client-log-level", - "error", - "--enable-debug-endpoints", - ], - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:4337/health"], - }, - }; -}; - -const proxy = (): Config => { - return { - name: "bundler-proxy", - content: `http: - routers: - bundler: - rule: "PathPrefix(\`/bundler\`)" - middlewares: - - "cors" - - "remove-bundler-prefix" - service: bundler - middlewares: - cors: - headers: - accessControlAllowMethods: - - GET - - OPTIONS - - PUT - accessControlAllowHeaders: "*" - accessControlAllowOriginList: - - "*" - accessControlMaxAge: 100 - addVaryHeader: true - remove-bundler-prefix: - replacePathRegex: - regex: "^/bundler/(.*)" - replacement: "/$1" - services: - bundler: - loadBalancer: - servers: - - url: "http://bundler:4337"`, - }; -}; - -export default (options: ServiceOptions): ComposeFile => ({ - configs: { - bundler_proxy: proxy(), - }, - services: { - bundler: service(options), - proxy: { - configs: [ - { - source: "bundler_proxy", - target: "/etc/traefik/conf.d/bundler.yaml", - }, - ], - }, - }, -}); diff --git a/apps/cli/src/compose/common.ts b/apps/cli/src/compose/common.ts deleted file mode 100644 index 0aef4f4b2..000000000 --- a/apps/cli/src/compose/common.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Healthcheck } from "../types/compose.js"; - -export const DEFAULT_HEALTHCHECK: Healthcheck = { - start_period: "10s", - start_interval: "200ms", - interval: "10s", - timeout: "1s", - retries: 5, -}; - -/** - * Escapes a value for a compose file, which would otherwise read `$name` and - * `${name}` in it as variables and replace them, `$` and all. - * The container still gets the original value. - */ -export const escapeComposeValue = (value: string): string => - value.replaceAll("$", () => "$$"); diff --git a/apps/cli/src/compose/database.ts b/apps/cli/src/compose/database.ts deleted file mode 100644 index 05b640d9a..000000000 --- a/apps/cli/src/compose/database.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { ComposeFile, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; - password: string; -}; - -// Database service -export const service = (options: ServiceOptions): Service => { - const imageTag = options?.imageTag ?? "latest"; - return { - image: `cartesi/rollups-database:${imageTag}`, - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: ["CMD-SHELL", "pg_isready -U postgres || exit 1"], - }, - environment: { - POSTGRES_PASSWORD: options?.password, - }, - }; -}; - -export default (options: ServiceOptions): ComposeFile => ({ - services: { - database: service(options), - }, -}); diff --git a/apps/cli/src/compose/explorer.ts b/apps/cli/src/compose/explorer.ts deleted file mode 100644 index 40a9c5dbe..000000000 --- a/apps/cli/src/compose/explorer.ts +++ /dev/null @@ -1,74 +0,0 @@ -import type { ComposeFile, Config, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; - port?: number; -}; - -// Explorer service -export const explorerService = (options: ServiceOptions): Service => { - const imageTag = options.imageTag ?? "latest"; - const port = options.port ?? 6571; - - const nodeRpcUrl = `http://127.0.0.1:${port}/anvil`; - const cartesiNodeRpcUrl = `http://127.0.0.1:${port}/rpc`; - - return { - image: `cartesi/rollups-explorer:${imageTag}`, - environment: { - NODE_RPC_URL: nodeRpcUrl, - CARTESI_NODE_RPC_URL: cartesiNodeRpcUrl, - }, - expose: ["3000"], - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: [ - "CMD", - "wget", - "--spider", - "-q", - `http://127.0.0.1:3000/explorer/api/healthz`, - ], - }, - - depends_on: { - anvil: { condition: "service_healthy" }, - rollups_node: { condition: "service_healthy" }, - }, - }; -}; - -// Explorer Proxy configuration -export const explorerProxyConfig = (): Config => { - return { - name: "explorer-proxy", - content: `http: - routers: - explorer: - rule: "PathPrefix(\`/explorer\`)" - service: explorer - services: - explorer: - loadBalancer: - servers: - - url: "http://explorer:3000"`, - }; -}; - -export default (options: ServiceOptions): ComposeFile => ({ - configs: { - explorer_proxy: explorerProxyConfig(), - }, - services: { - explorer: explorerService(options), - proxy: { - configs: [ - { - source: "explorer_proxy", - target: "/etc/traefik/conf.d/explorer.yaml", - }, - ], - }, - }, -}); diff --git a/apps/cli/src/compose/node.ts b/apps/cli/src/compose/node.ts deleted file mode 100644 index 4119f6284..000000000 --- a/apps/cli/src/compose/node.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { anvil } from "viem/chains"; -import type { CartesiEnvironmentVariables } from "../base.js"; -import { - applicationFactoryAddress, - daveAppFactoryAddress, - inputBoxAddress, - selfHostedApplicationFactoryAddress, -} from "../contracts.js"; -import type { ComposeFile, Config, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK, escapeComposeValue } from "./common.js"; -import { type FileSecret, fileSecret, secretInitService } from "./secrets.js"; - -/** - * Mnemonic of the devnet test accounts, used by the node to sign transactions - */ -export const DEVNET_MNEMONIC = - "test test test test test test test test test test test junk"; - -export type ServiceOptions = { - cpus?: number; - databaseHost?: string; - databasePort?: number; - databasePassword: string; - defaultBlock?: "latest" | "safe" | "finalized"; - forkChainId?: number; - logLevel?: "info" | "debug" | "warn" | "error" | "fatal"; - memory?: number; - mnemonic?: string; - imageTag?: string; - prt?: boolean; - /** - * whether the node submits claims, the default; with a sling claimer it - * runs in reader mode, following the tournaments and recording settled - * epochs with no PRT signer - */ - claimSubmission?: boolean; - cartesiEnvironmentVariables?: CartesiEnvironmentVariables; -}; - -/** - * A list of allowed environment variables - * that can be passed to the rollups node service. - * A number of environment variables are rule out to avoid confusion e.g. CORS, FEATURE Enablement, etc. - */ -export const nodeAllowedEnvironmentVariables = [ - "CARTESI_AUTH_KIND", - "CARTESI_AUTH_MNEMONIC", - "CARTESI_AUTH_MNEMONIC_ACCOUNT_INDEX", - "CARTESI_AUTH_MNEMONIC_FILE", - "CARTESI_AUTH_PRIVATE_KEY", - "CARTESI_AUTH_PRIVATE_KEY_FILE", - "CARTESI_BLOCKCHAIN_DEFAULT_BLOCK", - "CARTESI_BLOCKCHAIN_HTTP_AUTHORIZATION", - "CARTESI_BLOCKCHAIN_HTTP_ENDPOINT", - "CARTESI_BLOCKCHAIN_ID", - "CARTESI_CONTRACTS_APPLICATION_FACTORY_ADDRESS", - "CARTESI_CONTRACTS_AUTHORITY_FACTORY_ADDRESS", - "CARTESI_CONTRACTS_DAVE_APP_FACTORY_ADDRESS", - "CARTESI_CONTRACTS_INPUT_BOX_ADDRESS", - "CARTESI_CONTRACTS_QUORUM_FACTORY_ADDRESS", - "CARTESI_CONTRACTS_SELF_HOSTED_APPLICATION_FACTORY_ADDRESS", - "CARTESI_DATABASE_CONNECTION", - "CARTESI_LOG_LEVEL", - "CARTESI_LOG_LEVEL_ADVANCER", - "CARTESI_LOG_LEVEL_CLAIMER", - "CARTESI_LOG_LEVEL_EVM_READER", - "CARTESI_LOG_LEVEL_JSONRPC_API", - "CARTESI_LOG_LEVEL_PRT", - "CARTESI_LOG_LEVEL_VALIDATOR", - "CARTESI_JSONRPC_MACHINE_LOG_LEVEL", - // Only the mnemonic and private-key kinds are reachable here: the aws - // kind needs AWS_REGION and the SDK credential chain, which are not - // CARTESI_-prefixed and so never reach getCartesiEnvironmentVariables. - "CARTESI_PRT_AUTH_KIND", - "CARTESI_PRT_AUTH_MNEMONIC", - "CARTESI_PRT_AUTH_MNEMONIC_ACCOUNT_INDEX", - "CARTESI_PRT_AUTH_MNEMONIC_FILE", - "CARTESI_PRT_AUTH_PRIVATE_KEY", - "CARTESI_PRT_AUTH_PRIVATE_KEY_FILE", - "CARTESI_SNAPSHOTS_DIR", -] as const; - -type NodeAllowedEnvironmentVars = Partial< - Record<(typeof nodeAllowedEnvironmentVariables)[number], string> ->; - -/** - * Returns a subset of the provided environment variables that are allowed - * to be passed to the rollups node service. - * If no environment variables are provided, an empty object is returned. - * @param cartesiVars - An object containing environment variables to filter. - * @returns An object containing only the allowed environment variables. - * @param cartesiVars - * @returns - */ -export const getNodeAllowedVariables = ( - cartesiVars?: CartesiEnvironmentVariables, -): NodeAllowedEnvironmentVars => { - const allowedVars = nodeAllowedEnvironmentVariables.reduce( - (acc, variableName) => { - const value = cartesiVars?.[variableName]; - - if (value !== undefined && value !== null) { - acc[variableName] = value; - } - - return acc; - }, - {} as NodeAllowedEnvironmentVars, - ); - - return allowedVars; -}; - -/** - * The allowed variables of the node's PRT signer, which a reader-mode node - * has no use for. - */ -export const nodePrtAuthVariables = nodeAllowedEnvironmentVariables.filter( - (name) => name.startsWith("CARTESI_PRT_AUTH_"), -); - -/** - * The allowed variables that name a file the node reads its keys from. - * Forwarding only the path would leave the node without the file, so each - * one is copied into the container instead. - */ -export const nodeSecretFileVariables = nodeAllowedEnvironmentVariables.filter( - (name) => name.endsWith("_FILE"), -); - -const isPrtAuthVariable = (name: string) => - (nodePrtAuthVariables as readonly string[]).includes(name); - -/** Service that copies the key files for the node, and its volume. */ -const SECRET_INIT_SERVICE = "node-secret-init"; -const SECRETS_VOLUME = "node_secrets"; - -/** - * Returns the key files named in the host variables, each with the variable - * that points the node at its copy. - */ -const nodeFileSecrets = ( - cartesiVars: CartesiEnvironmentVariables | undefined, - claimSubmission: boolean, -): (FileSecret & { variable: string })[] => { - const allowedVars = getNodeAllowedVariables(cartesiVars); - return nodeSecretFileVariables.flatMap((variable) => { - if (!claimSubmission && isPrtAuthVariable(variable)) { - return []; - } - const hostPath = allowedVars[variable]; - return hostPath === undefined - ? [] - : [{ variable, ...fileSecret(variable.toLowerCase(), hostPath) }]; - }); -}; - -// Rollups Node service -const service = ( - options: ServiceOptions, - fileSecrets: (FileSecret & { variable: string })[], -): Service => { - const databasePassword = options.databasePassword; - const databaseHost = options.databaseHost ?? "database"; - const databasePort = options.databasePort ?? 5432; - const defaultBlock = options.defaultBlock ?? "latest"; - const imageTag = options.imageTag ?? "latest"; - const logLevel = options.logLevel ?? "info"; - const mnemonic = options.mnemonic ?? DEVNET_MNEMONIC; - const prt = options.prt ?? false; - const claimSubmission = options.claimSubmission ?? true; - const chainId = (options.forkChainId ?? - 31337) as keyof typeof daveAppFactoryAddress; - - let chainDaveAppFactoryAddress: string | undefined; - - if (prt) { - chainDaveAppFactoryAddress = daveAppFactoryAddress[chainId]; - } - - const defaultVars = { - CARTESI_AUTH_MNEMONIC: mnemonic, - // First account generated by the devnet test mnemonic 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 - CARTESI_AUTH_MNEMONIC_ACCOUNT_INDEX: "0", - CARTESI_BLOCKCHAIN_DEFAULT_BLOCK: defaultBlock, - CARTESI_BLOCKCHAIN_HTTP_ENDPOINT: "http://anvil:8545", - CARTESI_BLOCKCHAIN_ID: anvil.id.toString(), - // a deploy on an existing consensus, as the shell's redeploy does, - // creates only the application, through this factory - CARTESI_CONTRACTS_APPLICATION_FACTORY_ADDRESS: - applicationFactoryAddress, - ...(chainDaveAppFactoryAddress && { - CARTESI_CONTRACTS_DAVE_APP_FACTORY_ADDRESS: - chainDaveAppFactoryAddress, - }), - CARTESI_CONTRACTS_INPUT_BOX_ADDRESS: inputBoxAddress, - CARTESI_CONTRACTS_SELF_HOSTED_APPLICATION_FACTORY_ADDRESS: - selfHostedApplicationFactoryAddress, - CARTESI_DATABASE_CONNECTION: `postgres://postgres:${databasePassword}@${databaseHost}:${databasePort}/rollupsdb?sslmode=disable`, - CARTESI_LOG_LEVEL: logLevel, - // The node always starts its PRT service, and with claim submission - // enabled by default that service needs its own signer. PRT has no - // default mnemonic, so the devnet one is supplied explicitly. With a - // sling claimer the node reads instead, and needs no PRT signer. - ...(claimSubmission - ? { CARTESI_PRT_AUTH_MNEMONIC: mnemonic } - : { CARTESI_FEATURE_CLAIM_SUBMISSION_ENABLED: "false" }), - CARTESI_SNAPSHOTS_DIR: "/var/lib/cartesi-rollups-node/snapshots", - }; - - // the host values are the user's own and may hold a `$`, e.g. in a - // password, which compose must not interpolate - const hostVars = Object.fromEntries( - Object.entries( - getNodeAllowedVariables(options.cartesiEnvironmentVariables), - ) - // a reader-mode node has no PRT signer, so the host's is dropped - .filter(([name]) => claimSubmission || !isPrtAuthVariable(name)) - .map(([name, value]) => [name, escapeComposeValue(value)]), - ); - - // the key files reach the node as secrets, at a path inside the container - for (const { variable, target } of fileSecrets) { - hostVars[variable] = target; - } - - // Merge default and host environment variables, with host variables taking precedence - // further to the right of the parameter list the higher the precedence - // TODO: Here or somewhere else; Add other variables with precedence rules, e.g. command line > .toml > host environment > default - const environmentVariables = Object.assign({}, defaultVars, hostVars); - - return { - image: `cartesi/rollups-runtime:${imageTag}`, - init: true, - depends_on: { - database: { condition: "service_healthy" }, - anvil: { condition: "service_healthy" }, - ...(fileSecrets.length > 0 && { - [SECRET_INIT_SERVICE]: { - condition: "service_completed_successfully", - }, - }), - }, - deploy: { - resources: { - limits: { - cpus: - options.cpus !== undefined - ? options.cpus.toString() - : undefined, - memory: - options.memory !== undefined - ? `${options.memory.toString()}M` - : undefined, - }, - }, - }, - expose: ["10000", "10011", "10012"], - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:10000/livez"], - }, - command: ["cartesi-rollups-node"], - environment: { - ...environmentVariables, - }, - volumes: [ - "./.cartesi:/var/lib/cartesi-rollups-node/snapshots:ro", - ...(fileSecrets.length > 0 - ? [`${SECRETS_VOLUME}:/run/secrets:ro`] - : []), - ], - }; -}; - -// Rollups Node proxy configuration -const proxy = (): Config => { - return { - name: "rollups-node-proxy", - content: ` -http: - routers: - inspect_server: - rule: "PathPrefix(\`/inspect\`)" - middlewares: - - "cors" - service: inspect_server - rpc_server: - rule: "PathPrefix(\`/rpc\`)" - middlewares: - - "cors" - service: rpc_server - middlewares: - cors: - headers: - accessControlAllowMethods: - - GET - - OPTIONS - - POST - accessControlAllowHeaders: - - "Origin" - - "Content-Type" - - "Accept" - accessControlAllowOriginList: - - "*" - accessControlMaxAge: 86400 - addVaryHeader: true - services: - inspect_server: - loadBalancer: - servers: - - url: "http://rollups_node:10012" - rpc_server: - loadBalancer: - servers: - - url: "http://rollups_node:10011" -`, - }; -}; - -export default (options: ServiceOptions): ComposeFile => { - const fileSecrets = nodeFileSecrets( - options.cartesiEnvironmentVariables, - options.claimSubmission ?? true, - ); - - return { - services: { - proxy: { - configs: [ - { - source: "rollups_node_proxy", - target: "/etc/traefik/conf.d/rollups-node.yaml", - }, - ], - }, - rollups_node: service(options, fileSecrets), - ...(fileSecrets.length > 0 && { - [SECRET_INIT_SERVICE]: secretInitService({ - imageTag: options.imageTag ?? "latest", - secrets: fileSecrets, - volume: SECRETS_VOLUME, - }), - }), - }, - configs: { - rollups_node_proxy: proxy(), - }, - ...(fileSecrets.length > 0 && { - volumes: { [SECRETS_VOLUME]: {} }, - }), - }; -}; diff --git a/apps/cli/src/compose/passkey.ts b/apps/cli/src/compose/passkey.ts deleted file mode 100644 index df6b82262..000000000 --- a/apps/cli/src/compose/passkey.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { ComposeFile, Config, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; -}; - -// Passkey Server service -export const service = (options: ServiceOptions): Service => { - const imageTag = options.imageTag ?? "latest"; - - return { - image: `cartesi/sdk:${imageTag}`, - command: ["passkey-server"], - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:3000/health"], - }, - }; -}; - -// Passkey Proxy configuration -const proxy = (): Config => { - return { - name: "passkey-proxy", - content: `http: - routers: - passkey_server: - rule: "PathPrefix(\`/passkey\`)" - middlewares: - - "remove-passkey-server-prefix" - service: passkey_server - middlewares: - remove-passkey-server-prefix: - replacePathRegex: - regex: "^/passkey/(.*)" - replacement: "/$1" - services: - passkey_server: - loadBalancer: - servers: - - url: "http://passkey_server:3000"`, - }; -}; - -export default (options: ServiceOptions): ComposeFile => ({ - configs: { - passkey_server_proxy: proxy(), - }, - services: { - passkey_server: service(options), - proxy: { - configs: [ - { - source: "passkey_server_proxy", - target: "/etc/traefik/conf.d/passkey_server.yaml", - }, - ], - }, - }, -}); diff --git a/apps/cli/src/compose/paymaster.ts b/apps/cli/src/compose/paymaster.ts deleted file mode 100644 index 054bf6fb1..000000000 --- a/apps/cli/src/compose/paymaster.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { ComposeFile, Config, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; -}; - -const service = (options: ServiceOptions): Service => { - const imageTag = options.imageTag ?? "latest"; - - return { - image: `cartesi/sdk:${imageTag}`, - command: "mock-verifying-paymaster", - environment: { - ALTO_RPC: "http://bundler:4337", - ANVIL_RPC: "http://anvil:8545", - }, - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:3000/ping"], - }, - }; -}; - -const proxy = (): Config => { - return { - name: "paymaster-proxy", - content: `http: - routers: - paymaster: - rule: "PathPrefix(\`/paymaster\`)" - middlewares: - - "remove-paymaster-prefix" - service: paymaster - middlewares: - remove-paymaster-prefix: - replacePathRegex: - regex: "^/paymaster/(.*)" - replacement: "/$1" - services: - paymaster: - loadBalancer: - servers: - - url: "http://paymaster:3000"`, - }; -}; - -export default (options: ServiceOptions): ComposeFile => ({ - configs: { - paymaster_proxy: proxy(), - }, - services: { - paymaster: service(options), - proxy: { - configs: [ - { - source: "paymaster_proxy", - target: "/etc/traefik/conf.d/paymaster.yaml", - }, - ], - }, - }, -}); diff --git a/apps/cli/src/compose/proxy.ts b/apps/cli/src/compose/proxy.ts deleted file mode 100644 index 43cd87e16..000000000 --- a/apps/cli/src/compose/proxy.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { ComposeFile, Service } from "../types/compose.js"; -import { DEFAULT_HEALTHCHECK } from "./common.js"; - -type ServiceOptions = { - imageTag?: string; - port?: number; -}; - -const service = (options: ServiceOptions): Service => { - const imageTag = options.imageTag ?? "latest"; - const port = options.port ?? 6751; - - return { - image: `traefik:${imageTag}`, - healthcheck: { - ...DEFAULT_HEALTHCHECK, - test: ["CMD", "traefik", "healthcheck", "--ping"], - }, - command: [ - "--ping=true", - "--entryPoints.web.address=:8088", - "--entryPoints.traefik.address=:8080", - "--metrics.prometheus=true", - "--metrics.prometheus.addServicesLabels=true", - "--providers.file.directory=/etc/traefik/conf.d", - "--providers.file.watch=true", - "--log", - "--log.level=INFO", - ], - ports: [`${port}:8088`], - }; -}; - -export default (options: ServiceOptions): ComposeFile => ({ - services: { - proxy: service(options), - }, -}); diff --git a/apps/cli/src/compose/prt-node.ts b/apps/cli/src/compose/prt-node.ts deleted file mode 100644 index 0f1516fb3..000000000 --- a/apps/cli/src/compose/prt-node.ts +++ /dev/null @@ -1,129 +0,0 @@ -import type { Address } from "viem"; -import { anvil } from "viem/chains"; -import type { ResolvedPrtNode } from "../prt.js"; -import type { ComposeFile, Service } from "../types/compose.js"; -import { fileSecret, secretInitService } from "./secrets.js"; - -/** - * The compose services of the PRT nodes the CLI runs: one sling node per - * [prt.nodes.