|
| 1 | +import { identityKey, type PlanIdentity } from './identity.ts'; |
| 2 | +import { prepareSuggestions, type AuthorInput, type AuthorProvider } from './planning-author.ts'; |
| 3 | +import type { Diagnostic, EditReply, Plan } from './plan.ts'; |
| 4 | + |
| 5 | +/** Implemented by the existing Store. No SQL or second persistence writer in core. */ |
| 6 | +export interface SuggestionStore { |
| 7 | + getPlan(identity: PlanIdentity): Plan; |
| 8 | + getSnapshot(identity: PlanIdentity): { id: string; base: string; head: string }; |
| 9 | + beginSuggestions(identity: PlanIdentity, expected: { revision: number; snapshotId: string }): string; |
| 10 | + completeSuggestions(identity: PlanIdentity, id: string, reply: unknown): void; |
| 11 | + settleSuggestion(identity: PlanIdentity, id: string, expected: { revision: number; snapshotId: string }, outcome: { state: 'failed' | 'cancelled' | 'invalidated'; reason: string }): boolean; |
| 12 | + getSuggestions(identity: PlanIdentity, id: string): { state: string; revision: number; snapshotId: string | null; reply: EditReply | null; reason: string | null }; |
| 13 | +} |
| 14 | +export type SuggestionInput = Omit<AuthorInput, 'requestId' | 'previousPlan'> & { snapshotId: string }; |
| 15 | +export type SuggestionOutcome = |
| 16 | + | { state: 'completed'; id: string; warnings: Diagnostic[] } |
| 17 | + | { state: 'failed' | 'cancelled' | 'stale'; id: string; reason: string }; |
| 18 | +export interface SuggestionHandle { |
| 19 | + readonly id: string; |
| 20 | + readonly result: Promise<SuggestionOutcome>; |
| 21 | + cancel(reason?: string): void; |
| 22 | +} |
| 23 | +interface Active { |
| 24 | + handle: SuggestionHandle; |
| 25 | + stop: (state: 'failed' | 'cancelled', reason: string) => void; |
| 26 | +} |
| 27 | +type TerminalOutcome = Extract<SuggestionOutcome, { reason: string }>; |
| 28 | +function persistentReason(reason: string): string { |
| 29 | + return (reason.trim() || 'Suggestion invocation ended without a reason.').slice(0, 4000); |
| 30 | +} |
| 31 | +function retainDiagnostic(reason: string | null, diagnostic: string): string { |
| 32 | + return reason && reason !== diagnostic ? `${reason} ${diagnostic}` : diagnostic; |
| 33 | +} |
| 34 | + |
| 35 | +/** One instance per runner. Close it before closing Store. Not a cross-process scheduler. */ |
| 36 | +export class SuggestionCoordinator { |
| 37 | + #store: SuggestionStore; |
| 38 | + #provider: AuthorProvider; |
| 39 | + #active = new Map<string, Active>(); |
| 40 | + #closing = false; |
| 41 | + #closePromise?: Promise<void>; |
| 42 | + #timeoutMs: number; |
| 43 | + constructor(store: SuggestionStore, provider: AuthorProvider, timeoutMs = 120_000) { |
| 44 | + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) |
| 45 | + throw new Error('Suggestion timeout must fit a positive timer interval.'); |
| 46 | + this.#store = store; this.#provider = provider; this.#timeoutMs = timeoutMs; |
| 47 | + } |
| 48 | + start(input: SuggestionInput): SuggestionHandle { |
| 49 | + if (this.#closing) throw new Error('Suggestion coordinator is closing.'); |
| 50 | + const identity = { ...input.context.identity }, key = identityKey(identity); |
| 51 | + if (this.#active.has(key)) throw new Error('A suggestion invocation is still active for this plan.'); |
| 52 | + const snapshotId = input.snapshotId; |
| 53 | + const previousPlan = this.#store.getPlan(identity), snapshot = this.#store.getSnapshot(identity); |
| 54 | + if (previousPlan.revision !== input.revision) throw new Error('Stale plan revision.'); |
| 55 | + if (snapshot.id !== snapshotId || snapshot.base !== input.repo.baseSha) throw new Error('Stale repository snapshot.'); |
| 56 | + // Validate before allocating a durable request; no await permits local state changes. |
| 57 | + const prepared = prepareSuggestions({ ...input, requestId: 'pending', previousPlan }); |
| 58 | + const expected = Object.freeze({ revision: input.revision, snapshotId }); |
| 59 | + const id = this.#store.beginSuggestions(identity, expected); |
| 60 | + const request = Object.freeze({ ...prepared.request, requestId: id }); |
| 61 | + const controller = new AbortController(); |
| 62 | + let stopped: Omit<TerminalOutcome, 'id'> | undefined; |
| 63 | + const cancellation = () => stopped; |
| 64 | + let settled = false; |
| 65 | + const reconcile = (outcome: TerminalOutcome): TerminalOutcome => { |
| 66 | + const current = this.#store.getSuggestions(identity, id); |
| 67 | + if (current.state === 'cancelled') return { id, state: 'cancelled', reason: retainDiagnostic(current.reason, outcome.reason) }; |
| 68 | + if (current.state === 'invalidated') return { id, state: 'stale', reason: retainDiagnostic(current.reason, outcome.reason) }; |
| 69 | + if (current.state === 'failed') return { id, state: 'failed', reason: retainDiagnostic(current.reason, outcome.reason) }; |
| 70 | + if (this.#store.getPlan(identity).revision !== expected.revision || this.#store.getSnapshot(identity).id !== expected.snapshotId) |
| 71 | + return { id, state: 'stale', reason: retainDiagnostic(current.reason, outcome.reason) }; |
| 72 | + return outcome; |
| 73 | + }; |
| 74 | + const stop = (state: 'failed' | 'cancelled', reason: string) => { |
| 75 | + if (stopped || settled) return; |
| 76 | + stopped = { state, reason }; |
| 77 | + // Even if storage fails, deliver cancellation to the invocation and retain its slot. |
| 78 | + try { |
| 79 | + if (!this.#store.settleSuggestion(identity, id, expected, { state, reason: persistentReason(reason) })) { |
| 80 | + const reconciled = reconcile({ id, state, reason }); |
| 81 | + stopped = { state: reconciled.state, reason: reconciled.reason }; |
| 82 | + } |
| 83 | + } |
| 84 | + catch (error) { stopped.reason += ` Request cleanup failed: ${String(error)}`; } |
| 85 | + finally { controller.abort(new Error(reason)); } |
| 86 | + }; |
| 87 | + const timer = setTimeout(() => stop('failed', 'Suggestion invocation timed out.'), this.#timeoutMs); |
| 88 | + let finish!: (result: SuggestionOutcome) => void; |
| 89 | + const result = new Promise<SuggestionOutcome>(resolve => { finish = resolve; }); |
| 90 | + const handle: SuggestionHandle = Object.freeze({ id, result, |
| 91 | + cancel: (reason = 'Suggestion cancelled by user.') => stop('cancelled', reason) }); |
| 92 | + this.#active.set(key, { handle, stop }); |
| 93 | + // Defer invocation until the handle owns its slot, including synchronous provider errors. |
| 94 | + void Promise.resolve().then(async () => { |
| 95 | + let outcome: SuggestionOutcome; |
| 96 | + try { |
| 97 | + if (stopped) outcome = { id, ...stopped }; |
| 98 | + else { |
| 99 | + const source = await this.#provider.invoke(request, controller.signal); |
| 100 | + const afterInvocation = cancellation(); |
| 101 | + if (afterInvocation) outcome = { id, ...afterInvocation }; |
| 102 | + else { |
| 103 | + const current = this.#store.getSuggestions(identity, id); |
| 104 | + if (this.#store.getPlan(identity).revision !== request.revision || |
| 105 | + this.#store.getSnapshot(identity).id !== snapshot.id || current.state === 'invalidated') { |
| 106 | + outcome = { id, state: 'stale', reason: 'Plan revision or snapshot changed during authoring.' }; |
| 107 | + } else if (current.state !== 'pending') { |
| 108 | + outcome = { id, state: current.state === 'cancelled' ? 'cancelled' : 'stale', reason: `Suggestion request is ${current.state}.` }; |
| 109 | + } else { |
| 110 | + const validated = prepared.validate(source); |
| 111 | + this.#store.completeSuggestions(identity, id, validated.value); |
| 112 | + outcome = { id, state: 'completed', warnings: validated.warnings }; |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + } catch (error) { |
| 117 | + outcome = { id, ...(stopped ?? { state: 'failed' as const, reason: error instanceof Error ? error.message : String(error) }) }; |
| 118 | + // A different Store connection may cancel or advance the revision while |
| 119 | + // the provider runs or before publication CAS. Keep the original error too. |
| 120 | + if (!stopped) { |
| 121 | + try { |
| 122 | + const current = this.#store.getSuggestions(identity, id); |
| 123 | + if (current.state === 'invalidated' || this.#store.getPlan(identity).revision !== request.revision || |
| 124 | + this.#store.getSnapshot(identity).id !== snapshot.id) |
| 125 | + outcome = { id, state: 'stale', reason: `Plan revision or snapshot changed before publication. ${outcome.reason}` }; |
| 126 | + else if (current.state === 'cancelled') |
| 127 | + outcome = { id, state: 'cancelled', reason: `Suggestion request was cancelled before publication. ${outcome.reason}` }; |
| 128 | + } catch { /* Preserve the original error if durable state cannot be read. */ } |
| 129 | + } |
| 130 | + } |
| 131 | + if (outcome.state !== 'completed') { |
| 132 | + const terminal = outcome.state === 'stale' ? 'invalidated' : outcome.state; |
| 133 | + try { |
| 134 | + if (!this.#store.settleSuggestion(identity, id, expected, { state: terminal, reason: persistentReason(outcome.reason) })) |
| 135 | + outcome = reconcile(outcome); |
| 136 | + } |
| 137 | + catch (error) { |
| 138 | + // Keep the original provider/timeout reason, but surface cleanup failure too. |
| 139 | + outcome = { ...outcome, reason: `${outcome.reason} Request cleanup failed: ${String(error)}` }; |
| 140 | + } |
| 141 | + } |
| 142 | + clearTimeout(timer); |
| 143 | + settled = true; |
| 144 | + this.#active.delete(key); |
| 145 | + finish(outcome); |
| 146 | + }); |
| 147 | + return handle; |
| 148 | + } |
| 149 | + close(): Promise<void> { |
| 150 | + if (this.#closePromise) return this.#closePromise; |
| 151 | + this.#closing = true; |
| 152 | + const active = [...this.#active.values()]; |
| 153 | + this.#closePromise = Promise.all(active.map(job => job.handle.result)).then(() => undefined); |
| 154 | + for (const job of active) job.stop('cancelled', 'Suggestion coordinator is closing.'); |
| 155 | + return this.#closePromise; |
| 156 | + } |
| 157 | +} |
0 commit comments