summaryrefslogtreecommitdiff
path: root/packages/backend/src/misc/promise-tracker.ts
blob: 76b4dd810c301b24e6b3a19283a0a44e782122b2 (plain)
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
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

const promiseRefs: Set<WeakRef<Promise<unknown>>> = new Set();

export function trackTask(task: () => Promise<unknown>): void {
	trackPromise(task());
}

/**
 * This tracks promises that other modules decided not to wait for,
 * and makes sure they are all settled before fully closing down the server.
 */
export function trackPromise(promise: Promise<unknown>) {
	if (process.env.NODE_ENV !== 'test') {
		return;
	}
	const ref = new WeakRef(promise);
	promiseRefs.add(ref);
	promise.finally(() => promiseRefs.delete(ref));
}

export async function allSettled(): Promise<void> {
	await Promise.allSettled([...promiseRefs].map(r => r.deref()));
}