|
| 1 | +import { spawn } from "node:child_process"; |
| 2 | +import fs from "node:fs/promises"; |
| 3 | +import path from "node:path"; |
| 4 | +import { expectDefined } from "@openclaw/normalization-core"; |
| 5 | +import type { SandboxBackendHandle, SandboxFsBridge } from "openclaw/plugin-sdk/sandbox"; |
| 6 | +import { expect } from "vitest"; |
| 7 | + |
| 8 | +type ExecResult = { |
| 9 | + code: number; |
| 10 | + stdout: string; |
| 11 | + stderr: string; |
| 12 | +}; |
| 13 | + |
| 14 | +export async function runCommand(params: { |
| 15 | + command: string; |
| 16 | + args: string[]; |
| 17 | + cwd?: string; |
| 18 | + env?: NodeJS.ProcessEnv; |
| 19 | + stdin?: string | Uint8Array; |
| 20 | + allowFailure?: boolean; |
| 21 | + timeoutMs?: number; |
| 22 | +}): Promise<ExecResult> { |
| 23 | + return await new Promise((resolve, reject) => { |
| 24 | + const child = spawn(params.command, params.args, { |
| 25 | + cwd: params.cwd, |
| 26 | + env: params.env, |
| 27 | + stdio: ["pipe", "pipe", "pipe"], |
| 28 | + }); |
| 29 | + const stdoutChunks: Buffer[] = []; |
| 30 | + const stderrChunks: Buffer[] = []; |
| 31 | + let timedOut = false; |
| 32 | + const timeout = |
| 33 | + params.timeoutMs && params.timeoutMs > 0 |
| 34 | + ? setTimeout(() => { |
| 35 | + timedOut = true; |
| 36 | + child.kill("SIGKILL"); |
| 37 | + }, params.timeoutMs) |
| 38 | + : null; |
| 39 | + |
| 40 | + child.stdout.on("data", (chunk) => stdoutChunks.push(Buffer.from(chunk))); |
| 41 | + child.stderr.on("data", (chunk) => stderrChunks.push(Buffer.from(chunk))); |
| 42 | + child.on("error", reject); |
| 43 | + child.on("close", (code) => { |
| 44 | + if (timeout) { |
| 45 | + clearTimeout(timeout); |
| 46 | + } |
| 47 | + const stdout = Buffer.concat(stdoutChunks).toString("utf8"); |
| 48 | + const stderr = Buffer.concat(stderrChunks).toString("utf8"); |
| 49 | + if (timedOut) { |
| 50 | + reject(new Error(`command timed out: ${params.command} ${params.args.join(" ")}`)); |
| 51 | + return; |
| 52 | + } |
| 53 | + const exitCode = code ?? 1; |
| 54 | + if (exitCode !== 0 && !params.allowFailure) { |
| 55 | + const message = [ |
| 56 | + `command failed: ${params.command} ${params.args.join(" ")}`, |
| 57 | + `exit: ${exitCode}`, |
| 58 | + ]; |
| 59 | + const trimmedStdout = stdout.trim(); |
| 60 | + if (trimmedStdout.length > 0) { |
| 61 | + message.push(`stdout:\n${stdout}`); |
| 62 | + } |
| 63 | + const trimmedStderr = stderr.trim(); |
| 64 | + if (trimmedStderr.length > 0) { |
| 65 | + message.push(`stderr:\n${stderr}`); |
| 66 | + } |
| 67 | + reject(new Error(message.join("\n"))); |
| 68 | + return; |
| 69 | + } |
| 70 | + resolve({ code: exitCode, stdout, stderr }); |
| 71 | + }); |
| 72 | + |
| 73 | + child.stdin.end(params.stdin); |
| 74 | + }); |
| 75 | +} |
| 76 | + |
| 77 | +export async function runBackendExec(params: { |
| 78 | + backend: SandboxBackendHandle; |
| 79 | + command: string; |
| 80 | + env?: Record<string, string>; |
| 81 | + allowFailure?: boolean; |
| 82 | + timeoutMs?: number; |
| 83 | +}): Promise<ExecResult> { |
| 84 | + const execSpec = await params.backend.buildExecSpec({ |
| 85 | + command: params.command, |
| 86 | + env: params.env ?? {}, |
| 87 | + usePty: false, |
| 88 | + }); |
| 89 | + return await runPreparedBackendExec({ ...params, execSpec }); |
| 90 | +} |
| 91 | + |
| 92 | +export async function runPreparedBackendExec(params: { |
| 93 | + backend: SandboxBackendHandle; |
| 94 | + execSpec: Awaited<ReturnType<SandboxBackendHandle["buildExecSpec"]>>; |
| 95 | + allowFailure?: boolean; |
| 96 | + timeoutMs?: number; |
| 97 | +}): Promise<ExecResult> { |
| 98 | + const { execSpec } = params; |
| 99 | + let result: ExecResult | null | undefined; |
| 100 | + try { |
| 101 | + result = await runCommand({ |
| 102 | + command: execSpec.argv[0] ?? "ssh", |
| 103 | + args: execSpec.argv.slice(1), |
| 104 | + env: execSpec.env, |
| 105 | + allowFailure: params.allowFailure, |
| 106 | + timeoutMs: params.timeoutMs, |
| 107 | + }); |
| 108 | + return result; |
| 109 | + } finally { |
| 110 | + await params.backend.finalizeExec?.({ |
| 111 | + status: result?.code === 0 ? "completed" : "failed", |
| 112 | + exitCode: result?.code ?? 1, |
| 113 | + timedOut: false, |
| 114 | + token: execSpec.finalizeToken, |
| 115 | + }); |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +export async function stressBackend(params: { |
| 120 | + backends: Array<Parameters<typeof runBackendExec>[0]["backend"]>; |
| 121 | + bridge: SandboxFsBridge; |
| 122 | + mode: "mirror" | "remote"; |
| 123 | + workspaceDir: string; |
| 124 | +}): Promise<void> { |
| 125 | + const startedAt = Date.now(); |
| 126 | + const expectedIds: string[] = []; |
| 127 | + const latencies: number[] = []; |
| 128 | + const waves = 8; |
| 129 | + const concurrency = 8; |
| 130 | + for (let wave = 0; wave < waves; wave++) { |
| 131 | + // Keep all writes under one directory so mirror upload cost stays independent of task count. |
| 132 | + const results = await Promise.allSettled( |
| 133 | + Array.from({ length: concurrency }, async (_, slot) => { |
| 134 | + const id = `${wave}-${slot}`; |
| 135 | + const started = Date.now(); |
| 136 | + const backend = params.backends[(wave + Math.floor(slot / 2)) % params.backends.length]!; |
| 137 | + if (slot % 2 === 0) { |
| 138 | + expectedIds.push(id); |
| 139 | + const exitCode = slot === 0 ? 23 : 0; |
| 140 | + const result = await runBackendExec({ |
| 141 | + backend, |
| 142 | + command: `mkdir -p stress; n=$(cat stress/count 2>/dev/null || echo 0); sleep 0.02; printf '%s\\n' "$((n + 1))" > stress/count; printf '%s\\n' '${id}' >> stress/ledger; printf '%s' "$STRESS_VALUE" > 'stress/@exec-${id}'; exit ${exitCode}`, |
| 143 | + env: { STRESS_VALUE: `value-${id}` }, |
| 144 | + allowFailure: true, |
| 145 | + timeoutMs: 60_000, |
| 146 | + }); |
| 147 | + expect(result.code).toBe(exitCode); |
| 148 | + } else { |
| 149 | + const filePath = `stress/@file-${id}`; |
| 150 | + await params.bridge.writeFile({ filePath, data: id, mkdir: true }); |
| 151 | + const temporaryPath = `stress/tmp-${id}`; |
| 152 | + switch (slot) { |
| 153 | + case 1: |
| 154 | + await expect( |
| 155 | + params.bridge.createFileExclusive?.({ filePath, data: "overwrite" }), |
| 156 | + ).resolves.toBe("exists"); |
| 157 | + break; |
| 158 | + case 3: |
| 159 | + await expect( |
| 160 | + params.bridge.createFileExclusive?.({ filePath: temporaryPath, data: id }), |
| 161 | + ).resolves.toBe("created"); |
| 162 | + await params.bridge.rename({ from: temporaryPath, to: `stress/@renamed-${id}` }); |
| 163 | + break; |
| 164 | + case 5: |
| 165 | + await params.bridge.mkdirp({ filePath: temporaryPath }); |
| 166 | + await params.bridge.remove({ filePath: temporaryPath, recursive: true }); |
| 167 | + break; |
| 168 | + case 7: |
| 169 | + await expect(params.bridge.stat({ filePath })).resolves.toMatchObject({ |
| 170 | + type: "file", |
| 171 | + size: Buffer.byteLength(id), |
| 172 | + }); |
| 173 | + break; |
| 174 | + } |
| 175 | + } |
| 176 | + latencies.push(Date.now() - started); |
| 177 | + }), |
| 178 | + ); |
| 179 | + const failures = results.filter((result) => result.status === "rejected"); |
| 180 | + if (failures.length > 0) { |
| 181 | + throw new AggregateError( |
| 182 | + failures.map((failure) => failure.reason), |
| 183 | + "OpenShell stress wave failed", |
| 184 | + ); |
| 185 | + } |
| 186 | + await expect(params.bridge.readFile({ filePath: `stress/@file-${wave}-1` })).resolves.toEqual( |
| 187 | + Buffer.from(`${wave}-1`), |
| 188 | + ); |
| 189 | + console.log( |
| 190 | + JSON.stringify({ |
| 191 | + probe: "openshell-stress-progress", |
| 192 | + mode: params.mode, |
| 193 | + completedWorkflows: (wave + 1) * concurrency, |
| 194 | + elapsedMs: Date.now() - startedAt, |
| 195 | + }), |
| 196 | + ); |
| 197 | + } |
| 198 | + // Read the remote tree without exec preparation: a fresh mirror upload could hide divergence. |
| 199 | + const inventory = await params.backends[0]!.runShellCommand({ |
| 200 | + script: `python3 -c 'import json,pathlib,sys; root=pathlib.Path(sys.argv[1]); print(json.dumps({str(p.relative_to(root)):p.read_text() for p in root.rglob("*") if p.is_file()}))' "$1"`, |
| 201 | + args: [`${params.backends[0]!.workdir}/stress`], |
| 202 | + }); |
| 203 | + const remoteFiles = JSON.parse(inventory.stdout.toString("utf8")) as Record<string, string>; |
| 204 | + const ledger = expectDefined(remoteFiles.ledger, "OpenShell remote command ledger"); |
| 205 | + expect(ledger.trim().split("\n").toSorted()).toEqual(expectedIds.toSorted()); |
| 206 | + const expectedFiles: Record<string, string> = { |
| 207 | + ledger, |
| 208 | + count: `${expectedIds.length}\n`, |
| 209 | + }; |
| 210 | + for (let wave = 0; wave < waves; wave++) { |
| 211 | + for (let slot = 0; slot < concurrency; slot++) { |
| 212 | + const id = `${wave}-${slot}`; |
| 213 | + const filePath = `stress/@${slot % 2 === 0 ? "exec" : "file"}-${id}`; |
| 214 | + const expected = slot % 2 === 0 ? `value-${id}` : id; |
| 215 | + expectedFiles[path.posix.basename(filePath)] = expected; |
| 216 | + if (slot === 3) { |
| 217 | + expectedFiles[`@renamed-${id}`] = id; |
| 218 | + } |
| 219 | + } |
| 220 | + } |
| 221 | + expect(remoteFiles).toEqual(expectedFiles); |
| 222 | + if (params.mode === "mirror") { |
| 223 | + expect((await fs.readdir(path.join(params.workspaceDir, "stress"))).toSorted()).toEqual( |
| 224 | + Object.keys(expectedFiles).toSorted(), |
| 225 | + ); |
| 226 | + for (const [file, expected] of Object.entries(expectedFiles)) { |
| 227 | + await expect(params.bridge.readFile({ filePath: `stress/${file}` })).resolves.toEqual( |
| 228 | + Buffer.from(expected), |
| 229 | + ); |
| 230 | + } |
| 231 | + } |
| 232 | + if (params.mode === "remote") { |
| 233 | + await expect(fs.stat(path.join(params.workspaceDir, "stress"))).rejects.toMatchObject({ |
| 234 | + code: "ENOENT", |
| 235 | + }); |
| 236 | + } |
| 237 | + const orderedLatencies = latencies.toSorted((a, b) => a - b); |
| 238 | + console.log( |
| 239 | + JSON.stringify({ |
| 240 | + probe: "openshell-stress", |
| 241 | + mode: params.mode, |
| 242 | + workflows: waves * concurrency, |
| 243 | + concurrency, |
| 244 | + commands: expectedIds.length, |
| 245 | + intentionalCommandFailures: waves, |
| 246 | + elapsedMs: Date.now() - startedAt, |
| 247 | + p50Ms: orderedLatencies[Math.floor(latencies.length / 2)], |
| 248 | + p95Ms: orderedLatencies[Math.floor(latencies.length * 0.95)], |
| 249 | + verifiedFiles: Object.keys(expectedFiles).length - 2, |
| 250 | + }), |
| 251 | + ); |
| 252 | +} |
0 commit comments