-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpolling.ts
More file actions
211 lines (192 loc) · 6.2 KB
/
polling.ts
File metadata and controls
211 lines (192 loc) · 6.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
* Generic Polling Utility
*
* Provides a reusable polling mechanism with progress spinner display.
* Used by commands that need to wait for async operations to complete.
*/
import { TimeoutError } from "./errors.js";
import {
formatProgressLine,
truncateProgressMessage,
} from "./formatters/seer.js";
/** Default polling interval in milliseconds */
const DEFAULT_POLL_INTERVAL_MS = 1000;
/** Animation interval for spinner updates — 50ms gives 20fps, matching the ora/inquirer standard */
const ANIMATION_INTERVAL_MS = 50;
/** Default timeout in milliseconds (6 minutes) */
const DEFAULT_TIMEOUT_MS = 360_000;
/**
* Options for the generic poll function.
*/
export type PollOptions<T> = {
/** Function to fetch current state */
fetchState: () => Promise<T | null>;
/** Predicate to determine if polling should stop */
shouldStop: (state: T) => boolean;
/** Get progress message from state */
getProgressMessage: (state: T) => string;
/** Suppress progress output (JSON mode) */
json?: boolean;
/** Poll interval in ms (default: 1000) */
pollIntervalMs?: number;
/** Timeout in ms (default: 360000 / 6 min) */
timeoutMs?: number;
/** Custom timeout message */
timeoutMessage?: string;
/** Actionable hint appended to the TimeoutError (e.g., "Run the command again…") */
timeoutHint?: string;
/** Initial progress message */
initialMessage?: string;
};
/**
* Generic polling function with animated progress display.
*
* Polls the fetchState function until shouldStop returns true or timeout is reached.
* Displays an animated spinner with progress messages when not in JSON mode.
* Animation runs at 50ms intervals (20fps) independently of polling frequency.
*
* @typeParam T - The type of state being polled
* @param options - Polling configuration
* @returns The final state when shouldStop returns true
* @throws {TimeoutError} When timeout is reached before shouldStop returns true
*
* @example
* ```typescript
* const finalState = await poll({
* fetchState: () => getAutofixState(org, issueId),
* shouldStop: (state) => isTerminalStatus(state.status),
* getProgressMessage: (state) => state.message ?? "Processing...",
* json: false,
* timeoutMs: 360_000,
* timeoutMessage: "Operation timed out after 6 minutes.",
* });
* ```
*/
export async function poll<T>(options: PollOptions<T>): Promise<T> {
const {
fetchState,
shouldStop,
getProgressMessage,
json = false,
pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
timeoutMs = DEFAULT_TIMEOUT_MS,
timeoutMessage = "Operation timed out after 6 minutes. Try again or check the Sentry web UI.",
timeoutHint,
initialMessage = "Waiting for operation to start...",
} = options;
const startTime = Date.now();
const spinner = json ? null : startSpinner(initialMessage);
try {
while (Date.now() - startTime < timeoutMs) {
const state = await fetchState();
if (state) {
// Always call getProgressMessage (callers may rely on the callback
// being invoked), but only forward the result to the spinner.
const msg = getProgressMessage(state);
spinner?.setMessage(msg);
if (shouldStop(state)) {
return state;
}
}
await Bun.sleep(pollIntervalMs);
}
throw new TimeoutError(timeoutMessage, timeoutHint);
} finally {
spinner?.stop();
if (!json) {
process.stderr.write("\n");
}
}
}
/**
* Start an animated spinner that writes progress to stderr.
*
* Returns a controller with `setMessage` to update the displayed text
* and `stop` to halt the animation. Writes directly to `process.stderr`.
*/
function startSpinner(initialMessage: string): {
setMessage: (msg: string) => void;
stop: () => void;
} {
let currentMessage = initialMessage;
let tick = 0;
let stopped = false;
const scheduleFrame = () => {
if (stopped) {
return;
}
const display = truncateProgressMessage(currentMessage);
process.stderr.write(`\r\x1b[K${formatProgressLine(display, tick)}`);
tick += 1;
setTimeout(scheduleFrame, ANIMATION_INTERVAL_MS).unref();
};
scheduleFrame();
return {
setMessage: (msg: string) => {
currentMessage = msg;
},
stop: () => {
stopped = true;
},
};
}
/**
* Options for {@link withProgress}.
*/
export type WithProgressOptions = {
/** Initial spinner message */
message: string;
/** Suppress progress output (JSON mode). When true, the operation runs
* without a spinner — matching the behaviour of {@link poll}. */
json?: boolean;
};
/**
* Run an async operation with an animated spinner on stderr.
*
* The spinner uses the same braille frames as the Seer polling spinner,
* giving a consistent look across all CLI commands. Progress output goes
* to stderr, so it never contaminates stdout (safe to use alongside JSON output).
*
* When `options.json` is true the spinner is suppressed entirely, matching
* the behaviour of {@link poll}. This avoids noisy ANSI escape sequences on
* stderr when agents or CI pipelines consume `--json` output.
*
* The callback receives a `setMessage` function to update the displayed
* message as work progresses (e.g. to show page counts during pagination).
* Progress is automatically cleared when the operation completes.
*
* @param options - Spinner configuration
* @param fn - Async operation to run; receives `setMessage` to update the displayed text
* @returns The value returned by `fn`
*
* @example
* ```typescript
* const result = await withProgress(
* { message: "Fetching issues..." },
* async (setMessage) => {
* const data = await fetchWithPages({
* onPage: (fetched, total) => setMessage(`Fetching issues... ${fetched}/${total}`),
* });
* return data;
* }
* );
* ```
*/
export async function withProgress<T>(
options: WithProgressOptions,
fn: (setMessage: (msg: string) => void) => Promise<T>
): Promise<T> {
if (options.json) {
// JSON mode: skip the spinner entirely, pass a no-op setMessage
return fn(() => {
/* spinner suppressed in JSON mode */
});
}
const spinner = startSpinner(options.message);
try {
return await fn(spinner.setMessage);
} finally {
spinner.stop();
process.stderr.write("\r\x1b[K");
}
}