|
| 1 | +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; |
| 2 | +import { mkdtemp, rename, rm } from 'node:fs/promises'; |
| 3 | +import os from 'node:os'; |
| 4 | +import path from 'node:path'; |
| 5 | +import type { AgentBundle } from '../core/contracts.js'; |
| 6 | +import { checkAbort, Fault, readBounded, writePrivate } from '../core/util.js'; |
| 7 | +import { installBundle } from '../lang/bundle.js'; |
| 8 | + |
| 9 | +export const WORKER_WARM_BUNDLES = 128; |
| 10 | +export const WORKER_WARM_BUNDLE_BYTES = 16 * 1024 * 1024; |
| 11 | +const MAX_MANIFEST_BYTES = 12 * 1024 * 1024; |
| 12 | +const DIGEST = /^[a-f0-9]{64}$/; |
| 13 | +const NONCE_BYTES = 12; |
| 14 | +const TAG_BYTES = 16; |
| 15 | + |
| 16 | +export type InstalledBundle = Pick<AgentBundle, 'digest' | 'agent'> & { |
| 17 | + files: Pick<AgentBundle['files'][number], 'path' | 'sha256'>[]; |
| 18 | +}; |
| 19 | +type Entry = { manifest: InstalledBundle; bytes: number; sealed: boolean }; |
| 20 | + |
| 21 | +/** Keep parsed manifests hot. Before eviction, preserve trust in private runtime scratch. */ |
| 22 | +export class WorkerBundles { |
| 23 | + private readonly hot = new Map<string, Entry>(); |
| 24 | + private readonly installing = new Map<string, Promise<void>>(); |
| 25 | + private readonly reading = new Map<string, Promise<Entry | undefined>>(); |
| 26 | + private key?: Buffer; |
| 27 | + private directory?: Promise<string>; |
| 28 | + private serialized = Promise.resolve(); |
| 29 | + private closing?: Promise<void>; |
| 30 | + private bytes = 0; |
| 31 | + |
| 32 | + constructor( |
| 33 | + private readonly bundleRoot: string, |
| 34 | + private readonly capacity = WORKER_WARM_BUNDLES, |
| 35 | + private readonly byteBudget = WORKER_WARM_BUNDLE_BYTES, |
| 36 | + ) {} |
| 37 | + |
| 38 | + warm(): string[] { |
| 39 | + // Report membership, not recency. Merely using a digest must not churn advertisements. |
| 40 | + return [...this.hot.keys()].sort(); |
| 41 | + } |
| 42 | + |
| 43 | + cached(digest: string): InstalledBundle | undefined { |
| 44 | + if (this.closing) return undefined; |
| 45 | + const entry = this.hot.get(digest); |
| 46 | + if (!entry) return undefined; |
| 47 | + this.hot.delete(digest); |
| 48 | + this.hot.set(digest, entry); |
| 49 | + return entry.manifest; |
| 50 | + } |
| 51 | + |
| 52 | + async load(digest: string): Promise<InstalledBundle | undefined> { |
| 53 | + // An admitted dispatch can read cold data without having to evict another entry first. |
| 54 | + return (await this.read(digest))?.manifest; |
| 55 | + } |
| 56 | + |
| 57 | + async install(raw: AgentBundle, signal?: AbortSignal): Promise<void> { |
| 58 | + if (signal) checkAbort(signal); |
| 59 | + if (this.closing) throw new Fault('shutting_down', 'Worker is shutting down.', 503); |
| 60 | + const digest = raw?.digest; |
| 61 | + if (!DIGEST.test(digest ?? '')) throw new Fault('bundle_integrity', 'Invalid bundle digest.'); |
| 62 | + if (this.cached(digest)) return; |
| 63 | + let pending = this.installing.get(digest); |
| 64 | + if (!pending) { |
| 65 | + pending = this.prepare(digest, raw).finally(() => this.installing.delete(digest)); |
| 66 | + this.installing.set(digest, pending); |
| 67 | + } |
| 68 | + await pending; |
| 69 | + if (signal) checkAbort(signal); |
| 70 | + } |
| 71 | + |
| 72 | + private async prepare(digest: string, raw: AgentBundle): Promise<void> { |
| 73 | + const cold = await this.read(digest); |
| 74 | + if (cold) return this.admit(cold); |
| 75 | + const bundle = await installBundle(this.bundleRoot, raw); |
| 76 | + const manifest: InstalledBundle = { |
| 77 | + digest: bundle.digest, |
| 78 | + agent: bundle.agent, |
| 79 | + files: bundle.files.map(({ path, sha256 }) => ({ path, sha256 })), |
| 80 | + }; |
| 81 | + await this.admit({ |
| 82 | + manifest, |
| 83 | + bytes: Buffer.byteLength(JSON.stringify(manifest)), |
| 84 | + sealed: false, |
| 85 | + }); |
| 86 | + } |
| 87 | + |
| 88 | + private admit(entry: Entry): Promise<void> { |
| 89 | + const publish = this.serialized.then(async () => { |
| 90 | + if (entry.bytes > this.byteBudget) return this.spill(entry); |
| 91 | + while (this.hot.size >= this.capacity || this.bytes + entry.bytes > this.byteBudget) { |
| 92 | + const victim = this.hot.values().next().value!; |
| 93 | + // A failed spill leaves the installed copy live and the new install unacknowledged. |
| 94 | + await this.spill(victim); |
| 95 | + this.hot.delete(victim.manifest.digest); |
| 96 | + this.bytes -= victim.bytes; |
| 97 | + } |
| 98 | + this.hot.set(entry.manifest.digest, entry); |
| 99 | + this.bytes += entry.bytes; |
| 100 | + }); |
| 101 | + this.serialized = publish.catch(() => {}); |
| 102 | + return publish; |
| 103 | + } |
| 104 | + |
| 105 | + private scratch(): Promise<string> { |
| 106 | + if (!this.directory) { |
| 107 | + this.directory = mkdtemp(path.join(os.tmpdir(), 'oaa-worker-manifests-')).catch((error) => { |
| 108 | + this.directory = undefined; |
| 109 | + throw error; |
| 110 | + }); |
| 111 | + } |
| 112 | + return this.directory; |
| 113 | + } |
| 114 | + |
| 115 | + private async spill(entry: Entry): Promise<void> { |
| 116 | + if (entry.sealed) return; |
| 117 | + const dir = await this.scratch(); |
| 118 | + const digest = entry.manifest.digest; |
| 119 | + const nonce = randomBytes(NONCE_BYTES); |
| 120 | + const cipher = createCipheriv('aes-256-gcm', (this.key ??= randomBytes(32)), nonce); |
| 121 | + cipher.setAAD(Buffer.from(digest)); |
| 122 | + const ciphertext = [cipher.update(JSON.stringify(entry.manifest), 'utf8'), cipher.final()]; |
| 123 | + const stage = `${digest}.part`; |
| 124 | + try { |
| 125 | + await writePrivate( |
| 126 | + dir, |
| 127 | + stage, |
| 128 | + Buffer.concat([nonce, cipher.getAuthTag(), ...ciphertext]), |
| 129 | + true, |
| 130 | + ); |
| 131 | + await rename(path.join(dir, stage), path.join(dir, digest)); |
| 132 | + entry.sealed = true; |
| 133 | + } catch (error) { |
| 134 | + await rm(path.join(dir, stage), { force: true }).catch(() => {}); |
| 135 | + throw error; |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private async read(digest: string): Promise<Entry | undefined> { |
| 140 | + const directory = this.directory; |
| 141 | + if (this.closing || !DIGEST.test(digest) || !directory) return undefined; |
| 142 | + let pending = this.reading.get(digest); |
| 143 | + if (!pending) { |
| 144 | + pending = directory |
| 145 | + .then((dir) => this.open(dir, digest)) |
| 146 | + .finally(() => this.reading.delete(digest)); |
| 147 | + this.reading.set(digest, pending); |
| 148 | + } |
| 149 | + return pending; |
| 150 | + } |
| 151 | + |
| 152 | + private async open(dir: string, digest: string): Promise<Entry | undefined> { |
| 153 | + const key = this.key; |
| 154 | + if (!key) return undefined; |
| 155 | + try { |
| 156 | + const data = await readBounded(dir, digest, MAX_MANIFEST_BYTES + NONCE_BYTES + TAG_BYTES); |
| 157 | + const decipher = createDecipheriv('aes-256-gcm', key, data.subarray(0, NONCE_BYTES)); |
| 158 | + decipher.setAAD(Buffer.from(digest)); |
| 159 | + decipher.setAuthTag(data.subarray(NONCE_BYTES, NONCE_BYTES + TAG_BYTES)); |
| 160 | + const body = Buffer.concat([ |
| 161 | + decipher.update(data.subarray(NONCE_BYTES + TAG_BYTES)), |
| 162 | + decipher.final(), |
| 163 | + ]); |
| 164 | + return { |
| 165 | + manifest: JSON.parse(body.toString('utf8')) as InstalledBundle, |
| 166 | + bytes: body.length, |
| 167 | + sealed: true, |
| 168 | + }; |
| 169 | + } catch (error) { |
| 170 | + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; |
| 171 | + throw new Fault('bundle_integrity', 'The installed bundle manifest could not be verified.'); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + close(): Promise<void> { |
| 176 | + return (this.closing ??= this.cleanup().finally(() => (this.closing = undefined))); |
| 177 | + } |
| 178 | + |
| 179 | + private async cleanup(): Promise<void> { |
| 180 | + await Promise.allSettled([...this.installing.values(), ...this.reading.values()]); |
| 181 | + this.hot.clear(); |
| 182 | + this.bytes = 0; |
| 183 | + this.key?.fill(0); |
| 184 | + this.key = undefined; |
| 185 | + const dir = await this.directory?.catch(() => undefined); |
| 186 | + this.directory = undefined; |
| 187 | + if (dir) await rm(dir, { recursive: true, force: true }); |
| 188 | + } |
| 189 | +} |
0 commit comments