返回 CodeWhale
storage.ts
根目录 / crates / engine / extension-host / src / shims / storage.ts
1 /** Owner-local plugin state, never session history or a credential service. */
2 import { constants } from 'node:fs'
3 import { lstat, mkdir, open, readdir, rename, unlink } from 'node:fs/promises'
4 import { isAbsolute, join } from 'node:path'
5 import { createHash, randomUUID } from 'node:crypto'
6 import { setTimeout as delay } from 'node:timers/promises'
7 import { canonicalPath } from '../dsh/canonical-path.ts'
8 import { isJson } from '../json.ts'
9 import type { Json } from '../protocol.ts'
10
11 export const STORAGE_LIMITS = Object.freeze({ keyBytes: 128, valueBytes: 128 * 1024, totalBytes: 4 * 1024 * 1024, keys: 1024 })
12 const RECORD_NAME = /^[a-f0-9]{64}\.json$/u
13 const MAX_RECORD_BYTES = STORAGE_LIMITS.valueBytes + STORAGE_LIMITS.keyBytes * 6 + 128
14 const queues = new Map<string, Promise<void>>()
15
16 export interface PluginStorage {
17 get(key: string): Promise<Json | undefined>
18 set(key: string, value: Json): Promise<void>
19 delete(key: string): Promise<boolean>
20 }
21
22 export interface StorageOptions {
23 /** The exact directory Rust already assigned to this owner. */
24 dataDir: string
25 /** Must become false as soon as this owner starts disposal or is revoked. */
26 isActive: () => boolean
27 /** Optional host diagnostic when directory fsync is unavailable after publication. */
28 onWarning?: (message: string) => void
29 }
30
31 export class StorageError extends Error {
32 readonly code: 'not_available' | 'invalid' | 'limit' | 'corrupt' | 'io'
33 constructor(code: StorageError['code'], message: string) {
34 super(message)
35 this.code = code
36 this.name = 'StorageError'
37 }
38 }
39
40 function checkKey(key: string): void {
41 if (typeof key !== 'string' || !key.length || key.includes('\0') || Buffer.byteLength(key) > STORAGE_LIMITS.keyBytes) {
42 throw new StorageError('invalid', `storage key must contain 1 to ${STORAGE_LIMITS.keyBytes} UTF-8 bytes and no NUL`)
43 }
44 }
45
46 /** Reject accessors, symbols, sparse arrays and extra properties before isJson reads values. */
47 function snapshot(value: unknown): Json {
48 if (!isJson(value)) throw new StorageError('invalid', 'storage value must be plain JSON')
49 const encoded = JSON.stringify(value)
50 if (Buffer.byteLength(encoded) > STORAGE_LIMITS.valueBytes) throw new StorageError('limit', 'storage value exceeds its byte limit')
51 return JSON.parse(encoded)
52 }
53
54 function recordName(key: string): string {
55 return `${createHash('sha256').update(key).digest('hex')}.json`
56 }
57
58 function fsCode(error: unknown): string | undefined {
59 return (error as NodeJS.ErrnoException)?.code
60 }
61
62 // Windows may briefly deny access while another process replaces a record.
63 // Retry only sharing-related I/O errors; permanent denial still fails closed.
64 async function retryWindowsSharing<T>(operation: () => Promise<T>, beforeRetry?: () => unknown | Promise<unknown>): Promise<T> {
65 for (let retry = 0; ; retry++) {
66 if (retry) await beforeRetry?.()
67 try { return await operation() } catch (error) {
68 if (process.platform !== 'win32' || retry >= 10 || !['EACCES', 'EBUSY', 'EPERM'].includes(fsCode(error) ?? '')) throw error
69 await delay((retry + 1) * 50)
70 }
71 }
72 }
73
74 interface RecordSnapshot { key: string; value: Json; bytes: number }
75
76 /** Read one bounded, complete record without following a link. */
77 async function readRecordOnce(directory: string, name: string): Promise<RecordSnapshot | undefined> {
78 const path = join(directory, name)
79 let file
80 try {
81 const before = await lstat(path)
82 if (!before.isFile() || before.isSymbolicLink() || before.nlink > 1) throw new StorageError('corrupt', 'plugin storage record is not a single-link regular file')
83 file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
84 const stat = await file.stat()
85 // Another host may atomically replace this key between lstat and open,
86 // or unlink the old inode after we opened it. Both complete versions are
87 // valid snapshots; retain the no-follow/single-link checks on the version
88 // actually opened rather than calling an ordinary replacement corruption.
89 const current = await lstat(path).catch((error) => { if (fsCode(error) !== 'ENOENT') throw error; return undefined })
90 if (!stat.isFile() || stat.nlink > 1 || current?.isSymbolicLink()) throw new StorageError('corrupt', 'plugin storage record changed while opening')
91 if (stat.size > MAX_RECORD_BYTES) throw new StorageError('corrupt', 'plugin storage record exceeds its byte limit')
92 const bytes = Buffer.alloc(stat.size + 1)
93 let length = 0
94 while (length < bytes.length) {
95 const read = await file.read(bytes, length, bytes.length - length, length)
96 if (!read.bytesRead) break
97 length += read.bytesRead
98 }
99 if (length > stat.size) throw new StorageError('corrupt', 'plugin storage record changed while reading')
100 const stored = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length)))
101 if (!stored || stored.version !== 1 || Object.keys(stored).length !== 3 || !Object.hasOwn(stored, 'value')) throw new StorageError('corrupt', 'plugin storage record format is invalid')
102 checkKey(stored.key)
103 if (recordName(stored.key) !== name) throw new StorageError('corrupt', 'plugin storage record does not match its key')
104 return { key: stored.key, value: snapshot(stored.value), bytes: length }
105 } catch (error) {
106 if (fsCode(error) === 'ENOENT') return undefined
107 if (error instanceof StorageError) throw new StorageError('corrupt', error.message)
108 if (error instanceof SyntaxError || error instanceof TypeError) throw new StorageError('corrupt', 'plugin storage record is invalid; existing state was preserved')
109 throw error
110 } finally {
111 await file?.close()
112 }
113 }
114
115 /**
116 * One frozen API per owner generation; isActive is checked on every admission
117 * and again before publication. Unload never deletes state. A write admitted
118 * at that final check may finish its atomic rename during disposal.
119 *
120 * Completed records are atomic per key. Same-key writes from different host
121 * processes are last-writer-wins; different keys cannot overwrite one another.
122 * A shared in-process queue checks the observed 4 MiB / 1024-record quota before
123 * each set. This is not a strict shared disk cap: independent-process races,
124 * pending files and crash-orphaned temporary files are outside that accounting.
125 * Key/value limits remain strict. No lock survives a crash, no orphan is guessed
126 * away, and reads/deletes remain usable when the observed quota is exceeded.
127 * This API does not contain arbitrary co-resident native plugin code.
128 */
129 export function createStorage({ dataDir, isActive, onWarning }: StorageOptions): PluginStorage {
130 if (typeof dataDir !== 'string' || !isAbsolute(dataDir)) throw new StorageError('invalid', 'plugin storage needs its assigned absolute dataDir')
131
132 function active(): void {
133 if (!isActive()) throw new StorageError('not_available', 'plugin storage owner is no longer active')
134 }
135
136 async function readRecord(directory: string, name: string): Promise<RecordSnapshot | undefined> {
137 return retryWindowsSharing(() => readRecordOnce(directory, name), active)
138 }
139
140 async function directory(): Promise<string> {
141 const stat = await lstat(dataDir)
142 if (!stat.isDirectory() || stat.isSymbolicLink()) throw new StorageError('invalid', 'plugin storage dataDir must be a real directory')
143 return join(canonicalPath(dataDir), 'storage-v1')
144 }
145
146 async function prepare(directory: string): Promise<void> {
147 await mkdir(directory, { mode: 0o700 }).catch((error) => { if (fsCode(error) !== 'EEXIST') throw error })
148 const stat = await lstat(directory)
149 if (!stat.isDirectory() || stat.isSymbolicLink()) throw new StorageError('corrupt', 'plugin storage record directory must be a real directory')
150 active()
151 }
152
153 async function syncDirectory(directory: string): Promise<void> {
154 // File fsync is required before publication. Directory fsync is OS-best-
155 // effort after publication; reporting failure as a rejected set would lie
156 // about the complete record that already replaced the previous version.
157 let dir
158 try { dir = await open(directory, constants.O_RDONLY); await dir.sync() } catch (error) {
159 try { onWarning?.(`plugin storage record committed; directory fsync unavailable (${fsCode(error) ?? 'unknown filesystem error'})`) } catch { /* Diagnostics cannot undo publication. */ }
160 } finally {
161 await dir?.close().catch(() => undefined)
162 }
163 }
164
165 async function checkQuota(directory: string, name: string, candidateBytes: number): Promise<void> {
166 const names = (await readdir(directory)).filter((entry) => RECORD_NAME.test(entry))
167 let count = 0, bytes = 0
168 for (const entry of names) {
169 if (entry === name) continue
170 const record = await readRecord(directory, entry)
171 if (!record) continue // A separate process may have deleted this key.
172 count++
173 bytes += record.bytes
174 if (count + 1 > STORAGE_LIMITS.keys || bytes + candidateBytes > STORAGE_LIMITS.totalBytes) throw new StorageError('limit', 'plugin storage exceeds its observed owner quota')
175 }
176 if (count + 1 > STORAGE_LIMITS.keys || bytes + candidateBytes > STORAGE_LIMITS.totalBytes) throw new StorageError('limit', 'plugin storage exceeds its observed owner quota')
177 }
178
179 async function write(directory: string, key: string, value: Json): Promise<void> {
180 const name = recordName(key)
181 const encoded = JSON.stringify({ version: 1, key, value }) + '\n'
182 // Refuse silent replacement of a corrupt or linked record.
183 await readRecord(directory, name)
184 await checkQuota(directory, name, Buffer.byteLength(encoded))
185 const temporary = join(directory, `.pending-${randomUUID()}.tmp`)
186 let file
187 let published = false
188 try {
189 file = await open(temporary, 'wx', 0o600)
190 await file.writeFile(encoded)
191 await file.sync()
192 await file.close()
193 file = undefined
194 await retryWindowsSharing(async () => {
195 // Revalidation and publication share one bounded retry budget. A
196 // sharing error while checking the destination must not escape it.
197 active()
198 await readRecordOnce(directory, name)
199 active()
200 await rename(temporary, join(directory, name))
201 })
202 published = true
203 await syncDirectory(directory)
204 } finally {
205 await file?.close()
206 // This invocation's unpredictable file only; never remove crash orphans.
207 if (!published) await unlink(temporary).catch((error) => { if (fsCode(error) !== 'ENOENT') throw error })
208 }
209 }
210
211 async function queue<T>(operation: (directory: string) => Promise<T>): Promise<T> {
212 active()
213 try {
214 const dir = await directory()
215 const next = (queues.get(dir) ?? Promise.resolve()).then(async () => { active(); await prepare(dir); return operation(dir) })
216 const tail = next.then(() => undefined, () => undefined)
217 queues.set(dir, tail)
218 void tail.then(() => { if (queues.get(dir) === tail) queues.delete(dir) })
219 return await next
220 } catch (error) {
221 if (error instanceof StorageError) throw error
222 throw new StorageError('io', `plugin storage operation failed (${fsCode(error) ?? 'unknown filesystem error'})`)
223 }
224 }
225
226 return Object.freeze({
227 get(key: string) {
228 return queue(async (dir) => { checkKey(key); const record = await readRecord(dir, recordName(key)); active(); return record?.value })
229 },
230 set(key: string, value: Json) {
231 let copy: Json
232 try { active(); checkKey(key); copy = snapshot(value) } catch (error) { return Promise.reject(error) }
233 return queue((dir) => write(dir, key, copy))
234 },
235 delete(key: string) {
236 return queue(async (dir) => {
237 checkKey(key)
238 const path = join(dir, recordName(key))
239 const stat = await lstat(path).catch((error) => { if (fsCode(error) !== 'ENOENT') throw error; return undefined })
240 if (!stat) return false
241 if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new StorageError('corrupt', 'plugin storage record is not a single-link regular file')
242 active()
243 await unlink(path)
244 await syncDirectory(dir)
245 return true
246 })
247 },
248 })
249 }
250
250 lines TYPESCRIPT