|
| 1 | +import { Runloop } from '../index'; |
| 2 | +import { Stream } from '../streaming'; |
| 3 | +import type { DevboxEvictionEventView } from '../resources/devboxes/devboxes'; |
| 4 | +import type { Devbox } from './devbox'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Invoked once when the devbox it was registered for has a pending eviction. |
| 8 | + * |
| 9 | + * @param devbox - The devbox with a pending eviction. |
| 10 | + * @param evictionDeadlineMs - Unix timestamp (ms) by which the devbox will be suspended. |
| 11 | + */ |
| 12 | +export type EvictionCallback = (devbox: Devbox, evictionDeadlineMs: number) => void; |
| 13 | + |
| 14 | +/** |
| 15 | + * Fans account-wide eviction notifications out to per-devbox callbacks. |
| 16 | + * |
| 17 | + * One monitor is shared by every {@link Devbox} built from the same generated |
| 18 | + * client (see {@link getEvictionMonitor}), so all registered devboxes are served |
| 19 | + * by a single SSE connection. The stream opens the moment the first devbox |
| 20 | + * registers interest and closes as soon as the last interested devbox has been |
| 21 | + * notified. |
| 22 | + * |
| 23 | + * Delivery contract: |
| 24 | + * - The server replays every currently-pending eviction on connect, so a devbox |
| 25 | + * that registers after its eviction was scheduled is still notified. |
| 26 | + * - Notifications for devboxes not in the interest set are discarded. |
| 27 | + * - A devbox is removed from the interest set *before* its callback runs, so the |
| 28 | + * callback fires at most once even if the server repeats the notification. |
| 29 | + */ |
| 30 | +export class EvictionMonitor { |
| 31 | + private entries = new Map<string, { devbox: Devbox; callback: EvictionCallback }>(); |
| 32 | + private stream: Stream<DevboxEvictionEventView> | null = null; |
| 33 | + private running = false; |
| 34 | + |
| 35 | + constructor(private client: Runloop) {} |
| 36 | + |
| 37 | + /** Add `devbox` to the interest set, opening the stream if idle. */ |
| 38 | + register(devbox: Devbox, callback: EvictionCallback): void { |
| 39 | + this.entries.set(devbox.id, { devbox, callback }); |
| 40 | + if (!this.running) { |
| 41 | + this.running = true; |
| 42 | + void this.run(); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /** Drop `devboxId`; close the stream if it was the last interested devbox. */ |
| 47 | + unregister(devboxId: string): void { |
| 48 | + this.entries.delete(devboxId); |
| 49 | + if (this.entries.size === 0) { |
| 50 | + this.close(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** Clear all interest and tear down the stream. */ |
| 55 | + close(): void { |
| 56 | + this.entries.clear(); |
| 57 | + this.stream?.controller.abort(); |
| 58 | + this.stream = null; |
| 59 | + this.running = false; |
| 60 | + } |
| 61 | + |
| 62 | + private async run(): Promise<void> { |
| 63 | + // The server force-closes the stream on purpose (leader change / slow consumer) and a |
| 64 | + // long-lived HTTP/2 stream can drop; the client is expected to reconnect and re-read the |
| 65 | + // snapshot, which re-delivers anything missed. So reconnect (with backoff) until no devbox is |
| 66 | + // still interested. |
| 67 | + const INITIAL_BACKOFF_MS = 500; |
| 68 | + const MAX_BACKOFF_MS = 30_000; |
| 69 | + let backoff = INITIAL_BACKOFF_MS; |
| 70 | + try { |
| 71 | + while (this.entries.size > 0) { |
| 72 | + try { |
| 73 | + // Force the SSE Accept header: the endpoint only streams for text/event-stream; the |
| 74 | + // generated client's default (application/json) gets an empty text/plain response, so the |
| 75 | + // feed would silently deliver nothing. |
| 76 | + const stream = await this.client.devboxes.watchEvictions({ |
| 77 | + headers: { Accept: 'text/event-stream' }, |
| 78 | + }); |
| 79 | + this.stream = stream; |
| 80 | + for await (const event of stream) { |
| 81 | + this.dispatch(event); |
| 82 | + if (this.entries.size === 0) return; |
| 83 | + } |
| 84 | + // Clean end: reset backoff and reconnect if still interested. |
| 85 | + backoff = INITIAL_BACKOFF_MS; |
| 86 | + } catch (error) { |
| 87 | + // Aborting the stream on close surfaces as an AbortError; that is an intentional teardown. |
| 88 | + if (error instanceof Error && error.name === 'AbortError') return; |
| 89 | + if (this.entries.size === 0) return; |
| 90 | + // Otherwise a routine disconnect — fall through to backoff + reconnect. |
| 91 | + } |
| 92 | + if (this.entries.size === 0) return; |
| 93 | + await new Promise((resolve) => setTimeout(resolve, backoff)); |
| 94 | + backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); |
| 95 | + } |
| 96 | + } finally { |
| 97 | + this.stream = null; |
| 98 | + this.running = false; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + private dispatch(event: DevboxEvictionEventView): void { |
| 103 | + const entry = this.entries.get(event.devbox_id); |
| 104 | + if (!entry) return; |
| 105 | + // Remove before signaling so a duplicate notification for the same devbox is |
| 106 | + // discarded and the callback fires at most once. |
| 107 | + this.entries.delete(event.devbox_id); |
| 108 | + try { |
| 109 | + entry.callback(entry.devbox, event.eviction_deadline_ms); |
| 110 | + } catch (error) { |
| 111 | + console.error(`Error in eviction callback for devbox ${event.devbox_id}:`, error); |
| 112 | + } |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +const monitors = new WeakMap<Runloop, EvictionMonitor>(); |
| 117 | + |
| 118 | +/** Return the shared {@link EvictionMonitor} for `client`, creating it once. */ |
| 119 | +export function getEvictionMonitor(client: Runloop): EvictionMonitor { |
| 120 | + let monitor = monitors.get(client); |
| 121 | + if (!monitor) { |
| 122 | + monitor = new EvictionMonitor(client); |
| 123 | + monitors.set(client, monitor); |
| 124 | + } |
| 125 | + return monitor; |
| 126 | +} |
0 commit comments