Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

handle.ts

566 lines16.8 KB

1/**
2 * SandboxHandle backed by a Docker Sandboxes microVM (`sbx exec`).
3 *
4 * fs is the same chunked base64-over-exec design as the container handle.
5 * Kill uses the same in-VM pid file. Do not only kill the host `sbx exec`
6 * process.
7 *
8 * `writableStdin` and `killableProcesses` stay false until a live
9 * measurement after `sbx login`.
10 */
11import { randomUUID } from 'node:crypto'
12import { createExecBackedGit } from '@tanstack/ai-sandbox'
13import {
14 parseJsonAfterBanner,
15 runSbx,
16 runSbxStreaming,
17 sbxExecArgs,
18} from './cli'
19import { fsWriteCommands } from '../fs-write'
20import { removeOwnedClone, sandboxNameFromId } from './materialize'
21import type {
22 ExecResult,
23 ProcessOptions,
24 SandboxCapabilities,
25 SandboxChannel,
26 SandboxHandle,
27 SpawnHandle,
28} from '@tanstack/ai-sandbox'
29import type { SbxSpawn } from './cli'
30​
31export const SBX_CAPS: SandboxCapabilities = {
32 fs: true,
33 exec: true,
34 env: true,
35 ports: true,
36 backgroundProcesses: true,
37 // Stay false until a live measurement after `sbx login` proves stdin works.
38 writableStdin: false,
39 // Stay false until a live measurement after `sbx login` proves in-VM kill.
40 killableProcesses: false,
41 snapshots: false,
42 networkPolicy: true,
43 durableFilesystem: true,
44 fork: false,
46​
47export interface SbxLogger {
48 warn: (message: string, meta?: Record<string, unknown>) => void
50​
51/** POSIX single-quote escape for embedding paths in `sh -c`. */
52function q(value: string): string {
53 return `'${value.replace(/'/g, `'\\''`)}'`
55​
56const KILL_FAILED_MARKER = 'tanstack-sandbox-kill-failed'
57const KILL_NO_PID_MARKER = 'tanstack-sandbox-kill-no-pid'
58​
59function pidRecordingCommand(command: string, pidFile: string): string {
60 return `echo $$ > ${q(pidFile)}; exec sh -c ${q(command)}`
62​
63function killSignalArg(signal?: NodeJS.Signals | number): string {
64 if (typeof signal === 'number' && Number.isInteger(signal) && signal > 0) {
65 return String(signal)
66 }
67 if (typeof signal === 'string') {
68 const name = signal.replace(/^SIG/, '')
69 if (/^[A-Z][A-Z0-9]*$/.test(name)) return name
70 }
71 return 'TERM'
73​
74const PID_WAIT_TIMEOUT_MS = 2000
75const PID_WAIT_INTERVAL_MS = 50
76const KILL_ESCALATION_DELAY_MS = 200
77​
78function killRecordedPidCommand(
79 pidFile: string,
80 signal?: NodeJS.Signals | number,
81): string {
82 const sig = killSignalArg(signal)
83 const f = q(pidFile)
84 const attempts = Math.ceil(PID_WAIT_TIMEOUT_MS / PID_WAIT_INTERVAL_MS)
85 const sleepStep = (PID_WAIT_INTERVAL_MS / 1000).toFixed(3)
86 return [
87 `pid=''`,
88 `i=0`,
89 `while [ "$i" -lt ${attempts} ]; do`,
90 ` pid=$(cat ${f} 2>/dev/null)`,
91 ` [ -n "$pid" ] && break`,
92 ` sleep ${sleepStep}`,
93 ` i=$((i+1))`,
94 `done`,
95 `if [ -n "$pid" ]; then`,
96 ` kill -${sig} -"$pid" 2>/dev/null || kill -${sig} "$pid" 2>/dev/null`,
97 ` sleep ${(KILL_ESCALATION_DELAY_MS / 1000).toFixed(3)}`,
98 ` kill -KILL -"$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null`,
99 ` if kill -0 "$pid" 2>/dev/null; then`,
100 ` echo ${KILL_FAILED_MARKER} pid="$pid" >&2`,
101 ` fi`,
102 `else`,
103 ` echo ${KILL_NO_PID_MARKER} file=${f} >&2`,
104 `fi`,
105 `rm -f ${f}`,
106 `:`,
107 ].join('\n')
109​
110interface PidFileState {
111 exited: boolean
112 killRequested: boolean
113 kill?: Promise<void>
115​
116async function* decodeStream(
117 chunks: AsyncIterable<Buffer | string>,
118): AsyncIterable<string> {
119 const decoder = new TextDecoder('utf-8')
120 for await (const chunk of chunks) {
121 yield typeof chunk === 'string'
122 ? chunk
123 : decoder.decode(chunk, { stream: true })
124 }
125 const tail = decoder.decode()
126 if (tail !== '') yield tail
128​
129function asRecord(value: unknown): Record<string, unknown> | null {
130 if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
131 return value as Record<string, unknown>
132 }
133 return null
135​
136function numericPort(value: unknown): number | undefined {
137 if (typeof value === 'number') return value
138 if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)
139 return undefined
141​
142function hostPortFromPortsJson(stdout: string, port: number): number | null {
143 const parsed: unknown = parseJsonAfterBanner(stdout)
144 const rec = asRecord(parsed)
145 if (rec) {
146 const host = numericPort(rec[String(port)])
147 if (host !== undefined) return host
148 }
149 if (Array.isArray(parsed)) {
150 for (const item of parsed) {
151 const entry = asRecord(item)
152 if (!entry) continue
153 const guest =
154 numericPort(entry.sandbox_port) ??
155 numericPort(entry.port) ??
156 numericPort(entry.Port)
157 const host =
158 numericPort(entry.host_port) ??
159 numericPort(entry.hostPort) ??
160 numericPort(entry.HostPort)
161 if (guest === port && host !== undefined) return host
162 }
163 }
164 return null
166​
167export function isAlreadyGone(error: unknown): boolean {
168 const message = error instanceof Error ? error.message : String(error)
169 return /(?:sandbox|vm|container)(?:\s+(?:'[^']+'|"[^"]+"|\S+))?\s+not found|not found\s+(?:sandbox|vm|container)|no such\s+(?:sandbox|vm|container)/i.test(
170 message,
171 )
173​
174export function isNameAlreadyExists(error: unknown): boolean {
175 const message = error instanceof Error ? error.message : String(error)
176 return /(?:sandbox|vm|container).{0,80}already exists/i.test(message)
178​
179/** Host login or transport text that `test -e` never prints for a missing path. */
180function isLoginOrTransportError(stderr: string): boolean {
181 const text = stderr.toLowerCase()
182 return (
183 text.includes('unauthorized') ||
184 text.includes('not logged in') ||
185 text.includes('not authenticated') ||
186 text.includes('connection refused') ||
187 text.includes('econnrefused')
188 )
190​
191/** Quiet `test -e` miss, or the usual one-line diagnostic. */
192function isNormalTestMiss(stderr: string): boolean {
193 const text = stderr.trim()
194 return text === '' || text.toLowerCase().includes('no such file or directory')
196​
197export interface SbxHandleDeps {
198 name: string
199 workspaceRoot: string
200 binary?: string
201 spawn?: SbxSpawn
202 logger?: SbxLogger
203 /** When true, destroy also deletes `tmpdir/tanstack-sbx/<name>`. Default false. */
204 owned?: boolean
206​
207export class SbxHandle implements SandboxHandle {
208 readonly id: string
209 readonly provider = 'sbx'
210 readonly workspaceRoot: string
211 readonly capabilities = SBX_CAPS
212 readonly fs: SandboxHandle['fs']
213 readonly git: SandboxHandle['git']
214 readonly process: SandboxHandle['process']
215 readonly ports: SandboxHandle['ports']
216 readonly env: SandboxHandle['env']
217​
218 private readonly name: string
219 private readonly binary: string
220 private readonly spawnFn: SbxSpawn | undefined
221 private readonly logger: SbxLogger | undefined
222 private readonly owned: boolean
223 private readonly envVars: Record<string, string> = {}
224​
225 constructor(deps: SbxHandleDeps) {
226 this.name = deps.name
227 this.id = deps.name
228 this.workspaceRoot = deps.workspaceRoot
229 this.binary = deps.binary ?? 'sbx'
230 this.spawnFn = deps.spawn
231 this.logger = deps.logger
232 this.owned = deps.owned ?? false
233​
234 this.process = {
235 exec: (command, opts) => this.exec(command, opts),
236 spawn: (command, opts) => this.spawnProcess(command, opts),
237 }
238​
239 this.fs = {
240 read: async (p) => {
241 const r = await this.exec(`base64 ${q(this.abs(p))}`)
242 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
243 return Buffer.from(r.stdout, 'base64').toString('utf8')
244 },
245 readBytes: async (p) => {
246 const r = await this.exec(`base64 ${q(this.abs(p))}`)
247 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
248 return new Uint8Array(Buffer.from(r.stdout, 'base64'))
249 },
250 write: async (p, data) => {
251 for (const command of fsWriteCommands(this.abs(p), data)) {
252 const r = await this.exec(command)
253 if (r.exitCode !== 0)
254 throw new Error(`write failed: ${r.stderr.trim()}`)
255 }
256 },
257 list: async (p) => {
258 const r = await this.exec(`ls -1Ap ${q(this.abs(p))}`)
259 if (r.exitCode !== 0) throw new Error(`list failed: ${r.stderr.trim()}`)
260 return r.stdout
261 .split('\n')
262 .filter((line) => line.trim() !== '')
263 .map((entry) => {
264 const isDir = entry.endsWith('/')
265 const name = isDir ? entry.slice(0, -1) : entry
266 return {
267 name,
268 path: `${p.replace(/\/$/, '')}/${name}`,
269 type: isDir ? ('dir' as const) : ('file' as const),
270 }
271 })
272 },
273 mkdir: async (p) => {
274 const r = await this.exec(`mkdir -p ${q(this.abs(p))}`)
275 if (r.exitCode !== 0)
276 throw new Error(`mkdir failed: ${r.stderr.trim()}`)
277 },
278 remove: async (p) => {
279 const r = await this.exec(`rm -rf ${q(this.abs(p))}`)
280 if (r.exitCode !== 0)
281 throw new Error(`remove failed: ${r.stderr.trim()}`)
282 },
283 rename: async (from, to) => {
284 const r = await this.exec(`mv ${q(this.abs(from))} ${q(this.abs(to))}`)
285 if (r.exitCode !== 0)
286 throw new Error(`rename failed: ${r.stderr.trim()}`)
287 },
288 exists: async (p) => {
289 const r = await this.exec(`test -e ${q(this.abs(p))}`)
290 // `exec` uses allowNonZero, so login/transport must not look like a miss.
291 if (isLoginOrTransportError(r.stderr)) {
292 throw new Error(
293 r.stderr.trim() || `exists failed: exit ${r.exitCode}`,
294 )
295 }
296 if (r.exitCode === 0) return true
297 if (r.exitCode === 1 && isNormalTestMiss(r.stderr)) return false
298 throw new Error(r.stderr.trim() || `exists failed: exit ${r.exitCode}`)
299 },
300 }
301​
302 this.git = createExecBackedGit(this.process, this.workspaceRoot)
303​
304 this.ports = {
305 connect: (port) => this.connectPort(port),
306 }
307​
308 this.env = {
309 set: (vars) => {
310 Object.assign(this.envVars, vars)
311 return Promise.resolve()
312 },
313 }
314 }
315​
316 private abs(p: string): string {
317 if (this.workspaceRoot === '/workspace') return p
318 if (p === '/workspace') return this.workspaceRoot
319 if (p.startsWith('/workspace/')) {
320 return `${this.workspaceRoot}/${p.slice('/workspace/'.length)}`
321 }
322 return p
323 }
324​
325 private runOptions(): { binary: string; spawn?: SbxSpawn } {
326 return {
327 binary: this.binary,
328 ...(this.spawnFn ? { spawn: this.spawnFn } : {}),
329 }
330 }
331​
332 private execArgs(command: string, opts?: ProcessOptions): Array<string> {
333 const cwd = opts?.cwd ? this.abs(opts.cwd) : this.workspaceRoot
334 return sbxExecArgs(this.name, command, {
335 cwd,
336 env: { ...this.envVars, ...opts?.env },
337 })
338 }
339​
340 private killRecordedPid(
341 pidFile: string,
342 state: PidFileState,
343 signal?: NodeJS.Signals | number,
344 ): Promise<void> {
345 if (state.exited) return Promise.resolve()
346 state.killRequested = true
347 state.kill ??= this.runRecordedKill(pidFile, signal)
348 return state.kill
349 }
350​
351 private async runRecordedKill(
352 pidFile: string,
353 signal?: NodeJS.Signals | number,
354 ): Promise<void> {
355 let result: ExecResult
356 try {
357 result = await this.exec(killRecordedPidCommand(pidFile, signal))
358 } catch (error) {
359 this.logger?.warn('sbx: could not run the in-VM kill', {
360 pidFile,
361 error: error instanceof Error ? error.message : String(error),
362 })
363 return
364 }
365 if (result.stderr.includes(KILL_FAILED_MARKER)) {
366 this.logger?.warn(
367 'sbx: in-VM process survived the kill; it may be orphaned',
368 { pidFile, stderr: result.stderr.trim() },
369 )
370 } else if (result.stderr.includes(KILL_NO_PID_MARKER)) {
371 this.logger?.warn(
372 'sbx: no pid was recorded for this process, so it could not be signalled',
373 { pidFile, stderr: result.stderr.trim() },
374 )
375 }
376 }
377​
378 private removePidFile(pidFile: string): void {
379 void this.exec(`rm -f ${q(pidFile)}`).catch(() => {
380 // Sandbox already gone.
381 })
382 }
383​
384 private async exec(
385 command: string,
386 opts?: ProcessOptions,
387 ): Promise<ExecResult> {
388 const signal = opts?.signal
389 // Already aborted: do not start a kill waiter or the in-VM command.
390 signal?.throwIfAborted()
391 const pidFile = signal
392 ? `/tmp/.tanstack-sandbox-exec-${randomUUID()}.pid`
393 : undefined
394 const wrapped =
395 pidFile === undefined ? command : pidRecordingCommand(command, pidFile)
396 const state: PidFileState = { exited: false, killRequested: false }
397 const onAbort = (): void => {
398 if (pidFile !== undefined) void this.killRecordedPid(pidFile, state)
399 }
400 if (signal) {
401 signal.addEventListener('abort', onAbort, { once: true })
402 }
403 try {
404 const result = await runSbx(this.execArgs(wrapped, opts), {
405 ...this.runOptions(),
406 allowNonZero: true,
407 ...(signal ? { signal } : {}),
408 })
409 return {
410 stdout: result.stdout,
411 stderr: result.stderr,
412 exitCode: result.exitCode,
413 }
414 } finally {
415 if (signal) signal.removeEventListener('abort', onAbort)
416 if (pidFile !== undefined && !state.killRequested) {
417 state.exited = true
418 this.removePidFile(pidFile)
419 }
420 }
421 }
422​
423 private async spawnProcess(
424 command: string,
425 opts?: ProcessOptions,
426 ): Promise<SpawnHandle> {
427 const signal = opts?.signal
428 // Already aborted: do not start a kill waiter or the in-VM command.
429 signal?.throwIfAborted()
430 const pidFile = `/tmp/.tanstack-sandbox-spawn-${randomUUID()}.pid`
431 const state: PidFileState = { exited: false, killRequested: false }
432 const stdoutChunks: Array<Buffer> = []
433 const stderrChunks: Array<Buffer> = []
434 const stdoutWaiters: Array<() => void> = []
435 const stderrWaiters: Array<() => void> = []
436 let stdoutDone = false
437 let stderrDone = false
438​
439 const push = (
440 list: Array<Buffer>,
441 waiters: Array<() => void>,
442 chunk: Buffer,
443 ): void => {
444 list.push(chunk)
445 for (const wake of waiters) wake()
446 waiters.length = 0
447 }
448​
449 const finish = (done: () => void, waiters: Array<() => void>): void => {
450 done()
451 for (const wake of waiters) wake()
452 waiters.length = 0
453 }
454​
455 const child = runSbxStreaming(
456 this.execArgs(pidRecordingCommand(command, pidFile), opts),
457 {
458 ...this.runOptions(),
459 ...(signal ? { signal } : {}),
460 onStdout: (chunk) => push(stdoutChunks, stdoutWaiters, chunk),
461 onStderr: (chunk) => push(stderrChunks, stderrWaiters, chunk),
462 },
463 )
464​
465 const waitResult = child.wait().finally(() => {
466 finish(() => {
467 stdoutDone = true
468 }, stdoutWaiters)
469 finish(() => {
470 stderrDone = true
471 }, stderrWaiters)
472 if (!state.killRequested && !state.exited) {
473 state.exited = true
474 this.removePidFile(pidFile)
475 }
476 })
477​
478 async function* readSide(
479 list: Array<Buffer>,
480 waiters: Array<() => void>,
481 isDone: () => boolean,
482 ): AsyncIterable<Buffer> {
483 while (true) {
484 const next = list.shift()
485 if (next !== undefined) {
486 yield next
487 continue
488 }
489 if (isDone()) return
490 await new Promise<void>((resolve) => {
491 waiters.push(resolve)
492 })
493 }
494 }
495​
496 const onAbort = (): void => {
497 void this.killRecordedPid(pidFile, state)
498 child.kill()
499 }
500 if (signal) {
501 signal.addEventListener('abort', onAbort, { once: true })
502 void waitResult.finally(() => {
503 signal.removeEventListener('abort', onAbort)
504 })
505 }
506​
507 return {
508 pid: -1,
509 stdout: decodeStream(
510 readSide(stdoutChunks, stdoutWaiters, () => stdoutDone),
511 ),
512 stderr: decodeStream(
513 readSide(stderrChunks, stderrWaiters, () => stderrDone),
514 ),
515 stdin: {
516 write: () =>
517 Promise.reject(
518 new Error(
519 'sbx: background process stdin is not writable (see capabilities.writableStdin)',
520 ),
521 ),
522 end: () => Promise.resolve(),
523 },
524 wait: async () => {
525 const result = await waitResult
526 return result.exitCode
527 },
528 kill: async (killSignal) => {
529 await this.killRecordedPid(pidFile, state, killSignal)
530 child.kill()
531 },
532 }
533 }
534​
535 private async connectPort(port: number): Promise<SandboxChannel> {
536 await runSbx(
537 ['ports', this.name, '--publish', String(port)],
538 this.runOptions(),
539 )
540 const listed = await runSbx(
541 ['ports', this.name, '--json'],
542 this.runOptions(),
543 )
544 const hostPort = hostPortFromPortsJson(listed.stdout, port)
545 if (hostPort === null) {
546 throw new Error(
547 `sbx: sandbox port ${port} is not in sbx ports --json after publish.`,
548 )
549 }
550 return { url: `http://localhost:${hostPort}` }
551 }
552​
553 async destroy(): Promise<void> {
554 const name = sandboxNameFromId(this.name)
555 let rmError: unknown
556 try {
557 await runSbx(['rm', '--force', name], this.runOptions())
558 } catch (error) {
559 rmError = error
560 }
561 if (this.owned) {
562 await removeOwnedClone(name)
563 }
564 if (rmError && !isAlreadyGone(rmError)) throw rmError
565 }