@defrex/autobuild 1.8.1 → 1.9.0
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/README.md +1 -1
- package/SPEC.md +92 -11
- package/docs/architecture.md +38 -14
- package/docs/configuration.md +247 -4
- package/docs/dispatcher-hosting.md +4 -0
- package/docs/merge-policy.md +45 -5
- package/docs/operating.md +21 -0
- package/docs/operator-api.md +11 -2
- package/docs/plugin-authoring.md +4 -1
- package/docs/restacking.md +4 -0
- package/docs/setup.md +3 -1
- package/docs/verification.md +7 -6
- package/package.json +4 -3
- package/packages/core/src/cli/attention.ts +3 -0
- package/packages/core/src/cli/dashboard/landing-display.ts +9 -1
- package/packages/core/src/cli/dashboard/model.ts +25 -6
- package/packages/core/src/cli/dashboard/render.ts +2 -2
- package/packages/core/src/cli/dispatch.ts +120 -1
- package/packages/core/src/cli/help.ts +6 -2
- package/packages/core/src/cli/repository-status.ts +66 -1
- package/packages/core/src/cli/status.ts +2 -2
- package/packages/core/src/cli/watch.ts +1074 -627
- package/packages/core/src/config/live.ts +1 -0
- package/packages/core/src/config/load.ts +19 -0
- package/packages/core/src/config/schema.ts +114 -0
- package/packages/core/src/events/catalog.ts +2 -0
- package/packages/core/src/events/payloads.ts +22 -0
- package/packages/core/src/events/policy.ts +9 -0
- package/packages/core/src/events/repository.ts +43 -0
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
- package/packages/core/src/kernel/auto-merge.ts +33 -0
- package/packages/core/src/kernel/generators/repository-journals.ts +18 -0
- package/packages/core/src/kernel/landing-state.ts +56 -0
- package/packages/core/src/kernel/reducer.ts +1 -1
- package/packages/core/src/plugin-sdk/index.ts +7 -1
- package/packages/core/src/ports/forge/fake.ts +128 -8
- package/packages/core/src/ports/forge/git-rewrite.ts +34 -3
- package/packages/core/src/ports/forge/github-squash-message.ts +89 -0
- package/packages/core/src/ports/forge/github-transport.ts +30 -0
- package/packages/core/src/ports/forge/github.ts +565 -164
- package/packages/core/src/ports/types.ts +47 -3
- package/packages/core/src/processes/build-execution-state.ts +4 -3
- package/packages/core/src/processes/dispatcher.ts +73 -4
- package/packages/core/src/processes/execution-no-progress.ts +2 -0
- package/packages/core/src/processes/hook-command.ts +125 -0
- package/packages/core/src/processes/hook-webhook.ts +144 -0
- package/packages/core/src/processes/hooks.ts +740 -0
- package/packages/core/src/store/contract.ts +28 -0
- package/packages/core/src/store/reducer-value-shapes.json +3729 -3297
- package/packages/core/src/store/remote/released-clients.json +11 -0
- package/packages/core/src/store/remote/released-reducer-values/1.9.0.json +29475 -0
- package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
- package/packages/core/src/store/repo-state-events.ts +3 -0
- package/packages/core/src/store/retention.ts +16 -2
- package/packages/core/src/testing/index.ts +1 -0
- package/packages/core/src/testing/reduced-read-budget.ts +476 -1
- package/skills/guide/SKILL.md +81 -6
- package/skills/guide/references/merge-policy.md +45 -5
- package/skills/guide/references/operator-api.md +11 -2
- package/skills/guide/references/plugin-authoring.md +4 -1
- package/skills/guide/references/restacking.md +4 -0
- package/skills/guide/references/setup.md +3 -1
- package/skills/operate/SKILL.md +24 -4
- package/templates/hosted-service/package.json +2 -2
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configured hooks (§16.1 `[hooks]`): observe-only consumers the
|
|
3
|
+
* lease-holding dispatcher feeds. Each hook runs its own in-process
|
|
4
|
+
* `ab watch` feed (`cli/watch.ts`, `WatchFeed`) from a durable position, and
|
|
5
|
+
* every record the feed emits — the exact `ab watch --json` line, `id`
|
|
6
|
+
* included — is delivered to the hook's command or URL, one at a time and in
|
|
7
|
+
* order.
|
|
8
|
+
* Progress advances only after a success, so delivery is at-least-once.
|
|
9
|
+
*
|
|
10
|
+
* Nothing here is read by a decision path: a hook's exit status, output and
|
|
11
|
+
* duration never reach build state, and each hook has its own async loop
|
|
12
|
+
* outside the dispatch tick, so a slow or failing hook delays nothing else.
|
|
13
|
+
*
|
|
14
|
+
* Durable progress is the latest revision of the retention-managed
|
|
15
|
+
* repository artifact `hook-progress.<name>`. Its `position` is a safe point:
|
|
16
|
+
* a feed cursor such that every record emitted before it has been delivered.
|
|
17
|
+
* It moves on each success, and — for progress the hook's filter does not
|
|
18
|
+
* match — through checkpoints taken only when every record emitted before
|
|
19
|
+
* them has succeeded.
|
|
20
|
+
*
|
|
21
|
+
* Read cost: one shared gate reads `getRepoChangePosition` once per interval
|
|
22
|
+
* for every hook. An unchanged position runs only in-memory timer checks;
|
|
23
|
+
* a changed one runs each feed's incremental pass. Build discovery depends on
|
|
24
|
+
* ticket preparation journaling `creation-selected` and `resolved owned`
|
|
25
|
+
* around every `createBuild` (see `WatchFeed`); a new `createBuild` call site
|
|
26
|
+
* must journal the same way or hooks will not see its builds.
|
|
27
|
+
*/
|
|
28
|
+
import { z } from 'zod'
|
|
29
|
+
import type { HookConfig } from '../config/schema'
|
|
30
|
+
import type { RepositoryEventWrite } from '../events/repository'
|
|
31
|
+
import { DISPATCHER } from '../events/envelope'
|
|
32
|
+
import { CursorTooOldError, RetiredSeedGenerationError } from '../store/event-reads'
|
|
33
|
+
import { hookProgressKind } from '../store/retention'
|
|
34
|
+
import type { BuildStore } from '../store/types'
|
|
35
|
+
import { abWatch, decodeCursor, type WatchJsonRecord } from '../cli/watch'
|
|
36
|
+
import { defaultDelay } from '../cli/remote-poll'
|
|
37
|
+
|
|
38
|
+
/** Continuous failure after which `hook.failing` is recorded, once per episode. */
|
|
39
|
+
export const HOOK_FAILING_ATTENTION_MS = 5 * 60_000
|
|
40
|
+
/** Longest a safe checkpoint of filtered-out progress waits while the position moves. */
|
|
41
|
+
export const HOOK_CHECKPOINT_INTERVAL_MS = 30_000
|
|
42
|
+
/** Queued records at which a feed stops reading further events this pass. */
|
|
43
|
+
export const HOOK_QUEUE_LIMIT = 500
|
|
44
|
+
const BACKOFF_MAX_MS = 60_000
|
|
45
|
+
const SKIPPED_RANGES_MAX = 1_000
|
|
46
|
+
|
|
47
|
+
export const hookProgressSchema = z.strictObject({
|
|
48
|
+
v: z.literal(1),
|
|
49
|
+
hook: z.string().min(1),
|
|
50
|
+
/** The durable safe point: every record emitted before it was delivered. */
|
|
51
|
+
position: z.string().min(1),
|
|
52
|
+
delivered: z.number().int().min(0),
|
|
53
|
+
lastSuccessAt: z.iso.datetime().optional(),
|
|
54
|
+
lastDeliveredId: z.string().min(1).optional(),
|
|
55
|
+
/** Records queued, including one in flight, when this revision was written. */
|
|
56
|
+
pending: z.number().int().min(0),
|
|
57
|
+
failing: z
|
|
58
|
+
.strictObject({
|
|
59
|
+
since: z.iso.datetime(),
|
|
60
|
+
attempts: z.number().int().min(1),
|
|
61
|
+
error: z.string(),
|
|
62
|
+
reported: z.boolean(),
|
|
63
|
+
})
|
|
64
|
+
.optional(),
|
|
65
|
+
/** A reported failure episode whose `hook.recovered` is not yet recorded. */
|
|
66
|
+
recovery: z
|
|
67
|
+
.strictObject({
|
|
68
|
+
since: z.iso.datetime(),
|
|
69
|
+
attempts: z.number().int().min(1),
|
|
70
|
+
})
|
|
71
|
+
.optional(),
|
|
72
|
+
updatedAt: z.iso.datetime(),
|
|
73
|
+
})
|
|
74
|
+
export type HookProgress = z.infer<typeof hookProgressSchema>
|
|
75
|
+
|
|
76
|
+
/** The latest valid progress of one hook; an invalid artifact counts as absent. */
|
|
77
|
+
export async function readHookProgress(
|
|
78
|
+
store: Pick<BuildStore, 'getRepoArtifact'>,
|
|
79
|
+
repo: string,
|
|
80
|
+
name: string,
|
|
81
|
+
warn?: (message: string) => void,
|
|
82
|
+
): Promise<HookProgress | undefined> {
|
|
83
|
+
const artifact = await store.getRepoArtifact(repo, hookProgressKind(name))
|
|
84
|
+
if (artifact === null) return undefined
|
|
85
|
+
let value: unknown
|
|
86
|
+
try {
|
|
87
|
+
value = JSON.parse(new TextDecoder().decode(artifact.content))
|
|
88
|
+
} catch {
|
|
89
|
+
value = undefined
|
|
90
|
+
}
|
|
91
|
+
const parsed = hookProgressSchema.safeParse(value)
|
|
92
|
+
if (parsed.success) return parsed.data
|
|
93
|
+
warn?.(`hook ${name}: ignoring invalid progress; starting from the current position`)
|
|
94
|
+
return undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type HookInvokeResult = { ok: true } | { ok: false; error: string }
|
|
98
|
+
/** Deliver one record (`line` ends with a newline; `record` carries its
|
|
99
|
+
* stable id). Never throws. */
|
|
100
|
+
export type HookInvoke = (
|
|
101
|
+
hook: { name: string; config: HookConfig },
|
|
102
|
+
line: string,
|
|
103
|
+
signal: AbortSignal,
|
|
104
|
+
record?: { id: string },
|
|
105
|
+
) => Promise<HookInvokeResult>
|
|
106
|
+
|
|
107
|
+
export interface HookSupervisorDeps {
|
|
108
|
+
store: BuildStore
|
|
109
|
+
repo: string
|
|
110
|
+
storeRef: string
|
|
111
|
+
checkout: string
|
|
112
|
+
clock: () => Date
|
|
113
|
+
invoke: HookInvoke
|
|
114
|
+
warn: (message: string) => void
|
|
115
|
+
appendRepo: (event: RepositoryEventWrite) => Promise<unknown>
|
|
116
|
+
/** The change-gate cadence: 1 s for local stores, 5 s remote. */
|
|
117
|
+
intervalMs: number
|
|
118
|
+
/** Gate sleep between position reads; injectable for tests. */
|
|
119
|
+
interval?: (signal: AbortSignal) => Promise<void>
|
|
120
|
+
/** Retry backoff sleep; injectable for tests. */
|
|
121
|
+
backoff?: (ms: number, signal: AbortSignal) => Promise<void>
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
interface Queued {
|
|
125
|
+
id: string
|
|
126
|
+
line: string
|
|
127
|
+
cursor: string
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* One gate for every hook: a single `getRepoChangePosition` read per interval,
|
|
132
|
+
* however many hooks are configured, and none when no hook is.
|
|
133
|
+
*/
|
|
134
|
+
export class HookSupervisor {
|
|
135
|
+
private readonly workers = new Map<string, HookWorker>()
|
|
136
|
+
private gate: AbortController | undefined
|
|
137
|
+
private gateTask: Promise<void> | undefined
|
|
138
|
+
private waiters = new Set<() => void>()
|
|
139
|
+
/** The last change position read; workers compare it to what they consumed. */
|
|
140
|
+
position: string | undefined
|
|
141
|
+
private gateReported = false
|
|
142
|
+
|
|
143
|
+
constructor(readonly deps: HookSupervisorDeps) {}
|
|
144
|
+
|
|
145
|
+
/** Start new hooks, stop removed ones, restart changed ones from durable progress. */
|
|
146
|
+
async reconcile(hooks: Readonly<Record<string, HookConfig>>): Promise<void> {
|
|
147
|
+
const stopping: Promise<void>[] = []
|
|
148
|
+
for (const [name, worker] of this.workers) {
|
|
149
|
+
const next = Object.hasOwn(hooks, name) ? hooks[name] : undefined
|
|
150
|
+
if (next !== undefined && JSON.stringify(next) === JSON.stringify(worker.config)) continue
|
|
151
|
+
this.workers.delete(name)
|
|
152
|
+
stopping.push(worker.stop())
|
|
153
|
+
}
|
|
154
|
+
await Promise.all(stopping)
|
|
155
|
+
for (const [name, config] of Object.entries(hooks)) {
|
|
156
|
+
if (this.workers.has(name)) continue
|
|
157
|
+
const worker = new HookWorker(this, name, config, 'watch')
|
|
158
|
+
this.workers.set(name, worker)
|
|
159
|
+
worker.start()
|
|
160
|
+
}
|
|
161
|
+
if (this.workers.size > 0) this.startGate()
|
|
162
|
+
else await this.stopGate()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Stop every worker (in-flight commands are terminated and redelivered later). */
|
|
166
|
+
async stop(): Promise<void> {
|
|
167
|
+
const workers = [...this.workers.values()]
|
|
168
|
+
this.workers.clear()
|
|
169
|
+
await Promise.all(workers.map((worker) => worker.stop()))
|
|
170
|
+
await this.stopGate()
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* `ab dispatch --once`: each hook resumes, makes one full pass, delivers its
|
|
175
|
+
* queue until empty or its first failure, and stops at a safe checkpoint.
|
|
176
|
+
* The next invocation is the retry. An abort of `signal` (the invocation
|
|
177
|
+
* deadline) stops every worker as `stop()` does: the in-flight attempt is
|
|
178
|
+
* neither success nor failure and is redelivered next time.
|
|
179
|
+
*/
|
|
180
|
+
async drainOnce(
|
|
181
|
+
hooks: Readonly<Record<string, HookConfig>>,
|
|
182
|
+
signal?: AbortSignal,
|
|
183
|
+
): Promise<void> {
|
|
184
|
+
await Promise.all(
|
|
185
|
+
Object.entries(hooks).map(async ([name, config]) => {
|
|
186
|
+
const worker = new HookWorker(this, name, config, 'once')
|
|
187
|
+
const onAbort = (): void => void worker.stop()
|
|
188
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
189
|
+
try {
|
|
190
|
+
worker.start()
|
|
191
|
+
if (signal?.aborted === true) onAbort()
|
|
192
|
+
await worker.settled
|
|
193
|
+
} finally {
|
|
194
|
+
signal?.removeEventListener('abort', onAbort)
|
|
195
|
+
}
|
|
196
|
+
}),
|
|
197
|
+
)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Hook names with a running worker. */
|
|
201
|
+
get names(): string[] {
|
|
202
|
+
return [...this.workers.keys()]
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** One gate read, then wake every waiting feed. */
|
|
206
|
+
async pulse(): Promise<void> {
|
|
207
|
+
try {
|
|
208
|
+
this.position = await this.deps.store.getRepoChangePosition(this.deps.repo)
|
|
209
|
+
this.gateReported = false
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (!this.gateReported)
|
|
212
|
+
this.deps.warn(
|
|
213
|
+
`hooks: change position read failed (${error instanceof Error ? error.message : String(error)}); retrying`,
|
|
214
|
+
)
|
|
215
|
+
this.gateReported = true
|
|
216
|
+
}
|
|
217
|
+
const waiters = [...this.waiters]
|
|
218
|
+
this.waiters.clear()
|
|
219
|
+
for (const wake of waiters) wake()
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Resolves at the next gate pulse, or when `signal` aborts. */
|
|
223
|
+
nextWake(signal: AbortSignal): Promise<void> {
|
|
224
|
+
return new Promise((resolve) => {
|
|
225
|
+
if (signal.aborted) return resolve()
|
|
226
|
+
const wake = (): void => {
|
|
227
|
+
signal.removeEventListener('abort', wake)
|
|
228
|
+
this.waiters.delete(wake)
|
|
229
|
+
resolve()
|
|
230
|
+
}
|
|
231
|
+
this.waiters.add(wake)
|
|
232
|
+
signal.addEventListener('abort', wake, { once: true })
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private startGate(): void {
|
|
237
|
+
if (this.gate !== undefined) return
|
|
238
|
+
const gate = new AbortController()
|
|
239
|
+
this.gate = gate
|
|
240
|
+
const sleep =
|
|
241
|
+
this.deps.interval ?? ((signal: AbortSignal) => defaultDelay(this.deps.intervalMs, signal))
|
|
242
|
+
this.gateTask = (async () => {
|
|
243
|
+
while (!gate.signal.aborted) {
|
|
244
|
+
await sleep(gate.signal)
|
|
245
|
+
if (gate.signal.aborted) break
|
|
246
|
+
await this.pulse()
|
|
247
|
+
}
|
|
248
|
+
})()
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private async stopGate(): Promise<void> {
|
|
252
|
+
this.gate?.abort()
|
|
253
|
+
await this.gateTask
|
|
254
|
+
this.gate = undefined
|
|
255
|
+
this.gateTask = undefined
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function errorMessage(error: unknown): string {
|
|
260
|
+
return error instanceof Error ? error.message : String(error)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
class HookWorker {
|
|
264
|
+
private readonly stopping = new AbortController()
|
|
265
|
+
private task: Promise<void> | undefined
|
|
266
|
+
/** Resolves when the worker has fully stopped. */
|
|
267
|
+
settled: Promise<void> = Promise.resolve()
|
|
268
|
+
|
|
269
|
+
// Per feed session; reset whenever the feed (re)starts.
|
|
270
|
+
private queue: Queued[] = []
|
|
271
|
+
private emitted = 0
|
|
272
|
+
private succeeded = 0
|
|
273
|
+
private candidate: { cursor: string; emitted: number } | undefined
|
|
274
|
+
private consumed: string | undefined
|
|
275
|
+
private queued: (() => void) | undefined
|
|
276
|
+
private passes = 0
|
|
277
|
+
private passDone: (() => void) | undefined
|
|
278
|
+
|
|
279
|
+
/** The in-memory progress; `written` is the last revision persisted. */
|
|
280
|
+
private state: HookProgress | undefined
|
|
281
|
+
private written: HookProgress | undefined
|
|
282
|
+
private lastWriteAt = 0
|
|
283
|
+
private writes: Promise<void> = Promise.resolve()
|
|
284
|
+
private recoveryFailures = 0
|
|
285
|
+
|
|
286
|
+
constructor(
|
|
287
|
+
private readonly supervisor: HookSupervisor,
|
|
288
|
+
readonly name: string,
|
|
289
|
+
readonly config: HookConfig,
|
|
290
|
+
private readonly mode: 'watch' | 'once',
|
|
291
|
+
) {}
|
|
292
|
+
|
|
293
|
+
private get deps(): HookSupervisorDeps {
|
|
294
|
+
return this.supervisor.deps
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
start(): void {
|
|
298
|
+
this.task = this.run().catch((error) => {
|
|
299
|
+
this.deps.warn(`hook ${this.name}: stopped unexpectedly (${errorMessage(error)})`)
|
|
300
|
+
})
|
|
301
|
+
this.settled = this.task
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async stop(): Promise<void> {
|
|
305
|
+
this.stopping.abort()
|
|
306
|
+
await this.task
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private now(): Date {
|
|
310
|
+
return this.deps.clock()
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private sleepBackoff(attempts: number, signal: AbortSignal): Promise<void> {
|
|
314
|
+
const ms = Math.min(1000 * 2 ** Math.max(0, attempts - 1), BACKOFF_MAX_MS)
|
|
315
|
+
return (this.deps.backoff ?? defaultDelay)(ms, signal)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Persist the current in-memory progress; writes are serialized and each
|
|
319
|
+
* writes the newest state, so a slower write never regresses the position.
|
|
320
|
+
* Resolves whether the write succeeded; a failure is warned, never thrown. */
|
|
321
|
+
private persist(): Promise<boolean> {
|
|
322
|
+
const next = this.writes.then(async () => {
|
|
323
|
+
if (this.state === undefined) return true
|
|
324
|
+
const snapshot: HookProgress = { ...this.state, updatedAt: this.now().toISOString() }
|
|
325
|
+
try {
|
|
326
|
+
await this.deps.store.putRepoArtifact(this.deps.repo, {
|
|
327
|
+
kind: hookProgressKind(this.name),
|
|
328
|
+
content: JSON.stringify(snapshot),
|
|
329
|
+
})
|
|
330
|
+
this.written = snapshot
|
|
331
|
+
this.lastWriteAt = this.now().getTime()
|
|
332
|
+
return true
|
|
333
|
+
} catch (error) {
|
|
334
|
+
this.deps.warn(`hook ${this.name}: progress write failed (${errorMessage(error)})`)
|
|
335
|
+
return false
|
|
336
|
+
}
|
|
337
|
+
})
|
|
338
|
+
this.writes = next.then(() => {})
|
|
339
|
+
return next
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private async append(event: RepositoryEventWrite): Promise<boolean> {
|
|
343
|
+
try {
|
|
344
|
+
await this.deps.appendRepo(event)
|
|
345
|
+
return true
|
|
346
|
+
} catch (error) {
|
|
347
|
+
this.deps.warn(`hook ${this.name}: could not record ${event.type} (${errorMessage(error)})`)
|
|
348
|
+
return false
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
private async run(): Promise<void> {
|
|
353
|
+
const stopping = this.stopping.signal
|
|
354
|
+
let rebaseline: { reason: string; old: string | undefined } | undefined
|
|
355
|
+
let feedFailures = 0
|
|
356
|
+
while (!stopping.aborted) {
|
|
357
|
+
let progress: HookProgress | undefined
|
|
358
|
+
try {
|
|
359
|
+
progress = await readHookProgress(this.deps.store, this.deps.repo, this.name, (message) =>
|
|
360
|
+
this.deps.warn(message),
|
|
361
|
+
)
|
|
362
|
+
} catch (error) {
|
|
363
|
+
feedFailures += 1
|
|
364
|
+
this.deps.warn(`hook ${this.name}: progress read failed (${errorMessage(error)}); retrying`)
|
|
365
|
+
if (this.mode === 'once') return
|
|
366
|
+
await this.sleepBackoff(feedFailures, stopping)
|
|
367
|
+
continue
|
|
368
|
+
}
|
|
369
|
+
this.state = progress
|
|
370
|
+
this.written = progress
|
|
371
|
+
this.lastWriteAt = this.now().getTime()
|
|
372
|
+
this.queue = []
|
|
373
|
+
this.emitted = 0
|
|
374
|
+
this.succeeded = 0
|
|
375
|
+
this.candidate = undefined
|
|
376
|
+
this.passes = 0
|
|
377
|
+
this.consumed = this.supervisor.position
|
|
378
|
+
|
|
379
|
+
// A position this store or repository cannot resume (a moved checkout,
|
|
380
|
+
// a switched store) is history the hook can no longer read.
|
|
381
|
+
if (rebaseline === undefined && progress !== undefined) {
|
|
382
|
+
try {
|
|
383
|
+
decodeCursor(progress.position, { store: this.deps.storeRef, repo: this.deps.repo })
|
|
384
|
+
} catch (error) {
|
|
385
|
+
rebaseline = { reason: errorMessage(error), old: undefined }
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const session = new AbortController()
|
|
389
|
+
const signal = AbortSignal.any([stopping, session.signal])
|
|
390
|
+
const since = rebaseline === undefined ? progress?.position : undefined
|
|
391
|
+
const skip = rebaseline
|
|
392
|
+
const delivery = this.deliver(signal, session)
|
|
393
|
+
let failure: unknown
|
|
394
|
+
try {
|
|
395
|
+
await abWatch({
|
|
396
|
+
targetRepo: this.deps.checkout,
|
|
397
|
+
env: {},
|
|
398
|
+
exec: async () => {
|
|
399
|
+
throw new Error('hook feeds run no commands')
|
|
400
|
+
},
|
|
401
|
+
stdout: () => {},
|
|
402
|
+
stderr: (line) => this.deps.warn(`hook ${this.name}: ${line}`),
|
|
403
|
+
...(since !== undefined ? { since } : {}),
|
|
404
|
+
...(this.config.events !== undefined ? { events: this.config.events } : {}),
|
|
405
|
+
timeout: '0',
|
|
406
|
+
json: true,
|
|
407
|
+
now: () => this.now(),
|
|
408
|
+
delay: (_ms, delaySignal) => this.feedDelay(delaySignal ?? signal),
|
|
409
|
+
signal,
|
|
410
|
+
feed: {
|
|
411
|
+
context: {
|
|
412
|
+
store: this.deps.store,
|
|
413
|
+
repo: this.deps.repo,
|
|
414
|
+
storeRef: this.deps.storeRef,
|
|
415
|
+
checkout: this.deps.checkout,
|
|
416
|
+
},
|
|
417
|
+
record: (record) => this.enqueue(record),
|
|
418
|
+
baseline: (cursor) => this.saveBaseline(cursor, progress, skip),
|
|
419
|
+
position: (cursor) => this.onPosition(cursor),
|
|
420
|
+
changed: async () => {
|
|
421
|
+
if (this.mode === 'once') return true
|
|
422
|
+
const position = this.supervisor.position
|
|
423
|
+
if (position === this.consumed) return false
|
|
424
|
+
this.consumed = position
|
|
425
|
+
return true
|
|
426
|
+
},
|
|
427
|
+
saturated: () => this.queue.length >= HOOK_QUEUE_LIMIT,
|
|
428
|
+
unresolved: async (reason) => {
|
|
429
|
+
await this.deps.appendRepo({
|
|
430
|
+
actor: DISPATCHER,
|
|
431
|
+
type: 'hook.skipped',
|
|
432
|
+
payload: { hook: this.name, reason, ranges: [] },
|
|
433
|
+
})
|
|
434
|
+
},
|
|
435
|
+
},
|
|
436
|
+
})
|
|
437
|
+
} catch (error) {
|
|
438
|
+
failure = error
|
|
439
|
+
}
|
|
440
|
+
session.abort()
|
|
441
|
+
await delivery
|
|
442
|
+
if (stopping.aborted || (this.mode === 'once' && failure === undefined)) {
|
|
443
|
+
await this.checkpoint(true)
|
|
444
|
+
await this.writes
|
|
445
|
+
return
|
|
446
|
+
}
|
|
447
|
+
rebaseline = undefined
|
|
448
|
+
if (failure instanceof CursorTooOldError || failure instanceof RetiredSeedGenerationError) {
|
|
449
|
+
// History the hook still needed is gone: resume from the current
|
|
450
|
+
// position and report the skipped range, never drop it silently.
|
|
451
|
+
rebaseline = { reason: errorMessage(failure), old: this.state?.position }
|
|
452
|
+
continue
|
|
453
|
+
}
|
|
454
|
+
feedFailures += 1
|
|
455
|
+
this.deps.warn(`hook ${this.name}: feed failed (${errorMessage(failure)}); restarting`)
|
|
456
|
+
if (this.mode === 'once') return
|
|
457
|
+
await this.sleepBackoff(feedFailures, stopping)
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** The pre-emission baseline of a new hook (or a rebaseline), persisted
|
|
462
|
+
* before the feed emits anything. */
|
|
463
|
+
private async saveBaseline(
|
|
464
|
+
cursor: string,
|
|
465
|
+
progress: HookProgress | undefined,
|
|
466
|
+
skip: { reason: string; old: string | undefined } | undefined,
|
|
467
|
+
): Promise<void> {
|
|
468
|
+
if (skip !== undefined) {
|
|
469
|
+
await this.deps.appendRepo({
|
|
470
|
+
actor: DISPATCHER,
|
|
471
|
+
type: 'hook.skipped',
|
|
472
|
+
payload: {
|
|
473
|
+
hook: this.name,
|
|
474
|
+
reason: skip.reason.slice(0, 1_000) || 'history unavailable',
|
|
475
|
+
ranges: this.skippedRanges(skip.old, cursor),
|
|
476
|
+
},
|
|
477
|
+
})
|
|
478
|
+
}
|
|
479
|
+
const now = this.now().toISOString()
|
|
480
|
+
const next: HookProgress = {
|
|
481
|
+
v: 1,
|
|
482
|
+
hook: this.name,
|
|
483
|
+
position: cursor,
|
|
484
|
+
delivered: progress?.delivered ?? 0,
|
|
485
|
+
...(progress?.lastSuccessAt !== undefined ? { lastSuccessAt: progress.lastSuccessAt } : {}),
|
|
486
|
+
...(progress?.lastDeliveredId !== undefined
|
|
487
|
+
? { lastDeliveredId: progress.lastDeliveredId }
|
|
488
|
+
: {}),
|
|
489
|
+
pending: 0,
|
|
490
|
+
...(progress?.failing !== undefined ? { failing: progress.failing } : {}),
|
|
491
|
+
...(progress?.recovery !== undefined ? { recovery: progress.recovery } : {}),
|
|
492
|
+
updatedAt: now,
|
|
493
|
+
}
|
|
494
|
+
await this.deps.store.putRepoArtifact(this.deps.repo, {
|
|
495
|
+
kind: hookProgressKind(this.name),
|
|
496
|
+
content: JSON.stringify(next),
|
|
497
|
+
})
|
|
498
|
+
this.state = next
|
|
499
|
+
this.written = next
|
|
500
|
+
this.lastWriteAt = this.now().getTime()
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
private skippedRanges(
|
|
504
|
+
old: string | undefined,
|
|
505
|
+
cursor: string,
|
|
506
|
+
): { stream: string; after: number; through: number }[] {
|
|
507
|
+
if (old === undefined) return []
|
|
508
|
+
const expected = { store: this.deps.storeRef, repo: this.deps.repo }
|
|
509
|
+
try {
|
|
510
|
+
const before = decodeCursor(old, expected).streams
|
|
511
|
+
const after = decodeCursor(cursor, expected).streams
|
|
512
|
+
const ranges: { stream: string; after: number; through: number }[] = []
|
|
513
|
+
for (const [stream, through] of Object.entries(after)) {
|
|
514
|
+
const from = before[stream]
|
|
515
|
+
if (from !== undefined && through > from) ranges.push({ stream, after: from, through })
|
|
516
|
+
}
|
|
517
|
+
return ranges.slice(0, SKIPPED_RANGES_MAX)
|
|
518
|
+
} catch {
|
|
519
|
+
return []
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
private enqueue(record: WatchJsonRecord): void {
|
|
524
|
+
this.emitted += 1
|
|
525
|
+
this.queue.push({ id: record.id, line: JSON.stringify(record), cursor: record.cursor })
|
|
526
|
+
this.queued?.()
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
private onPosition(cursor: string): void {
|
|
530
|
+
this.candidate = { cursor, emitted: this.emitted }
|
|
531
|
+
this.passes += 1
|
|
532
|
+
void this.checkpoint(false)
|
|
533
|
+
// `--once`: the resume pass and one full pass are the whole feed.
|
|
534
|
+
if (this.mode === 'once' && this.passes >= 2) this.passDone?.()
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
private async feedDelay(signal: AbortSignal): Promise<void> {
|
|
538
|
+
if (this.mode === 'watch') return this.supervisor.nextWake(signal)
|
|
539
|
+
if (this.passes < 2) return
|
|
540
|
+
// After its full pass a `--once` feed waits for delivery to finish.
|
|
541
|
+
await new Promise<void>((resolve) => {
|
|
542
|
+
if (signal.aborted) return resolve()
|
|
543
|
+
signal.addEventListener('abort', () => resolve(), { once: true })
|
|
544
|
+
})
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Persist the newest safe candidate: one taken after the last delivered
|
|
549
|
+
* record, while nothing emitted before it is still undelivered. Only that
|
|
550
|
+
* candidate is both safe and newer than the delivered position.
|
|
551
|
+
*/
|
|
552
|
+
private async checkpoint(force: boolean): Promise<void> {
|
|
553
|
+
const candidate = this.candidate
|
|
554
|
+
if (this.state === undefined || candidate === undefined) return
|
|
555
|
+
if (candidate.emitted !== this.succeeded || candidate.cursor === this.state.position) return
|
|
556
|
+
if (!force && this.now().getTime() - this.lastWriteAt < HOOK_CHECKPOINT_INTERVAL_MS) return
|
|
557
|
+
this.state = { ...this.state, position: candidate.cursor, pending: this.queue.length }
|
|
558
|
+
await this.persist()
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Waits for a queued record or the end of the session. */
|
|
562
|
+
private waitForRecord(signal: AbortSignal): Promise<void> {
|
|
563
|
+
return new Promise((resolve) => {
|
|
564
|
+
if (signal.aborted || this.queue.length > 0) return resolve()
|
|
565
|
+
const done = (): void => {
|
|
566
|
+
this.queued = undefined
|
|
567
|
+
signal.removeEventListener('abort', done)
|
|
568
|
+
resolve()
|
|
569
|
+
}
|
|
570
|
+
this.queued = done
|
|
571
|
+
signal.addEventListener('abort', done, { once: true })
|
|
572
|
+
})
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Waits for a queued record, or a backoff before retrying the recovery report. */
|
|
576
|
+
private async waitForRecordOrRetry(signal: AbortSignal): Promise<void> {
|
|
577
|
+
const woken = new AbortController()
|
|
578
|
+
const both = AbortSignal.any([signal, woken.signal])
|
|
579
|
+
await Promise.race([
|
|
580
|
+
this.waitForRecord(both),
|
|
581
|
+
this.sleepBackoff(Math.max(1, this.recoveryFailures), both),
|
|
582
|
+
])
|
|
583
|
+
woken.abort()
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Record the outstanding `hook.recovered`, if any, and clear the durable
|
|
588
|
+
* obligation. Resolves false while the append fails; the command is never
|
|
589
|
+
* rerun to retry it.
|
|
590
|
+
*/
|
|
591
|
+
private async reportRecovery(): Promise<boolean> {
|
|
592
|
+
const recovery = this.state?.recovery
|
|
593
|
+
if (recovery === undefined) return true
|
|
594
|
+
const recorded = await this.append({
|
|
595
|
+
actor: DISPATCHER,
|
|
596
|
+
type: 'hook.recovered',
|
|
597
|
+
payload: { hook: this.name, since: recovery.since, attempts: recovery.attempts },
|
|
598
|
+
})
|
|
599
|
+
if (!recorded) {
|
|
600
|
+
this.recoveryFailures += 1
|
|
601
|
+
return false
|
|
602
|
+
}
|
|
603
|
+
this.recoveryFailures = 0
|
|
604
|
+
const { recovery: _reported, ...rest } = this.state!
|
|
605
|
+
this.state = rest
|
|
606
|
+
await this.persist()
|
|
607
|
+
return true
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
private async deliver(signal: AbortSignal, session: AbortController): Promise<void> {
|
|
611
|
+
const hook = { name: this.name, config: this.config }
|
|
612
|
+
let passEnded = this.mode === 'watch'
|
|
613
|
+
if (this.mode === 'once') {
|
|
614
|
+
void new Promise<void>((resolve) => {
|
|
615
|
+
this.passDone = resolve
|
|
616
|
+
}).then(() => {
|
|
617
|
+
passEnded = true
|
|
618
|
+
this.queued?.()
|
|
619
|
+
})
|
|
620
|
+
}
|
|
621
|
+
while (!signal.aborted) {
|
|
622
|
+
await this.reportRecovery()
|
|
623
|
+
const head = this.queue[0]
|
|
624
|
+
if (head === undefined) {
|
|
625
|
+
if (this.mode === 'once' && passEnded) {
|
|
626
|
+
session.abort()
|
|
627
|
+
return
|
|
628
|
+
}
|
|
629
|
+
if (this.mode === 'watch' && this.state?.recovery !== undefined)
|
|
630
|
+
await this.waitForRecordOrRetry(signal)
|
|
631
|
+
else await this.waitForRecord(signal)
|
|
632
|
+
continue
|
|
633
|
+
}
|
|
634
|
+
if (this.state === undefined) {
|
|
635
|
+
await this.waitForRecord(signal)
|
|
636
|
+
continue
|
|
637
|
+
}
|
|
638
|
+
if (this.written?.pending === 0) {
|
|
639
|
+
this.state = { ...this.state, pending: this.queue.length }
|
|
640
|
+
await this.persist()
|
|
641
|
+
}
|
|
642
|
+
const result = await this.deps.invoke(hook, `${head.line}\n`, signal, { id: head.id })
|
|
643
|
+
// A stop terminates the in-flight attempt; it is neither a success nor
|
|
644
|
+
// a failure, and the record is redelivered by the next session.
|
|
645
|
+
if (signal.aborted) return
|
|
646
|
+
if (result.ok) {
|
|
647
|
+
// The next record waits until this success is durable, so a restart
|
|
648
|
+
// redelivers at most the one record in flight.
|
|
649
|
+
if (!(await this.succeed(head, signal))) {
|
|
650
|
+
if (this.mode === 'once') session.abort()
|
|
651
|
+
return
|
|
652
|
+
}
|
|
653
|
+
} else {
|
|
654
|
+
await this.fail(head, result.error)
|
|
655
|
+
if (this.mode === 'once') {
|
|
656
|
+
session.abort()
|
|
657
|
+
return
|
|
658
|
+
}
|
|
659
|
+
await this.sleepBackoff(this.state?.failing?.attempts ?? 1, signal)
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Record a success and persist it, retrying the progress write with backoff
|
|
666
|
+
* (never the command). Resolves false when the session ends, or a `--once`
|
|
667
|
+
* write fails, before the success is durable; the record is then redelivered.
|
|
668
|
+
*/
|
|
669
|
+
private async succeed(record: Queued, signal: AbortSignal): Promise<boolean> {
|
|
670
|
+
this.queue.shift()
|
|
671
|
+
this.succeeded += 1
|
|
672
|
+
const failing = this.state!.failing
|
|
673
|
+
const candidate = this.candidate
|
|
674
|
+
// A candidate snapshotted after this record (and nothing undelivered
|
|
675
|
+
// before it) is newer and still safe: it carries filtered-out progress.
|
|
676
|
+
const position =
|
|
677
|
+
candidate !== undefined && candidate.emitted === this.succeeded
|
|
678
|
+
? candidate.cursor
|
|
679
|
+
: record.cursor
|
|
680
|
+
const { failing: _cleared, ...rest } = this.state!
|
|
681
|
+
this.state = {
|
|
682
|
+
...rest,
|
|
683
|
+
position,
|
|
684
|
+
delivered: this.state!.delivered + 1,
|
|
685
|
+
lastSuccessAt: this.now().toISOString(),
|
|
686
|
+
lastDeliveredId: record.id,
|
|
687
|
+
pending: this.queue.length,
|
|
688
|
+
// The episode's recovery is an obligation persisted with the success
|
|
689
|
+
// and reported by the delivery loop until `hook.recovered` lands.
|
|
690
|
+
...(failing?.reported === true
|
|
691
|
+
? { recovery: { since: failing.since, attempts: failing.attempts } }
|
|
692
|
+
: {}),
|
|
693
|
+
}
|
|
694
|
+
let attempts = 0
|
|
695
|
+
while (!(await this.persist())) {
|
|
696
|
+
attempts += 1
|
|
697
|
+
if (this.mode === 'once' || signal.aborted) return false
|
|
698
|
+
await this.sleepBackoff(attempts, signal)
|
|
699
|
+
if (signal.aborted) return false
|
|
700
|
+
}
|
|
701
|
+
return true
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
private async fail(record: Queued, error: string): Promise<void> {
|
|
705
|
+
const now = this.now()
|
|
706
|
+
const message = error.trim().length > 0 ? error.slice(0, 1_000) : 'failed'
|
|
707
|
+
const previous = this.state!.failing
|
|
708
|
+
const failing = previous
|
|
709
|
+
? { ...previous, attempts: previous.attempts + 1, error: message }
|
|
710
|
+
: { since: now.toISOString(), attempts: 1, error: message, reported: false }
|
|
711
|
+
this.state = { ...this.state!, failing, pending: this.queue.length }
|
|
712
|
+
let write = previous === undefined
|
|
713
|
+
if (previous === undefined)
|
|
714
|
+
this.deps.warn(`hook ${this.name}: delivery of ${record.id} failed (${message}); retrying`)
|
|
715
|
+
if (
|
|
716
|
+
!failing.reported &&
|
|
717
|
+
now.getTime() - Date.parse(failing.since) >= HOOK_FAILING_ATTENTION_MS &&
|
|
718
|
+
// A new episode is reported only after the previous one's recovery.
|
|
719
|
+
(await this.reportRecovery())
|
|
720
|
+
) {
|
|
721
|
+
if (
|
|
722
|
+
await this.append({
|
|
723
|
+
actor: DISPATCHER,
|
|
724
|
+
type: 'hook.failing',
|
|
725
|
+
payload: {
|
|
726
|
+
hook: this.name,
|
|
727
|
+
since: failing.since,
|
|
728
|
+
attempts: failing.attempts,
|
|
729
|
+
error: message,
|
|
730
|
+
record: record.id,
|
|
731
|
+
},
|
|
732
|
+
})
|
|
733
|
+
) {
|
|
734
|
+
this.state = { ...this.state, failing: { ...failing, reported: true } }
|
|
735
|
+
write = true
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (write || this.mode === 'once') await this.persist()
|
|
739
|
+
}
|
|
740
|
+
}
|