Open History to see the last commit
1/**
2 * Bound offline-oracle observation and exhaust test-owned cleanup.
3 *
4 * A checkpoint timeout says that an expected event was not observed; it does
5 * not cancel the underlying operation. Cleanup therefore tries every action.
6 * If the scenario already has a primary failure, cleanup failures are reported
7 * without replacing it. Otherwise they form one AggregateError after all
8 * resources have had a release attempt.
9 */
10export async function atOracleCheckpoint<T>(
11 promise: Promise<T>,
12 label: string,
13 timeout = 1000,
14): Promise<T> {
15 let timer: ReturnType<typeof setTimeout> | undefined
16 try {
17 return await Promise.race([
18 promise,
19 new Promise<never>((_resolve, reject) => {
20 timer = setTimeout(
21 () =>
22 reject(new Error(`Offline oracle checkpoint timed out: ${label}`)),
23 timeout,
24 )
25 }),
26 ])
27 } finally {
28 clearTimeout(timer)
29 }
30}
31
32/**
33 * Record unhandled process rejections until `cleanup` runs. Call `cleanup` in
34 * a `finally` block.
35 */
36export function captureUnhandledRejections(): {
37 rejections: Array<unknown>
38 cleanup: () => void
39} {
40 const rejections: Array<unknown> = []
41 const onUnhandled = (reason: unknown) => rejections.push(reason)
42 process.on(`unhandledRejection`, onUnhandled)
43 return {
44 rejections,
45 cleanup: () => {
46 process.off(`unhandledRejection`, onUnhandled)
47 },
48 }
49}
50
51export async function cleanupOfflineOracle(
52 actions: Array<() => void | Promise<unknown>>,
53 hasPrimaryFailure: boolean,
54): Promise<void> {
55 const failures: Array<unknown> = []
56 for (const [index, action] of actions.entries()) {
57 try {
58 await atOracleCheckpoint(
59 Promise.resolve().then(action),
60 `cleanup stage ${index}`,
61 250,
62 )
63 } catch (error) {
64 failures.push(error)
65 }
66 }
67 if (failures.length > 0) {
68 if (hasPrimaryFailure)
69 console.warn(
70 `Offline oracle cleanup failed after the primary failure:`,
71 failures,
72 )
73 else throw new AggregateError(failures, `Offline oracle cleanup failed`)
74 }
75}