返回 CodeWhale
index.ts
1 import { type EntryChange, type EntryOptions, EntryTree, EntryGroup, isJsExpr } from '@deepseek-ai/cordis-plugin-loader'
2 import { Context, Service } from '@deepseek-ai/cordis'
3 import { deepEqual } from '@deepseek-ai/cosmokit'
4 import { basename, dirname, extname, join } from 'node:path'
5 import { access, constants, readFile, rename, rm, writeFile } from 'node:fs/promises'
6 import { setTimeout as sleep } from 'node:timers/promises'
7 import { fileURLToPath, pathToFileURL } from 'node:url'
8 import * as yaml from 'js-yaml'
9 import { applyJournal, flatten, type Journal, merge, reconcile, record } from './journal.ts'
10 import { applyPatches, ensureIds, ensureInsertIds, PatchIndex, type PatchOptions, routeJournal } from './patch.ts'
11 /** Shared patch semantics used by config dumps and mounting. */
12 export { applyPatches as applyEntryPatches } from './patch.ts'
13 /** Serialized entry patch options. */
14 export type { PatchOptions } from './patch.ts'
15
16 const JsExpr = new yaml.Type('tag:yaml.org,2002:js', {
17 kind: 'scalar',
18 resolve: (data) => typeof data === 'string',
19 construct: (data) => ({ __jsExpr: data }),
20 predicate: isJsExpr,
21 represent: (data) => (data as { __jsExpr: string }).__jsExpr,
22 })
23
24 /** YAML dialect preserving child-owned JavaScript expression nodes. */
25 export const entryListSchema = yaml.JSON_SCHEMA.extend(JsExpr)
26 const schema = entryListSchema
27
28 const types: Record<string, string> = {
29 '.json': 'application/json',
30 '.yaml': 'application/yaml',
31 '.yml': 'application/yaml',
32 }
33
34 type ConfigStage = 'read' | 'parse' | 'validate'
35
36 interface Snapshot {
37 content: string
38 data: EntryOptions[]
39 }
40
41 export class ConfigFileError extends Error {
42 name = 'ConfigFileError'
43
44 constructor(public stage: ConfigStage, path: string, cause: unknown) {
45 super(`failed to ${stage} config file ${path}`, { cause })
46 }
47 }
48
49 /** The file changed under us between the pre-check and the rename. */
50 class StaleWriteError extends Error {
51 name = 'StaleWriteError'
52 }
53
54 interface Anonymous {
55 parent: string | null
56 options: EntryOptions
57 }
58
59 function isENOENT(error: unknown) {
60 return (error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'
61 }
62
63 const RENAME_RETRIES = 10
64 const RENAME_BACKOFF = 20
65
66 /**
67 * On Windows a rename over a file that another process holds open (typically
68 * an antivirus scanning what we just wrote) fails with one of these; the lock
69 * is normally gone within milliseconds. A bounded retry is cheap enough to
70 * apply on every platform.
71 */
72 function isTransientRenameError(error: unknown) {
73 const code = (error as NodeJS.ErrnoException | undefined)?.code
74 return code === 'EACCES' || code === 'EPERM' || code === 'EBUSY'
75 }
76
77 export namespace Include {
78 export interface Config {
79 path: string
80 initial?: any[]
81 patches?: PatchOptions[]
82 enableLogs?: boolean
83 }
84 }
85
86 export class Include extends EntryTree {
87 static inject = ['loader']
88
89 // Child entries evaluate their expressions against their own injections.
90 static readonly [EntryGroup.key] = true
91
92 public filename: string
93 private type: string
94
95 /** The last file state we read or wrote. */
96 private cache?: Snapshot
97 /** Tree-side changes that have not reached the file yet. */
98 private journal: Journal = new Map()
99 /** Ids we assigned to entries the file leaves anonymous. */
100 private anonymous = new Map<string, Anonymous>()
101
102 private dirtyRead = false
103 private dirtyWrite = false
104 private _draining?: Promise<void>
105
106 /** Only the latest intended tree is ever applied; older ones are skipped. */
107 private _pendingTree?: EntryOptions[]
108 private _applyTask?: Promise<void>
109
110 private _disposed = false
111 private _seq = 0
112 private persistenceError: unknown
113
114 constructor(ctx: Context, public config: Include.Config) {
115 super(ctx)
116 this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false
117 this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl))
118 const ext = extname(this.filename)
119 if (!types[ext]) {
120 throw new Error(`extension "${ext}" not supported`)
121 }
122 this.type = types[ext]
123 this.ctx.baseUrl = new URL('.', pathToFileURL(this.filename)).href
124 ensureInsertIds(config.patches, id => !!this.store[id])
125
126 ctx.on('internal/update', (config, next) => {
127 if (config.path !== this.config.path) return next()
128 this.config = config
129 ensureInsertIds(config.patches, id => !!this.store[id])
130 this._scheduleApply()
131 return this._applyTask
132 })
133 }
134
135 private warn = (format: string, ...args: any[]) => {
136 this.ctx.root.logger?.('loader').warn(format, ...args)
137 }
138
139 async* [Service.init]() {
140 try {
141 await this._read()
142 } catch (error) {
143 // only a missing file falls back to `initial`
144 const cause = error instanceof ConfigFileError && error.stage === 'read' ? error.cause : undefined
145 if (!isENOENT(cause)) throw error
146 if (!this.config.initial) {
147 throw new Error(`config file not found: ${this.filename}`)
148 }
149 const initial = structuredClone(this.config.initial) as EntryOptions[]
150 ensureIds(initial, id => !!this.store[id])
151 await this._writeText(this.dump(initial))
152 await this._read()
153 }
154
155 yield () => this.stop()
156 await this._applyTask
157 }
158
159 async stop() {
160 this._disposed = true
161 this._pendingTree = undefined
162 // Flush what the user last did before the tree goes away; this is also the
163 // last attempt for changes a failed write left in the journal.
164 if (this.journal.size) {
165 this.dirtyWrite = true
166 this._drain()
167 }
168 try {
169 await this.flush()
170 } finally {
171 this.root.stop()
172 }
173 }
174
175 /**
176 * Resolves once every pending read and write has been processed and the
177 * tree reflects the outcome. Retries pending writes and rejects while changes remain unsaved.
178 */
179 async flush() {
180 if (this.journal.size && !this._draining) {
181 this.dirtyWrite = true
182 this._drain()
183 }
184 while (this._draining || this._applyTask) {
185 await this._draining
186 await this._applyTask
187 }
188 if (this.journal.size) {
189 throw this.persistenceError ?? new Error(`config file ${this.filename} has ${this.journal.size} unsaved change(s)`)
190 }
191 this.persistenceError = undefined
192 }
193
194 /** Re-read the file and reconcile the tree with it. */
195 refresh() {
196 this.dirtyRead = true
197 this._drain()
198 return this.flush()
199 }
200
201 /** Called synchronously by the loader once a tree-side change is in place. */
202 commit(change: EntryChange) {
203 this.context.emit('loader/config-update')
204 const parent = change.group === this.root ? null : change.group.ctx.fiber.entry!.options.id
205 record(this.journal, change, parent)
206 this.dirtyWrite = true
207 this._drain()
208 }
209
210 private _drain() {
211 if (this._draining) return
212 this._draining = this._loop().finally(() => {
213 this._draining = undefined
214 })
215 }
216
217 private async _loop() {
218 while (this.dirtyRead || this.dirtyWrite) {
219 if (this.dirtyRead) {
220 this.dirtyRead = false
221 try {
222 await this._read()
223 } catch (error) {
224 // Half-written files are routine while the user is editing, hence
225 // only a warning. With the file in an unknown state there is nothing
226 // safe to write: unless another read is due, stop here and leave
227 // `dirtyWrite` set for the next trigger.
228 this.persistenceError = error
229 this.ctx.logger.warn(error)
230 if (this.dirtyRead) continue
231 return
232 }
233 }
234 if (this.dirtyWrite) {
235 this.dirtyWrite = false
236 try {
237 await this._write()
238 } catch (error) {
239 this.persistenceError = error
240 this.ctx.logger.error(error)
241 }
242 }
243 }
244 }
245
246 private async _read() {
247 let content: string
248 try {
249 content = await readFile(this.filename, 'utf8')
250 } catch (error) {
251 throw new ConfigFileError('read', this.filename, error)
252 }
253 if (content === this.cache?.content) return
254
255 let data: any
256 try {
257 data = this.type === 'application/yaml'
258 ? yaml.load(content, { schema })
259 : JSON.parse(content)
260 } catch (error) {
261 throw new ConfigFileError('parse', this.filename, error)
262 }
263 // An empty or truncated file (routine mid-edit) parses to `undefined`, so
264 // every non-array shape is rejected here as one "invalid file" signal.
265 if (!Array.isArray(data)) {
266 throw new ConfigFileError('validate', this.filename, new TypeError('config file must be a top-level array'))
267 }
268
269 this._assignIds(data)
270
271 if (this.cache) {
272 const index = new PatchIndex(this.config.patches ?? [])
273 const conflicts = reconcile(this.journal, flatten(this.cache.data), flatten(data), (id, key) => index.fileOwned(id, key))
274 for (const { id, reason } of conflicts) {
275 this.ctx.logger.error('config conflict in %C: entry %C %s; file wins', this.filename, id, reason)
276 }
277 }
278
279 this.cache = { content, data }
280 this._scheduleApply()
281 // the file changed while tree-side changes were pending: write the merge
282 if (this.journal.size) this.dirtyWrite = true
283 }
284
285 private async _write() {
286 if (!this.cache || !this.journal.size) return
287 const current = await readFile(this.filename, 'utf8').catch((error) => {
288 if (isENOENT(error)) return undefined
289 throw error
290 })
291 if (current === undefined) {
292 this.ctx.logger.warn('config file %C is missing, %d pending change(s) kept in memory', this.filename, this.journal.size)
293 return
294 }
295 if (current !== this.cache.content) {
296 // someone else wrote the file: merge first, then come back
297 this.dirtyRead = true
298 this.dirtyWrite = true
299 return
300 }
301
302 // Snapshot and swap: changes reported while we are writing belong to the
303 // next round.
304 const batch = this.journal
305 this.journal = new Map()
306 const restore = () => {
307 for (const [id, record] of this.journal) merge(batch, id, record)
308 this.journal = batch
309 }
310
311 const data = structuredClone(this.cache.data)
312 const patches = structuredClone(this.config.patches ?? [])
313 if (routeJournal(batch, data, patches, this.warn)) {
314 // Take the new patches now so that the tree scheduled below already
315 // reflects them; the round trip through the parent only persists them.
316 this.config = { ...this.config, patches }
317 if (this.ctx.fiber.entry) {
318 // Not awaited: the returned promise is the tree reconciliation, and
319 // the drain loop must not block on fibers.
320 try {
321 Promise.resolve(this.ctx.fiber.update(this.config)).catch((error) => {
322 this.ctx.logger.error(error)
323 })
324 } catch (error) {
325 this.ctx.logger.error(error)
326 }
327 } else {
328 this.ctx.logger.warn('patches of %C changed at runtime but cannot be persisted', this.filename)
329 }
330 }
331
332 // nothing for the file itself (patch-only changes, or ids we assigned to
333 // anonymous entries that are already part of the cache)
334 if (deepEqual(data, this.cache.data)) {
335 this._scheduleApply()
336 return
337 }
338 const text = this.dump(data)
339
340 try {
341 await access(this.filename, constants.W_OK)
342 } catch {
343 restore()
344 this.ctx.logger.warn('config file %C is read-only, %d pending change(s) kept in memory', this.filename, this.journal.size)
345 return
346 }
347
348 try {
349 await this._writeText(text, this.cache.content)
350 } catch (error) {
351 restore()
352 if (error instanceof StaleWriteError) {
353 this.dirtyRead = true
354 this.dirtyWrite = true
355 return
356 }
357 this.ctx.logger.warn('failed to write config file %C, %d pending change(s) kept in memory', this.filename, this.journal.size)
358 throw error
359 }
360 this.cache = { content: text, data }
361 this._scheduleApply()
362 }
363
364 /**
365 * Write through a temp file and a rename, so that no reader ever sees a
366 * truncated file. When `expected` is given, the rename (and every retry of
367 * it) only goes ahead while the file still holds that content.
368 */
369 private async _writeText(text: string, expected?: string) {
370 const tmp = join(dirname(this.filename), `.${basename(this.filename)}.${process.pid}.${this._seq++}.tmp`)
371 try {
372 await writeFile(tmp, text)
373 for (let attempt = 0; ; attempt++) {
374 if (expected !== undefined) {
375 const current = await readFile(this.filename, 'utf8').catch((error) => {
376 if (isENOENT(error)) return undefined
377 throw error
378 })
379 if (current !== expected) throw new StaleWriteError()
380 }
381 try {
382 await rename(tmp, this.filename)
383 return
384 } catch (error) {
385 if (attempt >= RENAME_RETRIES || !isTransientRenameError(error)) throw error
386 }
387 await sleep(RENAME_BACKOFF * (attempt + 1))
388 }
389 } catch (error) {
390 await rm(tmp, { force: true }).catch(() => {})
391 throw error
392 }
393 }
394
395 private dump(data: EntryOptions[]) {
396 return this.type === 'application/yaml'
397 ? yaml.dump(data, { schema })
398 : JSON.stringify(data, null, 2)
399 }
400
401 /**
402 * Entries the file leaves anonymous get an id here, before the loader sees
403 * them. One that looks exactly like an entry we named on the previous read
404 * keeps that id, so editing a neighbor does not restart it; anything else
405 * gets a fresh id. Assigned ids stay in memory until the next write.
406 */
407 private _assignIds(data: EntryOptions[]) {
408 const used = new Set<string>()
409 const pending: { options: EntryOptions; parent: string | null }[] = []
410 const walk = (entries: EntryOptions[], parent: string | null) => {
411 for (const options of entries) {
412 if (options.id) {
413 used.add(options.id)
414 } else {
415 pending.push({ options, parent })
416 }
417 if (options.group && Array.isArray(options.config)) {
418 walk(options.config, options.id ?? null)
419 }
420 }
421 }
422 walk(data, null)
423
424 const previous = this.anonymous
425 this.anonymous = new Map()
426 for (const { options, parent } of pending) {
427 let id: string | undefined
428 for (const [candidate, info] of previous) {
429 if (info.parent !== parent || !deepEqual(info.options, options)) continue
430 id = candidate
431 previous.delete(candidate)
432 break
433 }
434 if (!id) {
435 do {
436 id = Math.random().toString(16).slice(2, 10)
437 } while (used.has(id) || this.store[id])
438 }
439 used.add(id)
440 this.anonymous.set(id, { parent, options: structuredClone(options) })
441 const rest = { ...options }
442 for (const key of Object.keys(options)) delete (options as unknown as Record<string, unknown>)[key]
443 Object.assign(options, { id }, rest)
444 }
445 }
446
447 private _scheduleApply() {
448 if (this._disposed || !this.cache) return
449 const tree = applyPatches(this.cache.data, this.config.patches, this.warn)
450 this._pendingTree = applyJournal(tree, this.journal, undefined, this.warn)
451 this._applyTask ??= (async () => {
452 try {
453 while (this._pendingTree) {
454 const tree = this._pendingTree
455 this._pendingTree = undefined
456 await this.root.update(tree)
457 }
458 } finally {
459 this._applyTask = undefined
460 }
461 })()
462 }
463 }
464
465 export default Include
466
466 lines TYPESCRIPT