~james/core

core/web/src/lib/api/migrator.ts -rw-r--r-- 7.8 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
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
import { ClientResponseError } from "@atcute/client";
import { isDid } from "@atcute/lexicons/syntax";
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { mintServiceAuth, serviceDidForHost } from "#lib/auth/agent.ts";
import { missingPermissions, type Permission } from "#lib/auth/scopes.ts";
import {
	jsonGet,
	jsonPost,
	serviceClient,
	serviceUrlFor,
	toResponseError
} from "#lib/api/_request.ts";
import { nsidOf } from "#lib/api/syntax.ts";
import { mainSchema as createTaskSchema } from "#lib/api/lexicons/types/org/tangled/temp/migrator/createTask.ts";
import type * as Migrator from "#lib/api/lexicons/types/org/tangled/temp/migrator/defs.ts";
import { mainSchema as describeSourceSchema } from "#lib/api/lexicons/types/org/tangled/temp/migrator/describeSource.ts";
import type { $output as DescribeSourceOutput } from "#lib/api/lexicons/types/org/tangled/temp/migrator/describeSource.ts";
import { mainSchema as getTaskSchema } from "#lib/api/lexicons/types/org/tangled/temp/migrator/getTask.ts";
import { mainSchema as listTasksSchema } from "#lib/api/lexicons/types/org/tangled/temp/migrator/listTasks.ts";
import type { $output as ListTasksOutput } from "#lib/api/lexicons/types/org/tangled/temp/migrator/listTasks.ts";
import { mainSchema as retryJobSchema } from "#lib/api/lexicons/types/org/tangled/temp/migrator/retryJob.ts";
import type { Fetch } from "#lib/fetch.ts";

const CREATE_TASK = nsidOf(createTaskSchema.nsid);
const GET_TASK = getTaskSchema.nsid;
const LIST_TASKS = listTasksSchema.nsid;
const RETRY_JOB = retryJobSchema.nsid;
const DESCRIBE_SOURCE = describeSourceSchema.nsid;

export const describeSourcePermission = (host: string): Permission | null => {
	const aud = serviceDidForHost(host);
	return isDid(aud) ? { resource: "rpc", lxm: DESCRIBE_SOURCE, aud } : null;
};

export const missingDescribeSourceScope = (
	agent: OAuthUserAgent,
	host: string
): readonly Permission[] => {
	const wanted = describeSourcePermission(host);
	return wanted === null ? [] : missingPermissions(agent.session.token.scope, [wanted]);
};

export type MigrationTask = Migrator.Task;
export type NewMigrationJob = Migrator.NewJob;
export type MigrationJobStatus =
	"authorization_required" | "cloning" | "completed" | "failed" | "importing" | "queued";

export class MigrationGrantRequired extends Error {
	readonly startUrl: string | null;
	constructor(startUrl: string | null) {
		super("Authorize the migrator to start migrating.");
		this.name = "MigrationGrantRequired";
		this.startUrl = startUrl;
	}
}

// migrator echoes return_to and appends oauth_error; round trips must not nest them
const transportParams = ["return_to", "oauth_error", "migrator"];

const withQuery = (pathname: string, params: URLSearchParams): string => {
	const query = params.toString();
	return query === "" ? pathname : `${pathname}?${query}`;
};

export const returnPathFrom = (location: { pathname: string; search: string }): string => {
	const params = new URLSearchParams(location.search);
	for (const key of transportParams) params.delete(key);
	return withQuery(location.pathname, params);
};

export const flowReturnPath = (location: { pathname: string; search: string }): string => {
	const params = new URLSearchParams(location.search);
	params.delete("github_error");
	return withQuery(location.pathname, params);
};

const currentReturnPath = (): string =>
	typeof window === "undefined"
		? ""
		: returnPathFrom({ pathname: window.location.pathname, search: window.location.search });

export const startUrlFrom = (
	host: string,
	did: string | undefined,
	returnTo = currentReturnPath()
): string | null =>
	did === undefined
		? null
		: `${serviceUrlFor(host)}/oauth/start?did=${encodeURIComponent(did)}` +
			(returnTo === "" ? "" : `&return_to=${encodeURIComponent(returnTo)}`);

const extractGrantError = (
	cause: unknown,
	host: string,
	did: string | undefined
): MigrationGrantRequired | null =>
	cause instanceof ClientResponseError &&
	(cause.status === 428 || cause.error === "GrantRequired")
		? new MigrationGrantRequired(startUrlFrom(host, did))
		: null;

interface CreateMigrationTaskOptions {
	signal?: AbortSignal;
	fetch?: Fetch;
}

export const createMigrationTask = async (
	agent: OAuthUserAgent,
	host: string,
	requestId: string,
	jobs: NewMigrationJob[],
	options?: CreateMigrationTaskOptions | AbortSignal
): Promise<MigrationTask> => {
	if (jobs.length === 0) throw new Error("a migration needs at least one repository");
	const signal = options instanceof AbortSignal ? options : options?.signal;
	const customFetch =
		(options && !(options instanceof AbortSignal) ? options.fetch : undefined) ??
		globalThis.fetch;

	const token = await mintServiceAuth(agent, {
		aud: serviceDidForHost(host),
		lxm: CREATE_TASK,
		signal
	});

	const response = await customFetch("/_internal/github/migrator/createTask", {
		method: "POST",
		headers: {
			authorization: `Bearer ${token}`,
			"content-type": "application/json",
			accept: "application/json"
		},
		body: JSON.stringify({ requestId, jobs }),
		signal
	});

	if (!response.ok) {
		const err = await toResponseError(response);
		throw extractGrantError(err, host, agent.sub) ?? err;
	}

	const text = await response.text();
	return (text.length > 0 ? JSON.parse(text) : undefined) as MigrationTask;
};

export const getMigrationTask = async (
	agent: OAuthUserAgent,
	host: string,
	taskId: string,
	signal?: AbortSignal
): Promise<MigrationTask> => {
	const ctx = serviceClient(agent, host);
	try {
		return await jsonGet<MigrationTask>(ctx, GET_TASK, { taskId }, { signal });
	} catch (cause) {
		throw extractGrantError(cause, host, agent.sub) ?? cause;
	}
};

export const listMigrationTasks = async (
	agent: OAuthUserAgent,
	host: string,
	params?: { limit?: number },
	signal?: AbortSignal
): Promise<MigrationTask[]> => {
	const ctx = serviceClient(agent, host);
	try {
		const out = await jsonGet<ListTasksOutput>(ctx, LIST_TASKS, params, { signal });
		return out.tasks;
	} catch (cause) {
		throw extractGrantError(cause, host, agent.sub) ?? cause;
	}
};

export const describeSource = async (
	agent: OAuthUserAgent,
	host: string,
	sourceUrl: string,
	signal?: AbortSignal
): Promise<DescribeSourceOutput> => {
	const ctx = serviceClient(agent, host);
	try {
		return await jsonGet<DescribeSourceOutput>(ctx, DESCRIBE_SOURCE, { sourceUrl }, { signal });
	} catch (cause) {
		throw extractGrantError(cause, host, agent.sub) ?? cause;
	}
};

export const retryMigrationJob = async (
	agent: OAuthUserAgent,
	host: string,
	input: { taskId: string; jobId: string; githubToken?: string },
	signal?: AbortSignal
): Promise<MigrationTask> => {
	const ctx = serviceClient(agent, host);
	try {
		return await jsonPost<MigrationTask>(ctx, RETRY_JOB, input, { signal });
	} catch (cause) {
		throw extractGrantError(cause, host, agent.sub) ?? cause;
	}
};

// mirrors migrator isterminal; unrecognized status keeps poll alive
export const migrationRunning = (status: string): boolean =>
	!["completed", "failed", "authorization_required"].includes(status);

// jobs that failed on a scope the pds refused, from before the migrator stopped them as
// authorization_required, need a new grant too
export const grantRefused = (status: string | undefined, error?: string): boolean =>
	status === "authorization_required" || /ScopeMissingError|invalid_grant/.test(error ?? "");

export const migrationsInFlight = (tasks: MigrationTask[]): boolean =>
	tasks.some((task) => task.jobs.some((job) => migrationRunning(job.status)));

// only newest batch can wait on a grant; older batches are history
export const migratedRepoCount = (tasks: MigrationTask[]): number =>
	tasks.flatMap((task) => task.jobs).filter((job) => job.status === "completed").length;

export const migrationsUnfinished = (tasks: MigrationTask[]): boolean =>
	migrationsInFlight(tasks) ||
	(tasks[0]?.jobs.some((job) => job.status === "authorization_required") ?? false);