|
| 1 | +import { NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE } from "../infra/node-commands.js"; |
| 2 | +import { |
| 3 | + NodeWorkerLaunchStore, |
| 4 | + type NodeWorkerLaunchClaim, |
| 5 | + type NodeWorkerLaunchClaimResult, |
| 6 | + type NodeWorkerLaunchReceipt, |
| 7 | +} from "./node-worker-launch-store.js"; |
| 8 | +import { |
| 9 | + inspectNodeWorkerProcessIdentity, |
| 10 | + type NodeWorkerProcessIdentity, |
| 11 | +} from "./node-worker-process-identity.js"; |
| 12 | + |
| 13 | +const DEFAULT_WORKER_CAPACITY = 2; |
| 14 | +const DEFAULT_CAPACITY_WAIT_MS = 10_000; |
| 15 | +const CAPACITY_POLL_MS = 100; |
| 16 | + |
| 17 | +type NodeWorkerCapacityOptions = { |
| 18 | + capacity?: number; |
| 19 | + capacityWaitMs?: number; |
| 20 | + onAvailabilityChanged?: (available: boolean) => void; |
| 21 | +}; |
| 22 | + |
| 23 | +function capacityAbortReason(signal: AbortSignal): Error { |
| 24 | + return signal.reason instanceof Error |
| 25 | + ? signal.reason |
| 26 | + : new Error("node worker admission aborted"); |
| 27 | +} |
| 28 | + |
| 29 | +export class NodeWorkerCapacityExhaustedError extends Error { |
| 30 | + readonly code = NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE; |
| 31 | + |
| 32 | + constructor(waitMs: number) { |
| 33 | + super(`node worker capacity remained full for ${waitMs} ms`); |
| 34 | + this.name = "NodeWorkerCapacityExhaustedError"; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/** Owns durable worker slot admission and live full/free publication edges. */ |
| 39 | +export class NodeWorkerCapacity { |
| 40 | + private readonly capacity: number; |
| 41 | + private readonly waitMs: number; |
| 42 | + private readonly onAvailabilityChanged?: (available: boolean) => void; |
| 43 | + private readonly waiters = new Set<() => void>(); |
| 44 | + private readonly closeAbort = new AbortController(); |
| 45 | + private availability?: boolean; |
| 46 | + |
| 47 | + constructor( |
| 48 | + private readonly store: NodeWorkerLaunchStore, |
| 49 | + options: NodeWorkerCapacityOptions = {}, |
| 50 | + ) { |
| 51 | + this.capacity = options.capacity ?? DEFAULT_WORKER_CAPACITY; |
| 52 | + this.waitMs = options.capacityWaitMs ?? DEFAULT_CAPACITY_WAIT_MS; |
| 53 | + this.onAvailabilityChanged = options.onAvailabilityChanged; |
| 54 | + if (!Number.isSafeInteger(this.capacity) || this.capacity < 1) { |
| 55 | + throw new Error("node worker capacity must be a positive safe integer"); |
| 56 | + } |
| 57 | + if (!Number.isSafeInteger(this.waitMs) || this.waitMs < 0) { |
| 58 | + throw new Error("node worker capacity wait must be a non-negative safe integer"); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + async initialize( |
| 63 | + recoverRunning: (receipt: NodeWorkerLaunchReceipt) => Promise<void>, |
| 64 | + ): Promise<void> { |
| 65 | + this.publish(false); |
| 66 | + for (const receipt of this.store.listNonterminal()) { |
| 67 | + if (receipt.state === "pending") { |
| 68 | + const supervisorState = inspectNodeWorkerProcessIdentity(receipt.supervisor); |
| 69 | + if (supervisorState === "dead" || supervisorState === "reused") { |
| 70 | + this.finish( |
| 71 | + { |
| 72 | + launchId: receipt.launchId, |
| 73 | + planHash: receipt.planHash, |
| 74 | + supervisor: receipt.supervisor, |
| 75 | + worker: null, |
| 76 | + state: "interrupted", |
| 77 | + errorText: "node host stopped before the worker launch started", |
| 78 | + }, |
| 79 | + false, |
| 80 | + ); |
| 81 | + } |
| 82 | + continue; |
| 83 | + } |
| 84 | + await recoverRunning(receipt); |
| 85 | + } |
| 86 | + this.refresh(); |
| 87 | + } |
| 88 | + |
| 89 | + async claim( |
| 90 | + claim: NodeWorkerLaunchClaim, |
| 91 | + supervisor: NodeWorkerProcessIdentity, |
| 92 | + signal?: AbortSignal, |
| 93 | + ): Promise<Exclude<NodeWorkerLaunchClaimResult, { action: "at-capacity" }>> { |
| 94 | + const deadlineMs = Date.now() + this.waitMs; |
| 95 | + while (true) { |
| 96 | + if (this.closeAbort.signal.aborted) { |
| 97 | + throw new Error("node worker supervisor is closed"); |
| 98 | + } |
| 99 | + signal?.throwIfAborted(); |
| 100 | + const result = this.store.claim(claim, supervisor, this.capacity); |
| 101 | + this.publish(result.nonterminalCount < this.capacity); |
| 102 | + if (result.action !== "at-capacity") { |
| 103 | + return result; |
| 104 | + } |
| 105 | + await this.wait(deadlineMs, signal); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + finish( |
| 110 | + params: Parameters<NodeWorkerLaunchStore["finish"]>[0], |
| 111 | + notify = true, |
| 112 | + ): NodeWorkerLaunchReceipt { |
| 113 | + const receipt = this.store.finish(params); |
| 114 | + if (notify && receipt.state !== "pending" && receipt.state !== "running") { |
| 115 | + this.changed(); |
| 116 | + } |
| 117 | + return receipt; |
| 118 | + } |
| 119 | + |
| 120 | + finishCancelled( |
| 121 | + params: Parameters<NodeWorkerLaunchStore["finishCancelled"]>[0], |
| 122 | + ): NodeWorkerLaunchReceipt | undefined { |
| 123 | + const receipt = this.store.finishCancelled(params); |
| 124 | + if (receipt && receipt.state !== "pending" && receipt.state !== "running") { |
| 125 | + this.changed(); |
| 126 | + } |
| 127 | + return receipt; |
| 128 | + } |
| 129 | + |
| 130 | + close(): void { |
| 131 | + this.closeAbort.abort(); |
| 132 | + this.wake(); |
| 133 | + } |
| 134 | + |
| 135 | + private publish(available: boolean): void { |
| 136 | + if (this.availability === available) { |
| 137 | + return; |
| 138 | + } |
| 139 | + this.availability = available; |
| 140 | + this.onAvailabilityChanged?.(available); |
| 141 | + } |
| 142 | + |
| 143 | + private refresh(): void { |
| 144 | + const count = this.store.nonterminalCount(); |
| 145 | + this.publish(count < this.capacity); |
| 146 | + if (count < this.capacity) { |
| 147 | + this.wake(); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + private changed(): void { |
| 152 | + this.wake(); |
| 153 | + try { |
| 154 | + this.refresh(); |
| 155 | + } catch { |
| 156 | + this.publish(false); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + private wake(): void { |
| 161 | + for (const wake of this.waiters) { |
| 162 | + wake(); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + private async wait(deadlineMs: number, signal?: AbortSignal): Promise<void> { |
| 167 | + const remainingMs = deadlineMs - Date.now(); |
| 168 | + if (remainingMs <= 0) { |
| 169 | + throw new NodeWorkerCapacityExhaustedError(this.waitMs); |
| 170 | + } |
| 171 | + if (signal?.aborted) { |
| 172 | + throw capacityAbortReason(signal); |
| 173 | + } |
| 174 | + if (this.closeAbort.signal.aborted) { |
| 175 | + throw new Error("node worker supervisor is closed"); |
| 176 | + } |
| 177 | + await new Promise<void>((resolve, reject) => { |
| 178 | + const finish = (operation: () => void) => { |
| 179 | + clearTimeout(pollTimer); |
| 180 | + this.waiters.delete(wake); |
| 181 | + signal?.removeEventListener("abort", onAbort); |
| 182 | + this.closeAbort.signal.removeEventListener("abort", onClose); |
| 183 | + operation(); |
| 184 | + }; |
| 185 | + const wake = () => finish(resolve); |
| 186 | + const onAbort = () => |
| 187 | + finish(() => |
| 188 | + reject(signal ? capacityAbortReason(signal) : new Error("node worker admission aborted")), |
| 189 | + ); |
| 190 | + const onClose = () => finish(() => reject(new Error("node worker supervisor is closed"))); |
| 191 | + const pollTimer = setTimeout(wake, Math.min(CAPACITY_POLL_MS, remainingMs)); |
| 192 | + pollTimer.unref?.(); |
| 193 | + this.waiters.add(wake); |
| 194 | + signal?.addEventListener("abort", onAbort, { once: true }); |
| 195 | + this.closeAbort.signal.addEventListener("abort", onClose, { once: true }); |
| 196 | + }); |
| 197 | + } |
| 198 | +} |
0 commit comments