import "./sprites-cjs-shim"; import { randomBytes } from "node:crypto"; import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process"; import { stat } from "node:fs/promises"; import { promisify } from "node:util"; import { ExecError, SpritesClient, type Checkpoint, type Sprite, type SpriteCommand, type SpriteConfig, type StreamMessage, } from "@fly/sprites"; import type { CheckpointSummary, SpriteSummary, TokenSource, WorkerSummary, } from "../shared/contracts"; import type { FlySpritesSettings } from "../shared/settings"; import type { OpenBaoClient } from "./openbao-client"; const execFileAsync = promisify(nodeExecFile); const MAX_OUTPUT_BYTES = 256 * 1024; const TAIL_CHARS = 4000; export type { TokenSource }; export interface TrackedWorker { workerId: string; spriteName: string; command: string; cwd: string; status: WorkerSummary["status"]; exitCode: number | null; error: string | null; startedAt: string; endedAt: string | null; output: string; outputBytes: number; cmd?: SpriteCommand; } export function shellQuote(value: string): string { return `'${value.replace(/'/g, `'\\''`)}'`; } export function sanitizeSpriteName(raw: string): string { const cleaned = raw .toLowerCase() .replace(/[^a-z0-9-]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 56); return cleaned || `paseo-worker-${randomBytes(3).toString("hex")}`; } function toSpriteSummary(sprite: Sprite): SpriteSummary { return { name: sprite.name, id: sprite.id, status: sprite.status ?? "unknown", organization: sprite.organizationName, primaryRegion: sprite.primaryRegion, url: sprite.url, createdAt: sprite.createdAt?.toISOString(), updatedAt: sprite.updatedAt?.toISOString(), }; } function toWorkerSummary(worker: TrackedWorker): WorkerSummary { return { workerId: worker.workerId, spriteName: worker.spriteName, command: worker.command, cwd: worker.cwd, status: worker.status, exitCode: worker.exitCode, error: worker.error, startedAt: worker.startedAt, endedAt: worker.endedAt, outputTail: worker.output.length > TAIL_CHARS ? worker.output.slice(-TAIL_CHARS) : worker.output, outputBytes: worker.outputBytes, }; } function formatCheckpointStreamMessage(msg: StreamMessage): string { if (msg.data) return `${msg.type}: ${msg.data}`; if (msg.error) return `error: ${msg.error}`; return msg.type; } export class SpritesManager { private readonly getSettings: () => Promise; private readonly openbao: OpenBaoClient; private cachedClient: { key: string; client: SpritesClient } | null = null; private readonly workers = new Map(); private readonly listeners = new Set<(workers: WorkerSummary[]) => void>(); private notifyTimer: ReturnType | null = null; constructor(getSettings: () => Promise, openbao: OpenBaoClient) { this.getSettings = getSettings; this.openbao = openbao; } async resolveToken(): Promise<{ token: string; source: TokenSource; baseUrl: string }> { const settings = await this.getSettings(); const baseUrl = settings.baseUrl.trim() || "https://api.sprites.dev"; const fromSettings = settings.token.trim(); if (fromSettings) { return { token: fromSettings, source: "settings", baseUrl }; } if (settings.openbaoEnabled) { const fromOpenBao = await this.openbao.getSecretToken(); if (fromOpenBao) { return { token: fromOpenBao, source: "openbao", baseUrl }; } } const fromEnv = process.env.SPRITES_TOKEN?.trim() || process.env.FLY_TOKEN?.trim() || process.env.FLY_API_TOKEN?.trim() || ""; if (fromEnv) { return { token: fromEnv, source: "env", baseUrl }; } return { token: "", source: "none", baseUrl }; } async getClient(): Promise<{ client: SpritesClient; source: Exclude; settings: FlySpritesSettings }> { const settings = await this.getSettings(); const { token, source, baseUrl } = await this.resolveToken(); if (!token || source === "none") { throw new Error( "Fly Sprites token is not configured. Sign in with Zitadel (OpenBao), set it in Fly Sprites Workers settings, or export FLY_TOKEN / SPRITES_TOKEN.", ); } const key = `${baseUrl}::${token}`; if (!this.cachedClient || this.cachedClient.key !== key) { this.cachedClient = { key, client: new SpritesClient(token, { baseURL: baseUrl }), }; } return { client: this.cachedClient.client, source, settings }; } async buildSpriteConfig(overrides?: Partial): Promise { const settings = await this.getSettings(); const config: SpriteConfig = {}; const region = overrides?.region?.trim() || settings.defaultRegion.trim(); const ramMB = overrides?.ramMB ?? settings.defaultRamMB; const cpus = overrides?.cpus ?? settings.defaultCpus; if (region) config.region = region; if (ramMB && ramMB > 0) config.ramMB = ramMB; if (cpus && cpus > 0) config.cpus = cpus; return Object.keys(config).length > 0 ? config : undefined; } async generateSpriteName(prefixOverride?: string): Promise { const settings = await this.getSettings(); const prefix = prefixOverride ?? settings.spritePrefix ?? "paseo-worker-"; return sanitizeSpriteName(`${prefix}${randomBytes(3).toString("hex")}`); } async ensureSprite(options: { name?: string; config?: Partial; syncLocalPath?: string; remoteDir?: string; } = {}): Promise<{ sprite: Sprite; created: boolean; syncedFiles?: number; remoteDir: string }> { const { client, settings } = await this.getClient(); const remoteDir = options.remoteDir?.trim() || settings.defaultRemoteCwd.trim() || "/workspace"; const name = options.name?.trim() ? sanitizeSpriteName(options.name.trim()) : await this.generateSpriteName(); let sprite: Sprite | null = null; let created = false; if (options.name?.trim()) { try { sprite = await client.getSprite(name); } catch { sprite = null; } } if (!sprite) { const spriteConfig = await this.buildSpriteConfig(options.config); sprite = await client.createSprite(name, spriteConfig); created = true; } let syncedFiles: number | undefined; if (options.syncLocalPath?.trim()) { const syncResult = await this.syncWorkspace( sprite.name, options.syncLocalPath.trim(), remoteDir, ); syncedFiles = syncResult.fileCount; } return { sprite, created, syncedFiles, remoteDir }; } async listRemoteSprites(): Promise { const { client } = await this.getClient(); const sprites = await client.listAllSprites(); return sprites.map(toSpriteSummary); } async syncWorkspace( spriteName: string, localPath: string, remoteDirOverride?: string, ): Promise<{ fileCount: number; bytes: number; remoteDir: string }> { const { client, settings } = await this.getClient(); const remoteDir = remoteDirOverride?.trim() || settings.defaultRemoteCwd.trim() || "/workspace"; const info = await stat(localPath).catch(() => null); if (!info?.isDirectory()) { throw new Error(`Local workspace path does not exist or is not a directory: ${localPath}`); } const sprite = client.sprite(sanitizeSpriteName(spriteName)); let isGitRepo = false; let fileListBuffer: Buffer | null = null; let fileCount = 0; try { await execFileAsync("git", ["-C", localPath, "rev-parse", "--is-inside-work-tree"]); isGitRepo = true; const { stdout } = await execFileAsync( "git", ["-C", localPath, "ls-files", "-z", "-co", "--exclude-standard"], { encoding: "buffer", maxBuffer: 32 * 1024 * 1024 }, ); fileListBuffer = stdout; fileCount = stdout.toString("utf8").split("\0").filter(Boolean).length; } catch { isGitRepo = false; } const extractCmd = sprite.spawn( "bash", ["-lc", `mkdir -p ${shellQuote(remoteDir)} && tar -xzf - -C ${shellQuote(remoteDir)}`], ); const extractStderr: Buffer[] = []; extractCmd.stderr.on("data", (chunk: Buffer) => extractStderr.push(chunk)); let sentBytes = 0; await new Promise((resolve, reject) => { const tarArgs = isGitRepo && fileListBuffer && fileCount > 0 ? ["-czf", "-", "-C", localPath, "--null", "-T", "-"] : [ "-czf", "-", "--exclude=node_modules", "--exclude=.git", "--exclude=.DS_Store", "-C", localPath, ".", ]; const tarProc = nodeSpawn("tar", tarArgs, { stdio: ["pipe", "pipe", "pipe"] }); const tarStderr: Buffer[] = []; tarProc.stderr.on("data", (chunk: Buffer) => tarStderr.push(chunk)); extractCmd.on("error", (err) => reject(err)); tarProc.on("error", (err) => reject(err)); tarProc.stdout.on("data", (chunk: Buffer) => { sentBytes += chunk.length; extractCmd.stdin.write(chunk); }); tarProc.on("close", (tarCode) => { if (tarCode !== 0) { extractCmd.kill(); reject( new Error( `Local tar failed (${tarCode}): ${Buffer.concat(tarStderr).toString("utf8").trim()}`, ), ); return; } extractCmd.stdin.end(); }); extractCmd.on("exit", (code) => { if (code !== 0) { reject( new Error( `Remote tar extract failed (${code}): ${Buffer.concat(extractStderr).toString("utf8").trim()}`, ), ); return; } resolve(); }); if (isGitRepo && fileListBuffer && fileCount > 0) { tarProc.stdin.end(fileListBuffer); } else { tarProc.stdin.end(); } }); return { fileCount, bytes: sentBytes, remoteDir }; } async execCommand(options: { spriteName: string; command: string; cwd?: string; timeoutMs?: number; }): Promise<{ stdout: string; stderr: string; exitCode: number }> { const { client, settings } = await this.getClient(); const sprite = client.sprite(sanitizeSpriteName(options.spriteName)); const cwd = options.cwd?.trim() || settings.defaultRemoteCwd.trim() || "/workspace"; try { const result = await sprite.execFile("bash", ["-lc", options.command], { cwd, timeout: options.timeoutMs ?? 120_000, }); return { stdout: String(result.stdout), stderr: String(result.stderr), exitCode: result.exitCode, }; } catch (err) { if (err instanceof ExecError) { return { stdout: String(err.stdout), stderr: String(err.stderr), exitCode: err.exitCode, }; } throw err; } } async spawnWorker(options: { spriteName?: string; command: string; cwd?: string; syncLocalPath?: string; maxRunAfterDisconnect?: string; }): Promise { const { sprite, remoteDir } = await this.ensureSprite({ name: options.spriteName, syncLocalPath: options.syncLocalPath, remoteDir: options.cwd, }); const cwd = options.cwd?.trim() || remoteDir; const workerId = `wrk_${randomBytes(4).toString("hex")}`; const worker: TrackedWorker = { workerId, spriteName: sprite.name, command: options.command, cwd, status: "starting", exitCode: null, error: null, startedAt: new Date().toISOString(), endedAt: null, output: "", outputBytes: 0, }; const cmd = sprite.spawn("bash", ["-lc", options.command], { cwd, maxRunAfterDisconnect: options.maxRunAfterDisconnect, }); worker.cmd = cmd; this.workers.set(workerId, worker); this.emitWorkersUpdate(true); const appendOutput = (chunk: Buffer | string) => { const text = typeof chunk === "string" ? chunk : chunk.toString("utf8"); worker.outputBytes += Buffer.byteLength(text, "utf8"); worker.output += text; if (worker.output.length > MAX_OUTPUT_BYTES) { worker.output = worker.output.slice(-MAX_OUTPUT_BYTES); } this.emitWorkersUpdate(false); }; cmd.on("spawn", () => { if (worker.status === "starting") { worker.status = "running"; this.emitWorkersUpdate(true); } }); cmd.stdout.on("data", appendOutput); cmd.stderr.on("data", appendOutput); cmd.on("error", (err: unknown) => { worker.status = "failed"; worker.error = err instanceof Error ? err.message : String(err); worker.endedAt = new Date().toISOString(); worker.cmd = undefined; this.emitWorkersUpdate(true); }); cmd.on("exit", (code: number) => { worker.exitCode = code; if (worker.status !== "stopped") { worker.status = code === 0 ? "completed" : "failed"; } worker.endedAt = new Date().toISOString(); worker.cmd = undefined; this.emitWorkersUpdate(true); }); return toWorkerSummary(worker); } stopWorker(workerId: string): boolean { const worker = this.workers.get(workerId); if (!worker) return false; worker.status = "stopped"; worker.endedAt = new Date().toISOString(); if (worker.cmd) { try { worker.cmd.kill("SIGTERM"); worker.cmd.close(); } catch { // Ignore already-closed command sockets. } worker.cmd = undefined; } this.emitWorkersUpdate(true); return true; } getWorker(workerId: string): { summary: WorkerSummary; output: string } | null { const worker = this.workers.get(workerId); if (!worker) return null; return { summary: toWorkerSummary(worker), output: worker.output }; } listWorkers(): WorkerSummary[] { return [...this.workers.values()] .sort((a, b) => b.startedAt.localeCompare(a.startedAt)) .map(toWorkerSummary); } async deleteSprite(spriteName: string): Promise { const normalized = sanitizeSpriteName(spriteName); for (const worker of this.workers.values()) { if (worker.spriteName === normalized && (worker.status === "starting" || worker.status === "running")) { this.stopWorker(worker.workerId); } } const { client } = await this.getClient(); await client.deleteSprite(normalized); } async listCheckpoints(spriteName: string): Promise { const { client } = await this.getClient(); const sprite = client.sprite(sanitizeSpriteName(spriteName)); const checkpoints: Checkpoint[] = await sprite.listCheckpoints(); return checkpoints.map((cp) => ({ id: cp.id, comment: cp.comment, createdAt: cp.createTime instanceof Date ? cp.createTime.toISOString() : String(cp.createTime), isAuto: cp.isAuto, })); } async createCheckpoint(spriteName: string, comment?: string): Promise { const { client } = await this.getClient(); const sprite = client.sprite(sanitizeSpriteName(spriteName)); const stream = await sprite.createCheckpoint(comment); const messages: string[] = []; for await (const msg of stream) { messages.push(formatCheckpointStreamMessage(msg)); } return messages; } async restoreCheckpoint(spriteName: string, checkpointId: string): Promise { const { client } = await this.getClient(); const sprite = client.sprite(sanitizeSpriteName(spriteName)); const stream = await sprite.restoreCheckpoint(checkpointId); const messages: string[] = []; for await (const msg of stream) { messages.push(formatCheckpointStreamMessage(msg)); } return messages; } subscribeWorkers(listener: (workers: WorkerSummary[]) => void): () => void { this.listeners.add(listener); listener(this.listWorkers()); return () => { this.listeners.delete(listener); }; } dispose(): void { if (this.notifyTimer) { clearTimeout(this.notifyTimer); this.notifyTimer = null; } for (const worker of this.workers.values()) { if (worker.cmd) { try { worker.cmd.close(); } catch { // Ignore close errors during shutdown. } worker.cmd = undefined; } } this.listeners.clear(); } private emitWorkersUpdate(immediate: boolean): void { if (this.listeners.size === 0) return; if (immediate) { if (this.notifyTimer) { clearTimeout(this.notifyTimer); this.notifyTimer = null; } const snapshot = this.listWorkers(); for (const listener of this.listeners) { listener(snapshot); } return; } if (this.notifyTimer) return; this.notifyTimer = setTimeout(() => { this.notifyTimer = null; const snapshot = this.listWorkers(); for (const listener of this.listeners) { listener(snapshot); } }, 150); } }