@adea-ai/plugins 4.0.0 → 4.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-plugins-catalog.d.ts +2 -4
- package/dist/agent-plugins-catalog.js +42 -50
- package/dist/agent-plugins-catalog.js.map +1 -1
- package/dist/agent-plugins-schema.d.ts +8 -0
- package/dist/agent-plugins-schema.js +10 -1
- package/dist/agent-plugins-schema.js.map +1 -1
- package/dist/artifacts.d.ts +57 -0
- package/dist/artifacts.js +159 -0
- package/dist/artifacts.js.map +1 -0
- package/dist/build.d.ts +20 -0
- package/dist/build.js +103 -0
- package/dist/build.js.map +1 -0
- package/dist/capabilities.d.ts +7 -0
- package/dist/capabilities.js +116 -0
- package/dist/capabilities.js.map +1 -0
- package/dist/catalog-store.d.ts +76 -0
- package/dist/catalog-store.js +463 -0
- package/dist/catalog-store.js.map +1 -0
- package/dist/concurrency.d.ts +1 -0
- package/dist/concurrency.js +15 -0
- package/dist/concurrency.js.map +1 -0
- package/dist/consumer-index.d.ts +7 -29
- package/dist/consumer-index.js +24 -15
- package/dist/consumer-index.js.map +1 -1
- package/dist/digest.d.ts +13 -0
- package/dist/digest.js +47 -0
- package/dist/digest.js.map +1 -0
- package/dist/fs-atomic.d.ts +7 -0
- package/dist/fs-atomic.js +30 -0
- package/dist/fs-atomic.js.map +1 -0
- package/dist/harness.js +2 -1
- package/dist/harness.js.map +1 -1
- package/dist/icon-mirror.d.ts +5 -4
- package/dist/icon-mirror.js +73 -72
- package/dist/icon-mirror.js.map +1 -1
- package/dist/icons.d.ts +2 -2
- package/dist/icons.js +4 -12
- package/dist/icons.js.map +1 -1
- package/dist/index.d.ts +16 -309
- package/dist/index.js +12 -1900
- package/dist/index.js.map +1 -1
- package/dist/integrity-manifest.d.ts +43 -13
- package/dist/integrity-manifest.js +28 -17
- package/dist/integrity-manifest.js.map +1 -1
- package/dist/json-values.d.ts +3 -0
- package/dist/json-values.js +10 -0
- package/dist/json-values.js.map +1 -0
- package/dist/plugin-release.d.ts +38 -0
- package/dist/plugin-release.js +321 -0
- package/dist/plugin-release.js.map +1 -0
- package/dist/plugin-skips.d.ts +19 -0
- package/dist/plugin-skips.js +65 -0
- package/dist/plugin-skips.js.map +1 -0
- package/dist/policy.d.ts +13 -0
- package/dist/policy.js +26 -0
- package/dist/policy.js.map +1 -0
- package/dist/portable-catalog.d.ts +4 -4
- package/dist/portable-catalog.js +14 -126
- package/dist/portable-catalog.js.map +1 -1
- package/dist/portable-verify.d.ts +2 -0
- package/dist/portable-verify.js +68 -0
- package/dist/portable-verify.js.map +1 -0
- package/dist/publication.d.ts +12 -12
- package/dist/publication.js +31 -21
- package/dist/publication.js.map +1 -1
- package/dist/published-output.d.ts +17 -0
- package/dist/published-output.js +49 -0
- package/dist/published-output.js.map +1 -0
- package/dist/site-icons.d.ts +4 -3
- package/dist/site-icons.js +38 -11
- package/dist/site-icons.js.map +1 -1
- package/dist/snapshots.d.ts +39 -0
- package/dist/snapshots.js +238 -0
- package/dist/snapshots.js.map +1 -0
- package/dist/source-resolution.d.ts +28 -0
- package/dist/source-resolution.js +158 -0
- package/dist/source-resolution.js.map +1 -0
- package/dist/sources.d.ts +5 -1
- package/dist/sources.js +21 -27
- package/dist/sources.js.map +1 -1
- package/dist/synchronize.d.ts +44 -0
- package/dist/synchronize.js +118 -0
- package/dist/synchronize.js.map +1 -0
- package/dist/taxonomy.d.ts +23 -0
- package/dist/taxonomy.js +62 -0
- package/dist/taxonomy.js.map +1 -0
- package/dist/upstream.d.ts +42 -0
- package/dist/upstream.js +179 -0
- package/dist/upstream.js.map +1 -0
- package/dist/verify-artifacts.d.ts +36 -0
- package/dist/verify-artifacts.js +286 -0
- package/dist/verify-artifacts.js.map +1 -0
- package/native/build-provenance.txt +5 -5
- package/native/staged-reader-win32-arm64.node +0 -0
- package/native/staged-reader-win32-x64.node +0 -0
- package/package.json +3 -3
- package/src/agent-plugins-catalog.test.ts +2 -2
- package/src/agent-plugins-catalog.ts +46 -49
- package/src/agent-plugins-schema.ts +11 -1
- package/src/artifacts.test.ts +80 -0
- package/src/artifacts.ts +234 -0
- package/src/build.ts +131 -0
- package/src/capabilities.ts +153 -0
- package/src/catalog-store.ts +519 -0
- package/src/concurrency.ts +19 -0
- package/src/consumer-index.test.ts +147 -16
- package/src/consumer-index.ts +35 -43
- package/src/default-head.test.ts +143 -0
- package/src/digest.ts +55 -0
- package/src/fs-atomic.ts +32 -0
- package/src/harness.test.ts +4 -32
- package/src/harness.ts +2 -1
- package/src/icon-mirror.ts +78 -72
- package/src/icons.test.ts +0 -4
- package/src/icons.ts +4 -4
- package/src/index.test.ts +172 -46
- package/src/index.ts +58 -2562
- package/src/integrity-manifest.ts +41 -21
- package/src/json-values.ts +11 -0
- package/src/manifest-retry.test.ts +49 -0
- package/src/plugin-release.ts +457 -0
- package/src/plugin-skips.ts +110 -0
- package/src/policy.ts +39 -0
- package/src/portable-catalog.test.ts +0 -5
- package/src/portable-catalog.ts +16 -143
- package/src/portable-verify.ts +71 -0
- package/src/publication.test.ts +29 -1
- package/src/publication.ts +38 -22
- package/src/published-output.ts +60 -0
- package/src/site-icons.test.ts +73 -1
- package/src/site-icons.ts +31 -14
- package/src/snapshots.ts +287 -0
- package/src/source-config-sync.test.ts +84 -0
- package/src/source-digest.test.ts +61 -8
- package/src/source-resolution.ts +233 -0
- package/src/sources-json.test.ts +18 -2
- package/src/sources.ts +27 -33
- package/src/synchronize.ts +213 -0
- package/src/taxonomy.ts +87 -0
- package/src/upstream.ts +194 -0
- package/src/verify-artifacts.ts +365 -0
- package/src/write-artifacts.test.ts +374 -0
- package/dist/source-digest.d.ts +0 -2
- package/dist/source-digest.js +0 -12
- package/dist/source-digest.js.map +0 -1
- package/native/README.md +0 -24
- package/src/source-digest.ts +0 -14
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catalog output coordination and publication.
|
|
3
|
+
*
|
|
4
|
+
* Contract (see docs/architecture.md, "Catalog publication"):
|
|
5
|
+
*
|
|
6
|
+
* - Every writer and every coordinated reader of one output directory uses a
|
|
7
|
+
* lock directory that sits beside the output, in the output's real parent.
|
|
8
|
+
* The lock is keyed by the output, never by `TMPDIR`, so processes with
|
|
9
|
+
* different temporary directories, users or working directories still meet.
|
|
10
|
+
* - Supported filesystems are local filesystems where `mkdir` and same-directory
|
|
11
|
+
* `rename` are atomic: Linux (ext4, xfs, btrfs, tmpfs, overlayfs), macOS
|
|
12
|
+
* (APFS, HFS+) and Windows (NTFS, ReFS). Network filesystems are not
|
|
13
|
+
* supported: their lock leases depend on clocks and caches this module does
|
|
14
|
+
* not control.
|
|
15
|
+
* - A sync reads a base snapshot under the lock, builds without it, and then
|
|
16
|
+
* publishes only if the output still has the same fingerprint (compare and
|
|
17
|
+
* swap). A writer that replaced the catalog in between makes the later
|
|
18
|
+
* publication fail with `CATALOG_BASE_CHANGED` instead of being overwritten.
|
|
19
|
+
* - Publication stages a complete directory, records a journal, moves the
|
|
20
|
+
* current output to `<output>.previous`, then renames the staged directory
|
|
21
|
+
* into place. Coordinated readers never observe the window between the two
|
|
22
|
+
* renames. A process killed at any point leaves a journal that the next lock
|
|
23
|
+
* holder (writer or reader) rolls back or forward before doing anything else.
|
|
24
|
+
* - A lock whose holder process is gone (same host) or whose heartbeat is older
|
|
25
|
+
* than the lease is broken automatically and safely: the stale directory is
|
|
26
|
+
* renamed aside first, so only one contender can break it, and a holder that
|
|
27
|
+
* lost its lock refuses to swap with `CATALOG_LOCK_LOST`.
|
|
28
|
+
*/
|
|
29
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
30
|
+
import { promises as fs } from 'node:fs'
|
|
31
|
+
import { hostname } from 'node:os'
|
|
32
|
+
import { basename, dirname, join, sep } from 'node:path'
|
|
33
|
+
import { setTimeout as sleep } from 'node:timers/promises'
|
|
34
|
+
import { writeDurably } from './fs-atomic.js'
|
|
35
|
+
|
|
36
|
+
export type PublicationStep = 'acquiring' | 'staged' | 'backed-up' | 'swapped' | 'cleaned'
|
|
37
|
+
|
|
38
|
+
export interface CatalogCoordinationOptions {
|
|
39
|
+
/** How long to wait for another holder before failing; default 30 s. */
|
|
40
|
+
readonly waitMs?: number
|
|
41
|
+
/** Heartbeat age after which a holder is considered dead; default 120 s. */
|
|
42
|
+
readonly staleAfterMs?: number
|
|
43
|
+
/** Interval at which a holder refreshes its heartbeat; default 5 s. */
|
|
44
|
+
readonly heartbeatMs?: number
|
|
45
|
+
/** Interval between lock attempts while waiting; default 50 ms. */
|
|
46
|
+
readonly pollMs?: number
|
|
47
|
+
/** Test seam: called after each publication step while the lock is held. */
|
|
48
|
+
readonly onStep?: (step: PublicationStep) => void | Promise<void>
|
|
49
|
+
/** Test seam: called once a lock is held. */
|
|
50
|
+
readonly onLocked?: (mode: LockMode) => void | Promise<void>
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface PublishOptions extends CatalogCoordinationOptions {
|
|
54
|
+
/**
|
|
55
|
+
* Fingerprint of the output the caller built from, as returned by
|
|
56
|
+
* {@link catalogFingerprint} inside {@link withCatalogRead}. When set, the
|
|
57
|
+
* publication fails with `CATALOG_BASE_CHANGED` if the output differs.
|
|
58
|
+
*/
|
|
59
|
+
readonly expectedBase?: string
|
|
60
|
+
/** Runs after the swap while the lock is still held, e.g. to publish an index. */
|
|
61
|
+
readonly afterPublish?: () => Promise<void>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type LockMode = 'read' | 'write'
|
|
65
|
+
|
|
66
|
+
const LOCK_PREFIX = '.catalog-'
|
|
67
|
+
const ABSENT = 'absent'
|
|
68
|
+
const READ_ONLY_CODES = new Set(['EACCES', 'EPERM', 'EROFS'])
|
|
69
|
+
|
|
70
|
+
export interface CatalogPaths {
|
|
71
|
+
readonly output: string
|
|
72
|
+
readonly parent: string
|
|
73
|
+
readonly backup: string
|
|
74
|
+
readonly lock: string
|
|
75
|
+
readonly owner: string
|
|
76
|
+
readonly journal: string
|
|
77
|
+
readonly stagePrefix: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Names the coordination files of one output, beside it in its real parent. */
|
|
81
|
+
export function catalogPathsIn(parent: string, name: string): CatalogPaths {
|
|
82
|
+
const normalized = name.normalize('NFC').toLowerCase()
|
|
83
|
+
// Case-insensitive and Unicode-normalized so that `Generated` and
|
|
84
|
+
// `generated` on macOS or Windows share one lock. On a case-sensitive
|
|
85
|
+
// filesystem such outputs are merely serialized together, which is harmless.
|
|
86
|
+
const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 16)
|
|
87
|
+
const label = normalized.replace(/[^a-z0-9_-]/g, '_').slice(0, 32)
|
|
88
|
+
const stem = `${LOCK_PREFIX}${label}-${hash}`
|
|
89
|
+
const output = join(parent, name)
|
|
90
|
+
const lock = `${stem}.lock`
|
|
91
|
+
return {
|
|
92
|
+
output,
|
|
93
|
+
parent,
|
|
94
|
+
backup: `${output}.previous`,
|
|
95
|
+
lock: join(parent, lock),
|
|
96
|
+
owner: join(parent, lock, 'owner.json'),
|
|
97
|
+
journal: join(parent, `${stem}.journal.json`),
|
|
98
|
+
stagePrefix: join(parent, `${stem}.stage-`),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isReservedName(name: string): boolean {
|
|
103
|
+
return name.startsWith(LOCK_PREFIX)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function reserved(component: string): boolean {
|
|
107
|
+
return isReservedName(component) || component.endsWith('.previous')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Resolves the output's real parent, optionally creating it. */
|
|
111
|
+
async function resolvePaths(output: string, create: boolean): Promise<CatalogPaths | undefined> {
|
|
112
|
+
// Not `resolve()`: it would collapse `link/..` lexically, while the
|
|
113
|
+
// filesystem resolves the symbolic link first. `realpath` below does that.
|
|
114
|
+
const name = basename(output)
|
|
115
|
+
const parent = dirname(output)
|
|
116
|
+
// Reading a backup or a coordination directory, for example while
|
|
117
|
+
// inspecting one by hand, is allowed but not coordinated; writing is not.
|
|
118
|
+
if (create && (name === '' || name === '.' || name === '..'))
|
|
119
|
+
throw new Error(`CATALOG_OUTPUT_INVALID: ${output}`)
|
|
120
|
+
if (reserved(name) || parent.split(/[\\/]/).some(reserved)) {
|
|
121
|
+
if (!create) return undefined
|
|
122
|
+
throw new Error(`CATALOG_WRITE_LOCK_RESERVED: ${output}`)
|
|
123
|
+
}
|
|
124
|
+
if (create) await fs.mkdir(parent, { recursive: true })
|
|
125
|
+
let actualParent: string
|
|
126
|
+
try {
|
|
127
|
+
actualParent = await fs.realpath(parent)
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (!create && (error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
|
|
130
|
+
throw error
|
|
131
|
+
}
|
|
132
|
+
// An output reached through a coordination directory, for example a
|
|
133
|
+
// symbolic link into another output's lock, would be destroyed when that
|
|
134
|
+
// lock is released or broken.
|
|
135
|
+
if (actualParent.split(sep).some(reserved)) {
|
|
136
|
+
if (!create) return undefined
|
|
137
|
+
throw new Error(`CATALOG_WRITE_LOCK_RESERVED: ${output}`)
|
|
138
|
+
}
|
|
139
|
+
return catalogPathsIn(actualParent, name)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface Holder {
|
|
143
|
+
readonly token?: string
|
|
144
|
+
readonly pid?: number
|
|
145
|
+
readonly host?: string
|
|
146
|
+
readonly heartbeatAt: number
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function inspectHolder(lock: string): Promise<Holder | undefined> {
|
|
150
|
+
const owner = join(lock, 'owner.json')
|
|
151
|
+
try {
|
|
152
|
+
const [text, stat] = await Promise.all([fs.readFile(owner, 'utf8'), fs.stat(owner)])
|
|
153
|
+
const parsed = JSON.parse(text) as { token?: unknown; pid?: unknown; host?: unknown }
|
|
154
|
+
return {
|
|
155
|
+
...(typeof parsed.token === 'string' ? { token: parsed.token } : {}),
|
|
156
|
+
...(typeof parsed.pid === 'number' ? { pid: parsed.pid } : {}),
|
|
157
|
+
...(typeof parsed.host === 'string' ? { host: parsed.host } : {}),
|
|
158
|
+
heartbeatAt: stat.mtimeMs,
|
|
159
|
+
}
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
162
|
+
if (code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error
|
|
163
|
+
}
|
|
164
|
+
// The holder created the directory but has not written its owner record yet
|
|
165
|
+
// (or was killed in between): the directory's own age is the heartbeat.
|
|
166
|
+
try {
|
|
167
|
+
return { heartbeatAt: (await fs.stat(lock)).mtimeMs }
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
|
|
170
|
+
throw error
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function processIsAlive(pid: number): boolean {
|
|
175
|
+
try {
|
|
176
|
+
process.kill(pid, 0)
|
|
177
|
+
return true
|
|
178
|
+
} catch (error) {
|
|
179
|
+
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function holderIsStale(holder: Holder, staleAfterMs: number): boolean {
|
|
184
|
+
if (holder.pid !== undefined && holder.host === hostname() && !processIsAlive(holder.pid))
|
|
185
|
+
return true
|
|
186
|
+
return Date.now() - holder.heartbeatAt > staleAfterMs
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Breaks a stale lock. Renaming first means two contenders cannot both remove
|
|
191
|
+
* it; re-inspecting the renamed directory catches the case where the stale
|
|
192
|
+
* lock was replaced by a live one between inspection and rename.
|
|
193
|
+
*/
|
|
194
|
+
async function breakLock(paths: CatalogPaths, staleAfterMs: number): Promise<void> {
|
|
195
|
+
const grave = `${paths.lock}.stale-${randomUUID()}`
|
|
196
|
+
try {
|
|
197
|
+
await fs.rename(paths.lock, grave)
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
|
|
200
|
+
throw error
|
|
201
|
+
}
|
|
202
|
+
const taken = await inspectHolder(grave)
|
|
203
|
+
if (taken && !holderIsStale(taken, staleAfterMs)) {
|
|
204
|
+
// A live holder: give the lock back. If someone already took the name,
|
|
205
|
+
// the live holder will see CATALOG_LOCK_LOST before it swaps anything.
|
|
206
|
+
await fs.rename(grave, paths.lock).catch(() => undefined)
|
|
207
|
+
return
|
|
208
|
+
}
|
|
209
|
+
await fs.rm(grave, { recursive: true, force: true })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export class CatalogLock {
|
|
213
|
+
#timer: ReturnType<typeof setInterval> | undefined
|
|
214
|
+
#released = false
|
|
215
|
+
|
|
216
|
+
constructor(
|
|
217
|
+
readonly paths: CatalogPaths,
|
|
218
|
+
readonly token: string,
|
|
219
|
+
heartbeatMs: number
|
|
220
|
+
) {
|
|
221
|
+
this.#timer = setInterval(() => {
|
|
222
|
+
const now = new Date()
|
|
223
|
+
fs.utimes(paths.owner, now, now).catch(() => undefined)
|
|
224
|
+
}, heartbeatMs)
|
|
225
|
+
this.#timer.unref?.()
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Fails with `CATALOG_LOCK_LOST` if another process broke this lock. */
|
|
229
|
+
async assertHeld(): Promise<void> {
|
|
230
|
+
const holder = await inspectHolder(this.paths.lock)
|
|
231
|
+
if (holder?.token !== this.token) throw new Error(`CATALOG_LOCK_LOST: ${this.paths.output}`)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async release(): Promise<void> {
|
|
235
|
+
if (this.#released) return
|
|
236
|
+
this.#released = true
|
|
237
|
+
clearInterval(this.#timer)
|
|
238
|
+
const holder = await inspectHolder(this.paths.lock)
|
|
239
|
+
if (holder?.token !== this.token) return
|
|
240
|
+
await fs.rm(this.paths.lock, { recursive: true, force: true })
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function acquire(
|
|
245
|
+
paths: CatalogPaths,
|
|
246
|
+
mode: LockMode,
|
|
247
|
+
options: CatalogCoordinationOptions
|
|
248
|
+
): Promise<CatalogLock | undefined> {
|
|
249
|
+
const waitMs = options.waitMs ?? 30_000
|
|
250
|
+
const staleAfterMs = options.staleAfterMs ?? 120_000
|
|
251
|
+
const pollMs = options.pollMs ?? 50
|
|
252
|
+
const deadline = Date.now() + waitMs
|
|
253
|
+
for (;;) {
|
|
254
|
+
try {
|
|
255
|
+
await fs.mkdir(paths.lock)
|
|
256
|
+
} catch (error) {
|
|
257
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
258
|
+
// A read-only output cannot be published by anyone using this mount, so
|
|
259
|
+
// a reader proceeds without coordination there.
|
|
260
|
+
if (mode === 'read' && code !== undefined && READ_ONLY_CODES.has(code)) return undefined
|
|
261
|
+
if (code !== 'EEXIST') throw error
|
|
262
|
+
const holder = await inspectHolder(paths.lock)
|
|
263
|
+
if (holder === undefined) continue
|
|
264
|
+
if (holderIsStale(holder, staleAfterMs)) {
|
|
265
|
+
await breakLock(paths, staleAfterMs)
|
|
266
|
+
continue
|
|
267
|
+
}
|
|
268
|
+
if (Date.now() >= deadline) {
|
|
269
|
+
const who = holder.pid === undefined ? '' : ` (held by pid ${holder.pid} on ${holder.host})`
|
|
270
|
+
throw new Error(`CATALOG_WRITE_IN_PROGRESS: ${paths.output}${who}`, { cause: error })
|
|
271
|
+
}
|
|
272
|
+
await sleep(pollMs)
|
|
273
|
+
continue
|
|
274
|
+
}
|
|
275
|
+
const token = randomUUID()
|
|
276
|
+
try {
|
|
277
|
+
await fs.writeFile(
|
|
278
|
+
paths.owner,
|
|
279
|
+
`${JSON.stringify({ token, pid: process.pid, host: hostname(), mode, acquiredAt: new Date().toISOString() })}\n`,
|
|
280
|
+
{ flag: 'wx' }
|
|
281
|
+
)
|
|
282
|
+
} catch (error) {
|
|
283
|
+
// A contender that misjudged a live lock as stale restored it over the
|
|
284
|
+
// directory just created here (see breakLock): the lock is not ours.
|
|
285
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST') continue
|
|
286
|
+
throw error
|
|
287
|
+
}
|
|
288
|
+
const lock = new CatalogLock(paths, token, options.heartbeatMs ?? 5_000)
|
|
289
|
+
try {
|
|
290
|
+
await options.onLocked?.(mode)
|
|
291
|
+
} catch (error) {
|
|
292
|
+
await lock.release()
|
|
293
|
+
throw error
|
|
294
|
+
}
|
|
295
|
+
return lock
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async function exists(path: string): Promise<boolean> {
|
|
300
|
+
try {
|
|
301
|
+
await fs.lstat(path)
|
|
302
|
+
return true
|
|
303
|
+
} catch (error) {
|
|
304
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
|
|
305
|
+
throw error
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
interface Journal {
|
|
310
|
+
readonly version: 1
|
|
311
|
+
readonly stage: string
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function readJournal(paths: CatalogPaths): Promise<Journal | undefined> {
|
|
315
|
+
let text: string
|
|
316
|
+
try {
|
|
317
|
+
text = await fs.readFile(paths.journal, 'utf8')
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
|
|
320
|
+
throw error
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
const parsed = JSON.parse(text) as Partial<Journal>
|
|
324
|
+
if (
|
|
325
|
+
parsed.version === 1 &&
|
|
326
|
+
typeof parsed.stage === 'string' &&
|
|
327
|
+
join(paths.parent, parsed.stage).startsWith(paths.stagePrefix) &&
|
|
328
|
+
!parsed.stage.includes(sep) &&
|
|
329
|
+
!parsed.stage.includes('/')
|
|
330
|
+
)
|
|
331
|
+
return parsed as Journal
|
|
332
|
+
} catch {
|
|
333
|
+
// An empty or torn journal: the writer died while writing it, before it
|
|
334
|
+
// moved anything, so the output and backup have not been touched.
|
|
335
|
+
return { version: 1, stage: '' }
|
|
336
|
+
}
|
|
337
|
+
throw new Error(`CATALOG_RECOVERY_REQUIRED: unrecognized journal ${paths.journal}`)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Best effort: directory fsync is unavailable on Windows and some filesystems. */
|
|
341
|
+
async function syncDirectory(path: string): Promise<void> {
|
|
342
|
+
let handle
|
|
343
|
+
try {
|
|
344
|
+
handle = await fs.open(path, 'r')
|
|
345
|
+
await handle.sync()
|
|
346
|
+
} catch {
|
|
347
|
+
// Process-crash safety does not depend on it; power-loss durability does.
|
|
348
|
+
} finally {
|
|
349
|
+
await handle?.close().catch(() => undefined)
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function removeOrphanStages(paths: CatalogPaths, keep?: string): Promise<void> {
|
|
354
|
+
const prefix = basename(paths.stagePrefix)
|
|
355
|
+
for (const name of await fs.readdir(paths.parent))
|
|
356
|
+
if (name.startsWith(prefix) && name !== keep)
|
|
357
|
+
await fs.rm(join(paths.parent, name), { recursive: true, force: true })
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Completes or undoes an interrupted publication. Must run under the lock.
|
|
362
|
+
*
|
|
363
|
+
* | output | backup | staged dir | meaning | action |
|
|
364
|
+
* | ------ | ------ | ---------- | -------------------------------- | -------------- |
|
|
365
|
+
* | yes | no | any | not swapped, or already cleaned | drop staging |
|
|
366
|
+
* | no | yes | any | died between the two renames | roll back |
|
|
367
|
+
* | yes | yes | no | swapped, backup not yet removed | roll forward |
|
|
368
|
+
* | no | no | any | first publication never swapped | drop staging |
|
|
369
|
+
* | yes | yes | yes | inconsistent | stop, preserve |
|
|
370
|
+
*/
|
|
371
|
+
export async function recoverCatalogOutput(paths: CatalogPaths): Promise<void> {
|
|
372
|
+
const journal = await readJournal(paths)
|
|
373
|
+
if (journal === undefined) {
|
|
374
|
+
// Staging directories without a journal belong to a writer that died
|
|
375
|
+
// before it recorded anything; nothing else references them.
|
|
376
|
+
await removeOrphanStages(paths)
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
const stage = journal.stage === '' ? undefined : join(paths.parent, journal.stage)
|
|
380
|
+
const [hasOutput, hasBackup, hasStage] = await Promise.all([
|
|
381
|
+
exists(paths.output),
|
|
382
|
+
exists(paths.backup),
|
|
383
|
+
stage ? exists(stage) : Promise.resolve(false),
|
|
384
|
+
])
|
|
385
|
+
if (stage === undefined && hasBackup)
|
|
386
|
+
// A torn journal is written before anything moves, so a backup next to it
|
|
387
|
+
// was not made by that writer.
|
|
388
|
+
throw new Error(`CATALOG_RECOVERY_REQUIRED: preserve and inspect ${paths.backup}`)
|
|
389
|
+
if (!hasOutput && hasBackup) await fs.rename(paths.backup, paths.output)
|
|
390
|
+
else if (hasOutput && hasBackup && !hasStage)
|
|
391
|
+
await fs.rm(paths.backup, { recursive: true, force: true })
|
|
392
|
+
else if (hasOutput && hasBackup)
|
|
393
|
+
throw new Error(`CATALOG_RECOVERY_REQUIRED: preserve and inspect ${paths.backup}`)
|
|
394
|
+
await removeOrphanStages(paths)
|
|
395
|
+
await syncDirectory(paths.parent)
|
|
396
|
+
await fs.rm(paths.journal, { force: true })
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* A digest of the output's entries and bytes, or `absent`. Run it under the
|
|
401
|
+
* lock (inside {@link withCatalogRead}) so it describes a published state.
|
|
402
|
+
*/
|
|
403
|
+
export async function catalogFingerprint(output: string): Promise<string> {
|
|
404
|
+
let names: string[]
|
|
405
|
+
try {
|
|
406
|
+
names = (await fs.readdir(output)).toSorted()
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return ABSENT
|
|
409
|
+
throw error
|
|
410
|
+
}
|
|
411
|
+
const hash = createHash('sha256')
|
|
412
|
+
for (const name of names) {
|
|
413
|
+
const path = join(output, name)
|
|
414
|
+
const stat = await fs.lstat(path)
|
|
415
|
+
hash.update(`${name}\0`)
|
|
416
|
+
if (stat.isFile()) hash.update('f\0').update(await fs.readFile(path))
|
|
417
|
+
else if (stat.isSymbolicLink()) hash.update('l\0').update(await fs.readlink(path))
|
|
418
|
+
else hash.update(`o\0${stat.mode}\0${stat.size}`)
|
|
419
|
+
hash.update('\0')
|
|
420
|
+
}
|
|
421
|
+
return `sha256:${hash.digest('hex')}`
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Runs `read` while no writer can publish to `output`, after finishing any
|
|
426
|
+
* interrupted publication. Readers are serialized with writers and with each
|
|
427
|
+
* other; the lock is held only for the read itself.
|
|
428
|
+
*/
|
|
429
|
+
export async function withCatalogRead<T>(
|
|
430
|
+
output: string,
|
|
431
|
+
read: () => Promise<T>,
|
|
432
|
+
options: CatalogCoordinationOptions = {}
|
|
433
|
+
): Promise<T> {
|
|
434
|
+
const paths = await resolvePaths(output, false)
|
|
435
|
+
if (paths === undefined) return read()
|
|
436
|
+
const lock = await acquire(paths, 'read', options)
|
|
437
|
+
try {
|
|
438
|
+
if (lock) await recoverCatalogOutput(paths)
|
|
439
|
+
return await read()
|
|
440
|
+
} finally {
|
|
441
|
+
await lock?.release()
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Replaces `output` with exactly `files`. The previous output stays in place
|
|
447
|
+
* until the new one is complete, and a coordinated reader sees either one or
|
|
448
|
+
* the other.
|
|
449
|
+
*/
|
|
450
|
+
export async function publishCatalog(
|
|
451
|
+
output: string,
|
|
452
|
+
files: Readonly<Record<string, string | Uint8Array>>,
|
|
453
|
+
options: PublishOptions = {}
|
|
454
|
+
): Promise<void> {
|
|
455
|
+
const paths = await resolvePaths(output, true)
|
|
456
|
+
if (paths === undefined) throw new Error(`CATALOG_OUTPUT_UNRESOLVED: ${output}`)
|
|
457
|
+
await options.onStep?.('acquiring')
|
|
458
|
+
const lock = await acquire(paths, 'write', options)
|
|
459
|
+
if (lock === undefined) throw new Error(`CATALOG_OUTPUT_UNRESOLVED: ${output}`)
|
|
460
|
+
try {
|
|
461
|
+
await recoverCatalogOutput(paths)
|
|
462
|
+
// A backup without a journal predates coordinated publication or was made
|
|
463
|
+
// by hand. Its provenance is unknown, so it is never deleted or restored.
|
|
464
|
+
if (await exists(paths.backup))
|
|
465
|
+
throw new Error(`CATALOG_RECOVERY_REQUIRED: preserve and inspect ${paths.backup}`)
|
|
466
|
+
if (options.expectedBase !== undefined) {
|
|
467
|
+
const current = await catalogFingerprint(paths.output)
|
|
468
|
+
if (current !== options.expectedBase)
|
|
469
|
+
throw new Error(
|
|
470
|
+
`CATALOG_BASE_CHANGED: ${paths.output} was replaced after this sync read it; run the sync again`
|
|
471
|
+
)
|
|
472
|
+
}
|
|
473
|
+
const stage = await fs.mkdtemp(paths.stagePrefix)
|
|
474
|
+
try {
|
|
475
|
+
await writeDurably(
|
|
476
|
+
paths.journal,
|
|
477
|
+
`${JSON.stringify({ version: 1, stage: basename(stage) } satisfies Journal)}\n`
|
|
478
|
+
)
|
|
479
|
+
for (const [name, content] of Object.entries(files)) {
|
|
480
|
+
if (
|
|
481
|
+
name === '' ||
|
|
482
|
+
name.includes('/') ||
|
|
483
|
+
name.includes('\\') ||
|
|
484
|
+
name === '.' ||
|
|
485
|
+
name === '..'
|
|
486
|
+
)
|
|
487
|
+
throw new Error(`CATALOG_ARTIFACT_NAME_INVALID: ${name}`)
|
|
488
|
+
await writeDurably(join(stage, name), content)
|
|
489
|
+
}
|
|
490
|
+
await syncDirectory(stage)
|
|
491
|
+
await options.onStep?.('staged')
|
|
492
|
+
await lock.assertHeld()
|
|
493
|
+
try {
|
|
494
|
+
await fs.rename(paths.output, paths.backup)
|
|
495
|
+
} catch (error) {
|
|
496
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
497
|
+
}
|
|
498
|
+
await options.onStep?.('backed-up')
|
|
499
|
+
await fs.rename(stage, paths.output)
|
|
500
|
+
await syncDirectory(paths.parent)
|
|
501
|
+
await options.onStep?.('swapped')
|
|
502
|
+
await fs.rm(paths.backup, { recursive: true, force: true })
|
|
503
|
+
await fs.rm(paths.journal, { force: true })
|
|
504
|
+
await options.onStep?.('cleaned')
|
|
505
|
+
} catch (error) {
|
|
506
|
+
// Same state machine a later process would run after a crash, unless
|
|
507
|
+
// another process now holds the lock: then it owns the recovery.
|
|
508
|
+
const held = await lock.assertHeld().then(
|
|
509
|
+
() => true,
|
|
510
|
+
() => false
|
|
511
|
+
)
|
|
512
|
+
if (held) await recoverCatalogOutput(paths)
|
|
513
|
+
throw error
|
|
514
|
+
}
|
|
515
|
+
await options.afterPublish?.()
|
|
516
|
+
} finally {
|
|
517
|
+
await lock.release()
|
|
518
|
+
}
|
|
519
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export async function mapWithConcurrency<T, U>(
|
|
2
|
+
values: readonly T[],
|
|
3
|
+
concurrency: number,
|
|
4
|
+
mapper: (value: T, index: number) => Promise<U>
|
|
5
|
+
): Promise<U[]> {
|
|
6
|
+
const results = Array.from<U>({ length: values.length })
|
|
7
|
+
let nextIndex = 0
|
|
8
|
+
const worker = async (): Promise<void> => {
|
|
9
|
+
while (true) {
|
|
10
|
+
const index = nextIndex++
|
|
11
|
+
if (index >= values.length) return
|
|
12
|
+
results[index] = await mapper(values[index]!, index)
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
await Promise.all(
|
|
16
|
+
Array.from({ length: Math.min(Math.max(concurrency, 1), values.length) }, () => worker())
|
|
17
|
+
)
|
|
18
|
+
return results
|
|
19
|
+
}
|