~james/core

core/web/src/lib/components/migration/MigrationLanding.svelte -rw-r--r-- 7.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 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
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<script lang="ts">
	import { refreshAll } from "$app/navigation";
	import { page } from "$app/state";
	import ArrowRight from "$icon/arrow-right";
	import LogIn from "$icon/log-in";
	import LogOut from "$icon/log-out";
	import RotateCcw from "$icon/rotate-ccw";
	import X from "$icon/x";
	import { getAuth } from "#lib/auth.svelte.ts";
	import { createAction } from "#lib/action.svelte.ts";
	import { createBobbinClient } from "#lib/api/client.ts";
	import Meta from "#lib/components/seo/Meta.svelte";
	import Button from "#lib/components/ui/Button.svelte";
	import ConfirmModal from "#lib/components/ui/ConfirmModal.svelte";
	import ErrorAlert from "#lib/components/ui/Error.svelte";
	import {
		importFromLiar,
		MigrationScopeError,
		unmarkLiarAccount,
		type ImportProgress,
		type LostBlob
	} from "#lib/migration/import.ts";
	import { waitForMigration, type MigrationConfig } from "#lib/migration/status.ts";

	interface Props {
		config: MigrationConfig & { bobbinUrl: string };
		onSignOut: () => void;
	}

	let { config, onSignOut }: Props = $props();

	const auth = getAuth();

	let progress = $state<ImportProgress | null>(null);
	let waiting = $state(false);
	let needsGrant = $state(false);
	let confirmSkip = $state(false);
	let lostBlobs = $state<LostBlob[]>([]);
	let migrated = $state(false);
	// a retry skips whatever already went through
	let imported = false;
	let unmarked = false;

	const migrate = createAction(async (skip: boolean = false) => {
		const agent = auth.agent;
		if (!agent) throw new Error("Still signing you in. Try again in a moment.");
		needsGrant = false;
		confirmSkip = false;

		try {
			const fetch = config.liarMock
				? (await import("#lib/migration/mock.ts")).mockLiarFetch
				: undefined;
			if (!imported && !skip) {
				({ lostBlobs } = await importFromLiar(agent, {
					liarPdsUrl: config.liarPdsUrl,
					bobbinUrl: config.bobbinUrl,
					fetch,
					onProgress: (next) => (progress = next)
				}));
				imported = true;
			}
			if (!unmarked) {
				progress = {
					phase: "finalizing",
					done: 0,
					total: 0,
					overall: { done: 1, total: 1 }
				};
				await unmarkLiarAccount(agent, config.bobbinUrl, { fetch });
				unmarked = true;
			}

			progress = null;
			waiting = true;
			const settled = await waitForMigration(
				createBobbinClient({ serviceUrl: config.bobbinUrl }),
				agent.sub,
				config
			);
			if (!settled) {
				throw new Error(
					"Your data is migrated, but Tangled hasn't switched you over yet. Try again in a minute."
				);
			}
			if (lostBlobs.length > 0) migrated = true;
			else await refreshAll();
		} catch (cause) {
			needsGrant = cause instanceof MigrationScopeError;
			throw cause;
		} finally {
			progress = null;
			waiting = false;
		}
	});

	const reauthorize = createAction(async () => {
		const did = auth.currentDid;
		if (!did) return;
		await auth.signIn(did, page.url.pathname + page.url.search);
	});

	const status = $derived.by(() => {
		if (waiting) return "Waiting for Tangled to switch you over…";
		if (progress?.resumesAt) {
			const at = new Date(progress.resumesAt).toLocaleTimeString([], {
				hour: "numeric",
				minute: "2-digit"
			});
			return `Your PDS limits how fast records can be written. Continuing at ${at}…`;
		}
		if (progress?.phase === "reading") return "Reading records…";
		if (progress?.phase === "blobs") {
			return `Copying files (${progress.done} of ${progress.total})`;
		}
		if (progress?.phase === "importing") {
			return `Migrating records (${progress.done} of ${progress.total})`;
		}
		if (progress?.phase === "finalizing") return "Finishing up…";
		return null;
	});

	const percent = $derived.by(() => {
		if (waiting || progress?.phase === "finalizing") return 100;
		if (!progress?.overall.total) return 0;
		return Math.round((progress.overall.done / progress.overall.total) * 100);
	});

	const indeterminate = $derived(waiting || progress?.phase === "reading");
</script>

<Meta noindex title="Migrate your data" />

<section class="mx-auto flex w-full max-w-medium flex-col gap-md px-7 py-5xl">
	<h1 class="typography-heading-2 text-foreground-default">Migrate your data</h1>
	<p class="typography-paragraph-regular text-foreground-muted">
		Tangled now stores your data in a new record format. Migrate it to keep using Tangled
		{#if auth.currentUser}as <span class="font-medium text-foreground-default"
				>{auth.currentUser.handle}</span
			>{/if}. If anything fails, you can safely try again.
	</p>

	<ErrorAlert label={reauthorize.error ?? migrate.error} />

	{#if migrated}
		<div
			class="flex flex-col gap-xs rounded-md border border-border-default bg-background-warning-subtle px-sm py-xs typography-paragraph-small text-foreground-warning-strong"
			role="status"
		>
			<p>
				Your data is migrated, but some files couldn't be copied because they no longer
				exist anywhere. These records were migrated without them:
			</p>
			<ul class="list-disc pl-md">
				{#each lostBlobs as lost (`${lost.collection}/${lost.rkey}/${lost.field}`)}
					<li class="typography-monospace-regular">
						{lost.collection}/{lost.rkey} ({lost.field})
					</li>
				{/each}
			</ul>
		</div>
		<div>
			<Button variant="primary" icon={ArrowRight} onclick={() => refreshAll()}
				>Continue</Button
			>
		</div>
	{:else}
		<div class="flex flex-wrap items-center gap-sm">
			{#if needsGrant}
				<Button
					variant="primary"
					icon={LogIn}
					loading={reauthorize.loading}
					onclick={reauthorize.run}
				>
					Sign in again to grant permission
				</Button>
			{:else}
				<Button
					variant={migrate.error ? "danger" : "primary"}
					icon={migrate.error ? RotateCcw : ArrowRight}
					loading={migrate.loading}
					disabled={!auth.agent}
					onclick={() => migrate.run()}
				>
					{migrate.error ? "Try again" : "Start migration"}
				</Button>
			{/if}
			<Button
				variant="ghost"
				icon={X}
				disabled={!auth.agent || migrate.loading}
				onclick={() => (confirmSkip = true)}
			>
				Skip migration
			</Button>
			<Button variant="ghost" icon={LogOut} disabled={migrate.loading} onclick={onSignOut}>
				Sign out
			</Button>
		</div>
	{/if}

	{#if status}
		<div class="flex flex-col gap-xs" role="status">
			<p class="typography-paragraph-small text-foreground-muted tabular-nums">{status}</p>
			<div
				class={[
					"h-2 w-full overflow-hidden rounded-full border border-border-default bg-background-inset",
					indeterminate && "animate-pulse motion-reduce:animate-none"
				]}
				role="progressbar"
				aria-valuenow={indeterminate ? undefined : percent}
				aria-valuemin={0}
				aria-valuemax={100}
			>
				<div
					class="h-full rounded-full bg-background-info-emphasis transition-transform duration-250 ease-out-strong motion-reduce:transition-none"
					style:transform="translateX(-{100 - percent}%)"
				></div>
			</div>
		</div>
	{/if}
</section>

<ConfirmModal
	bind:open={confirmSkip}
	title="Skip migration?"
	description="Your existing Tangled data (sh.tangled.* records) won't be copied to the new format. It stays in your PDS, but Tangled no longer reads it, so none of it will appear on Tangled."
	confirmLabel="Skip migration"
	loading={migrate.loading}
	onconfirm={() => migrate.run(true)}
/>