|
| 1 | +import { OneCLIRequestError } from "../errors.js"; |
| 2 | +import type { ApprovalRequest, ManualApprovalCallback } from "./types.js"; |
| 3 | + |
| 4 | +/** Internal response shape from the gateway long-poll endpoint. */ |
| 5 | +interface PollResponse { |
| 6 | + requests: ApprovalRequest[]; |
| 7 | + timeoutSeconds: number; |
| 8 | +} |
| 9 | + |
| 10 | +export class ApprovalClient { |
| 11 | + private baseUrl: string; |
| 12 | + private apiKey: string; |
| 13 | + private gatewayUrl: string | null; |
| 14 | + private running = false; |
| 15 | + private abortController: AbortController | null = null; |
| 16 | + |
| 17 | + /** |
| 18 | + * Tracks approval IDs currently being processed by a callback. |
| 19 | + * Prevents duplicate callback invocations for the same request |
| 20 | + * when the poll returns it again before the decision is submitted. |
| 21 | + */ |
| 22 | + private inFlight = new Set<string>(); |
| 23 | + |
| 24 | + constructor(baseUrl: string, apiKey: string, gatewayUrl: string | null) { |
| 25 | + this.baseUrl = baseUrl.replace(/\/+$/, ""); |
| 26 | + this.apiKey = apiKey; |
| 27 | + this.gatewayUrl = gatewayUrl; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Resolve the gateway URL from the web app. |
| 32 | + * Called once on first poll, then cached. |
| 33 | + */ |
| 34 | + private async resolveGatewayUrl(): Promise<string> { |
| 35 | + if (this.gatewayUrl) return this.gatewayUrl; |
| 36 | + |
| 37 | + const url = `${this.baseUrl}/api/gateway-url`; |
| 38 | + const res = await fetch(url, { |
| 39 | + headers: { Authorization: `Bearer ${this.apiKey}` }, |
| 40 | + signal: AbortSignal.timeout(5000), |
| 41 | + }); |
| 42 | + |
| 43 | + if (!res.ok) { |
| 44 | + throw new OneCLIRequestError("Failed to resolve gateway URL", { |
| 45 | + url, |
| 46 | + statusCode: res.status, |
| 47 | + }); |
| 48 | + } |
| 49 | + |
| 50 | + const data = (await res.json()) as { url: string }; |
| 51 | + this.gatewayUrl = data.url.replace(/\/+$/, ""); |
| 52 | + return this.gatewayUrl; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Start the long-polling loop. Runs until stop() is called. |
| 57 | + * |
| 58 | + * Dispatches callbacks concurrently — multiple approvals are handled |
| 59 | + * in parallel without blocking each other or the polling loop. |
| 60 | + * Each approval ID is tracked in `inFlight` to prevent duplicate |
| 61 | + * callback invocations. On failure (callback throws or decision |
| 62 | + * submission fails), the ID is removed from `inFlight` and the |
| 63 | + * approval will be retried on the next poll cycle. |
| 64 | + */ |
| 65 | + async start(callback: ManualApprovalCallback): Promise<void> { |
| 66 | + this.running = true; |
| 67 | + const gatewayUrl = await this.resolveGatewayUrl(); |
| 68 | + |
| 69 | + while (this.running) { |
| 70 | + try { |
| 71 | + const poll = await this.poll(gatewayUrl); |
| 72 | + |
| 73 | + for (const request of poll.requests) { |
| 74 | + this.inFlight.add(request.id); |
| 75 | + request.timeoutSeconds = poll.timeoutSeconds; |
| 76 | + |
| 77 | + this.handleRequest(gatewayUrl, request, callback); |
| 78 | + } |
| 79 | + } catch { |
| 80 | + if (!this.running) return; |
| 81 | + await this.sleep(5000); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Process a single approval: call the callback, submit the decision. |
| 88 | + * Runs independently — multiple calls execute concurrently. |
| 89 | + * On any failure, removes from inFlight so the next poll retries. |
| 90 | + */ |
| 91 | + private handleRequest( |
| 92 | + gatewayUrl: string, |
| 93 | + request: ApprovalRequest, |
| 94 | + callback: ManualApprovalCallback, |
| 95 | + ): void { |
| 96 | + (async () => { |
| 97 | + try { |
| 98 | + const decision = await callback(request); |
| 99 | + await this.submitDecision(gatewayUrl, request.id, decision); |
| 100 | + } finally { |
| 101 | + this.inFlight.delete(request.id); |
| 102 | + } |
| 103 | + })().catch(() => { |
| 104 | + this.inFlight.delete(request.id); |
| 105 | + }); |
| 106 | + } |
| 107 | + |
| 108 | + /** Stop the polling loop and abort any in-flight poll request. */ |
| 109 | + stop(): void { |
| 110 | + this.running = false; |
| 111 | + this.abortController?.abort(); |
| 112 | + } |
| 113 | + |
| 114 | + /** |
| 115 | + * Long-poll the gateway for pending approvals. |
| 116 | + * Server holds up to 30s; we set a 35s client timeout. |
| 117 | + */ |
| 118 | + private async poll(gatewayUrl: string): Promise<PollResponse> { |
| 119 | + this.abortController = new AbortController(); |
| 120 | + |
| 121 | + let url = `${gatewayUrl}/api/approvals/pending`; |
| 122 | + if (this.inFlight.size > 0) { |
| 123 | + const exclude = [...this.inFlight].join(","); |
| 124 | + url += `?exclude=${encodeURIComponent(exclude)}`; |
| 125 | + } |
| 126 | + const res = await fetch(url, { |
| 127 | + headers: { Authorization: `Bearer ${this.apiKey}` }, |
| 128 | + signal: AbortSignal.any([ |
| 129 | + this.abortController.signal, |
| 130 | + AbortSignal.timeout(35_000), |
| 131 | + ]), |
| 132 | + }); |
| 133 | + |
| 134 | + if (!res.ok) { |
| 135 | + throw new OneCLIRequestError("Approval poll failed", { |
| 136 | + url, |
| 137 | + statusCode: res.status, |
| 138 | + }); |
| 139 | + } |
| 140 | + |
| 141 | + return (await res.json()) as PollResponse; |
| 142 | + } |
| 143 | + |
| 144 | + /** Submit a decision for a single approval request. */ |
| 145 | + private async submitDecision( |
| 146 | + gatewayUrl: string, |
| 147 | + id: string, |
| 148 | + decision: string, |
| 149 | + ): Promise<void> { |
| 150 | + const url = `${gatewayUrl}/api/approvals/${encodeURIComponent(id)}/decision`; |
| 151 | + |
| 152 | + const res = await fetch(url, { |
| 153 | + method: "POST", |
| 154 | + headers: { |
| 155 | + "Content-Type": "application/json", |
| 156 | + Authorization: `Bearer ${this.apiKey}`, |
| 157 | + }, |
| 158 | + body: JSON.stringify({ decision }), |
| 159 | + signal: AbortSignal.timeout(5000), |
| 160 | + }); |
| 161 | + |
| 162 | + if (!res.ok && res.status !== 410) { |
| 163 | + throw new OneCLIRequestError("Decision submission failed", { |
| 164 | + url, |
| 165 | + statusCode: res.status, |
| 166 | + }); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + private sleep(ms: number): Promise<void> { |
| 171 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 172 | + } |
| 173 | +} |
0 commit comments