~james/core

core/web/src/lib/migration/status.ts -rw-r--r-- 2.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
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
import type { BobbinContext } from "#lib/api/client.ts";
import { fetchMiniDoc, type MiniDoc } from "#lib/api/identity.ts";

export interface MigrationConfig {
	liarPdsUrl: string;
	liarMock: boolean;
}

const originOf = (url: string): string | null => {
	try {
		return new URL(url).origin;
	} catch {
		return null;
	}
};

export const sameOrigin = (candidate: string | undefined, expectedUrl: string): boolean => {
	const expected = originOf(expectedUrl);
	return expected !== null && candidate !== undefined && originOf(candidate) === expected;
};

// not cached, it has to flip as soon as hydrant unmarks the account
export const migrationPending = async (
	ctx: BobbinContext,
	did: string,
	config: MigrationConfig
): Promise<boolean> => {
	if (!config.liarPdsUrl) return false;
	let doc: MiniDoc = await fetchMiniDoc(ctx, did);
	if (config.liarMock) {
		const { mockHydrantDoc } = await import("#lib/migration/mock.ts");
		doc = await mockHydrantDoc(doc, config.liarPdsUrl, ctx.fetch);
	}
	return sameOrigin(doc.pds, config.liarPdsUrl);
};

export const sleep = (ms: number, signal?: AbortSignal) =>
	new Promise<void>((done, fail) => {
		if (signal?.aborted) return fail(signal.reason);
		const onAbort = () => {
			clearTimeout(timer);
			fail(signal?.reason);
		};
		const timer = setTimeout(() => {
			signal?.removeEventListener("abort", onAbort);
			done();
		}, ms);
		signal?.addEventListener("abort", onAbort, { once: true });
	});

// hydrant may lag the unmark, so this polls the doc
export const waitForMigration = async (
	ctx: BobbinContext,
	did: string,
	config: MigrationConfig,
	{
		intervalMs = 2000,
		timeoutMs = 60_000,
		signal
	}: { intervalMs?: number; timeoutMs?: number; signal?: AbortSignal } = {}
): Promise<boolean> => {
	const deadline = Date.now() + timeoutMs;
	for (;;) {
		// the records are already moved, so a failed lookup is just another poll
		const pending = await migrationPending(ctx, did, config).catch(() => true);
		if (!pending) return true;
		const left = deadline - Date.now();
		if (left <= 0) return false;
		await sleep(Math.min(intervalMs, left), signal);
	}
};