|
| 1 | +import type { Logger } from '../types' |
| 2 | +import { randomUUID } from 'node:crypto' |
| 3 | +import type { TuiLoopRestartAppliedState, TuiLoopRestartRepo } from '../storage' |
| 4 | + |
| 5 | +export interface TuiLoopRestartRequest { |
| 6 | + loopName: string |
| 7 | + auditorModel: string |
| 8 | + auditorVariant: string |
| 9 | +} |
| 10 | + |
| 11 | +export type TuiLoopRestartResult = { sessionId: string } | { error: string } |
| 12 | + |
| 13 | +export interface TuiLoopRestartControllerDeps { |
| 14 | + projectId: string |
| 15 | + repo: TuiLoopRestartRepo |
| 16 | + restart(request: TuiLoopRestartRequest): Promise<TuiLoopRestartResult> |
| 17 | + logger: Logger |
| 18 | + pollIntervalMs?: number |
| 19 | + maxRequestAgeMs?: number |
| 20 | + processingLeaseMs?: number |
| 21 | + processingHeartbeatMs?: number |
| 22 | +} |
| 23 | + |
| 24 | +export interface TuiLoopRestartController { |
| 25 | + start(): Promise<void> |
| 26 | + dispose(): Promise<void> |
| 27 | +} |
| 28 | + |
| 29 | +const DEFAULT_POLL_INTERVAL_MS = 250 |
| 30 | +const DEFAULT_MAX_REQUEST_AGE_MS = 30_000 |
| 31 | +const DEFAULT_PROCESSING_LEASE_MS = 600_000 |
| 32 | +const DEFAULT_PROCESSING_HEARTBEAT_MS = 30_000 |
| 33 | + |
| 34 | +export function createTuiLoopRestartController(deps: TuiLoopRestartControllerDeps): TuiLoopRestartController { |
| 35 | + const pollIntervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS |
| 36 | + const maxRequestAgeMs = deps.maxRequestAgeMs ?? DEFAULT_MAX_REQUEST_AGE_MS |
| 37 | + const processingLeaseMs = deps.processingLeaseMs ?? DEFAULT_PROCESSING_LEASE_MS |
| 38 | + const processingHeartbeatMs = deps.processingHeartbeatMs ?? DEFAULT_PROCESSING_HEARTBEAT_MS |
| 39 | + const ownerId = randomUUID() |
| 40 | + |
| 41 | + let timer: ReturnType<typeof setInterval> | null = null |
| 42 | + let disposed = false |
| 43 | + let disposing = false |
| 44 | + let inFlight: Promise<void> | null = null |
| 45 | + let completed: { revision: string; result: TuiLoopRestartResult; claim: TuiLoopRestartAppliedState } | null = null |
| 46 | + |
| 47 | + const completedState = (revision: string, sessionId: string | null, error: string | null): TuiLoopRestartAppliedState => ({ |
| 48 | + version: 1, |
| 49 | + revision, |
| 50 | + status: 'completed', |
| 51 | + ownerId: null, |
| 52 | + sessionId, |
| 53 | + error, |
| 54 | + appliedAt: Date.now(), |
| 55 | + }) |
| 56 | + |
| 57 | + const processingState = (revision: string): TuiLoopRestartAppliedState => ({ |
| 58 | + version: 1, |
| 59 | + revision, |
| 60 | + status: 'processing', |
| 61 | + ownerId, |
| 62 | + sessionId: null, |
| 63 | + error: null, |
| 64 | + appliedAt: Date.now(), |
| 65 | + }) |
| 66 | + |
| 67 | + const reconcileOnce = async (): Promise<void> => { |
| 68 | + if (disposed || disposing) return |
| 69 | + const { desired, applied } = deps.repo.getPair(deps.projectId) |
| 70 | + if (!desired) return |
| 71 | + |
| 72 | + if (completed?.revision === desired.revision) { |
| 73 | + const pending = completed |
| 74 | + const result = pending.result |
| 75 | + const state = 'sessionId' in result |
| 76 | + ? completedState(desired.revision, result.sessionId, null) |
| 77 | + : completedState(desired.revision, null, result.error) |
| 78 | + deps.repo.compareAndSetApplied(deps.projectId, pending.claim, state) |
| 79 | + completed = null |
| 80 | + return |
| 81 | + } |
| 82 | + completed = null |
| 83 | + if (applied && applied.revision === desired.revision) { |
| 84 | + if (applied.status === 'processing' && Date.now() - applied.appliedAt > processingLeaseMs) { |
| 85 | + deps.repo.compareAndSetApplied( |
| 86 | + deps.projectId, |
| 87 | + applied, |
| 88 | + completedState(desired.revision, null, 'restart outcome is unknown because its controller stopped before acknowledging completion'), |
| 89 | + ) |
| 90 | + } |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + const age = Date.now() - desired.requestedAt |
| 95 | + if (age > maxRequestAgeMs) { |
| 96 | + deps.logger.debug(`[tui-loop-restart] rejecting stale request revision=${desired.revision} age=${age}ms`) |
| 97 | + const claim = processingState(desired.revision) |
| 98 | + if (deps.repo.claim(deps.projectId, claim)) { |
| 99 | + deps.repo.compareAndSetApplied( |
| 100 | + deps.projectId, |
| 101 | + claim, |
| 102 | + completedState(desired.revision, null, 'restart request expired before it could be applied'), |
| 103 | + ) |
| 104 | + } |
| 105 | + return |
| 106 | + } |
| 107 | + |
| 108 | + let claim = processingState(desired.revision) |
| 109 | + const claimed = deps.repo.claim(deps.projectId, claim) |
| 110 | + if (!claimed) return |
| 111 | + |
| 112 | + let result: TuiLoopRestartResult |
| 113 | + const heartbeat = setInterval(() => { |
| 114 | + const next = { ...claim, appliedAt: Date.now() } |
| 115 | + try { |
| 116 | + if (deps.repo.compareAndSetApplied(deps.projectId, claim, next)) claim = next |
| 117 | + } catch (err) { |
| 118 | + deps.logger.error('TUI loop restart heartbeat failed', err) |
| 119 | + } |
| 120 | + }, processingHeartbeatMs) |
| 121 | + try { |
| 122 | + result = await deps.restart({ |
| 123 | + loopName: desired.loopName, |
| 124 | + auditorModel: desired.auditorModel, |
| 125 | + auditorVariant: desired.auditorVariant, |
| 126 | + }) |
| 127 | + } catch (err) { |
| 128 | + result = { error: err instanceof Error ? err.message : String(err) } |
| 129 | + } finally { |
| 130 | + clearInterval(heartbeat) |
| 131 | + } |
| 132 | + if (disposed) return |
| 133 | + |
| 134 | + const current = deps.repo.getDesired(deps.projectId) |
| 135 | + if (!current || current.revision !== desired.revision) return |
| 136 | + |
| 137 | + completed = { revision: desired.revision, result, claim } |
| 138 | + const state = 'sessionId' in result |
| 139 | + ? completedState(desired.revision, result.sessionId, null) |
| 140 | + : completedState(desired.revision, null, result.error) |
| 141 | + if (deps.repo.compareAndSetApplied(deps.projectId, claim, state)) completed = null |
| 142 | + } |
| 143 | + |
| 144 | + const reconcile = (): Promise<void> => { |
| 145 | + if (inFlight) return inFlight |
| 146 | + const run = reconcileOnce() |
| 147 | + .catch((err: unknown) => { |
| 148 | + deps.logger.error(`[tui-loop-restart] reconciliation failed: ${err instanceof Error ? err.message : String(err)}`) |
| 149 | + }) |
| 150 | + .finally(() => { |
| 151 | + if (inFlight === run) inFlight = null |
| 152 | + }) |
| 153 | + inFlight = run |
| 154 | + return run |
| 155 | + } |
| 156 | + |
| 157 | + const start = async (): Promise<void> => { |
| 158 | + if (disposed || disposing) return |
| 159 | + if (!timer) { |
| 160 | + timer = setInterval(() => { void reconcile() }, pollIntervalMs) |
| 161 | + } |
| 162 | + await reconcile() |
| 163 | + } |
| 164 | + |
| 165 | + const dispose = async (): Promise<void> => { |
| 166 | + if (disposed) return |
| 167 | + disposing = true |
| 168 | + if (timer) { |
| 169 | + clearInterval(timer) |
| 170 | + timer = null |
| 171 | + } |
| 172 | + await inFlight |
| 173 | + disposed = true |
| 174 | + } |
| 175 | + |
| 176 | + return { start, dispose } |
| 177 | +} |
0 commit comments