import { page } from "$app/state"; import { SvelteSet } from "svelte/reactivity"; import { isDid, type Did } from "@atcute/lexicons/syntax"; import { getAuth } from "#lib/auth.svelte.ts"; import { hostForServiceDid, serviceDidForHost } from "#lib/auth/agent.ts"; import { validateRepoName } from "#lib/api/repoCreate.ts"; import { githubErrorMessage, type GitHubAccount, type GitHubRepo } from "#lib/github.ts"; import { flowReturnPath, returnPathFrom, startUrlFrom } from "#lib/api/migrator.ts"; import { hasGrantEvidence } from "#lib/components/import/grantEvidence.ts"; import { findRepoCollisions, fetchGitHubAccount, invalidateGitHubAccount, importGitHubRepos } from "#lib/api/githubImport.ts"; import { getMigrationTask, grantRefused, listMigrationTasks, migrationRunning, MigrationGrantRequired, type MigrationJobStatus, type MigrationTask } from "#lib/api/migrator.ts"; import type { MigrationItem } from "#lib/components/import/MigrationStep.svelte"; import { migrationRows } from "#lib/components/import/migrationRows.ts"; import { createJobMatcher, type JobRef } from "#lib/components/import/jobMatcher.ts"; type Migration = | { status: "idle" } | { status: "submitting" } | { status: "error"; error: string } | { status: "success"; task: { taskId: string; name: string }; jobId?: string; jobStatus: MigrationJobStatus | string; jobError?: string; repoDid?: string; }; export type Draft = { selected: boolean; name: string; description: string; knot: string; rkey?: string; migration: Migration; }; type Stash = { id: number; name: string; description: string; knot: string }[]; interface GitHubImporterOptions { knots: () => readonly string[] | Promise; migratorUrl: () => string; fetcher?: () => typeof fetch | undefined; } type MigrationJob = MigrationTask["jobs"][number]; type GrantLatch = Pick | null; const MAX_JOBS_PER_TASK = 50; const POLL_MIN_MS = 4_000; const POLL_MAX_MS = 60_000; const STASH_KEY = "tangled.import.github"; const GRANT_KEY = "tangled.import.github.grant_confirmed"; const TRANSPORT_PARAMS = ["return_to", "oauth_error", "migrator"] as const; const messageOf = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause); export const resolveKnotOptions = async ( knots: readonly string[] | Promise ): Promise => { if (Array.isArray(knots)) return knots; return await knots; }; export const isMigratable = (m: Migration | undefined): boolean => !m || m.status === "idle" || m.status === "error" || (m.status === "success" && (m.jobStatus === "failed" || m.jobStatus === "authorization_required")); export const createRunGuard = () => { let current = 0; return { begin: (): number => ++current, owns: (token: number): boolean => token === current }; }; // the migrator's callback is the only proof the grant was completed, and the app strips the // parameter it arrives with, so it is remembered here until the account is disconnected export const createRememberedGrant = (storage: GrantLatch, key: string) => ({ restore: (): boolean => storage?.getItem(key) === "true", confirm: (): void => { try { storage?.setItem(key, "true"); } catch {} }, clear: (): void => { try { storage?.removeItem(key); } catch {} } }); export const taskStatusPatches = ( task: MigrationTask, repos: readonly { id: number; name: string }[], drafts: Record ): [number, Migration][] => { const match = createJobMatcher(repos, drafts); return task.jobs.flatMap((job): [number, Migration][] => { const repo = match(job); const current = repo ? drafts[repo.id]?.migration : undefined; if (!repo || current?.status !== "success" || current.task.taskId !== task.id) return []; return [ [ repo.id, { ...current, jobId: job.id, jobStatus: job.status, ...(job.error !== undefined ? { jobError: job.error } : {}), ...(job.repoDid !== undefined ? { repoDid: job.repoDid } : {}) } ] ]; }); }; export const createGitHubImporter = (options: GitHubImporterOptions) => { const auth = getAuth(); const user = $derived(auth.currentUser); let account = $state(null); let accountLoading = $state(false); let drafts = $state>({}); const expanded = new SvelteSet(); let errorMessage = $state(""); let fetchedKnots = $state([]); let grantConfirmed = $state(false); let loadedTasks = $state([]); let grantAsked = $state(false); let grantedNow = $state(false); let running = $state(false); let sessionTaskCreated = $state(false); let accountDid: string | undefined; let consumedTransport = false; let destroyed = false; let generation = 0; let pollDelay = POLL_MIN_MS; let restoredFromStash = false; let stash: Stash | undefined; let statusTimer: ReturnType | undefined; const grantLatch = createRememberedGrant( typeof sessionStorage === "undefined" ? null : sessionStorage, GRANT_KEY ); const runGuard = createRunGuard(); const loadKnots = async (): Promise => { const knots = await resolveKnotOptions(options.knots()); fetchedKnots = knots; return knots; }; $effect(() => { const knots = options.knots(); if (Array.isArray(knots)) return; void Promise.resolve(knots).then((res) => { fetchedKnots = res; }); }); const knotOptions = $derived( Array.isArray(options.knots()) ? (options.knots() as readonly string[]) : fetchedKnots ); const defaultKnot = $derived(knotOptions[0] ?? ""); $effect(() => { if (!defaultKnot) return; for (const id of Object.keys(drafts)) { if (!drafts[Number(id)].knot) updateDraft(Number(id), { knot: defaultKnot }); } }); const repos = $derived(account?.repos ?? []); const selected = $derived(repos.filter((repo) => drafts[repo.id]?.selected)); const allSelected = $derived(repos.length > 0 && selected.length === repos.length); const disabled = $derived(running || !user); const migratable = $derived( selected.filter((repo) => isMigratable(drafts[repo.id]?.migration)) ); const migrationItems = $derived(migrationRows(loadedTasks, drafts)); const anyRunning = $derived( running || migrationItems.some((item) => { const m = item.migration; return ( m.status === "submitting" || (m.status === "success" && m.jobStatus !== undefined && migrationRunning(m.jobStatus)) ); }) ); const anyFailed = $derived( migrationItems.some((item) => { const m = item.migration; return m.status === "error" || (m.status === "success" && m.jobStatus !== "completed"); }) ); // a grant made on this visit outranks the failures of jobs that ran before it const grantNeeded = $derived( grantAsked || (!grantedNow && migrationItems.some( (item) => item.migration.status === "success" && grantRefused(item.migration.jobStatus, item.migration.jobError) )) ); const authorized = $derived( !grantNeeded && hasGrantEvidence({ granted: grantConfirmed, url: page.url, tasks: loadedTasks, sessionCreated: sessionTaskCreated }) ); const connectUrl = $derived( `/_internal/github/connect?return_to=${encodeURIComponent(flowReturnPath(page.url))}` ); const connectError = $derived(githubErrorMessage(page.url.searchParams.get("github_error"))); const repoRkey = (name: string): string => { try { return validateRepoName(name).toLowerCase(); } catch { return name.toLowerCase(); } }; const freshDraft = (repo: GitHubRepo, fallbackKnot = defaultKnot): Draft => ({ selected: false, name: repo.name, description: repo.description ? Array.from(repo.description).slice(0, 140).join("") : "", knot: fallbackKnot || defaultKnot, rkey: repoRkey(repo.name), migration: { status: "idle" } }); const updateDraft = (id: number, patch: Partial) => { const next = { ...patch }; if (patch.name !== undefined && patch.rkey === undefined) next.rkey = repoRkey(patch.name); drafts[id] = { ...drafts[id], ...next }; }; const migrationFromJob = ( task: MigrationTask, job: MigrationJob | undefined, taskName: string ): Migration => ({ status: "success", task: { taskId: task.id, name: taskName }, jobId: job?.id, jobStatus: job?.status ?? "queued", jobError: job?.error, repoDid: job?.repoDid }); const findRepoForJob = (job: JobRef): GitHubRepo | undefined => createJobMatcher(repos, drafts)(job); const syncTasksToDrafts = (tasks: MigrationTask[]) => { const match = createJobMatcher(repos, drafts); for (const task of tasks) { for (const job of task.jobs) { const repo = match(job); if (repo && drafts[repo.id]?.migration.status === "idle") { updateDraft(repo.id, { migration: migrationFromJob(task, job, job.name) }); } } } }; const adoptSubmittedJob = (task: MigrationTask, repo: GitHubRepo) => { const draft = drafts[repo.id]; const wanted = [draft.name.toLowerCase(), (draft.rkey ?? draft.name).toLowerCase()]; const job = task.jobs.find((j) => wanted.includes(j.name.toLowerCase())) ?? task.jobs[0]; updateDraft(repo.id, { selected: false, migration: migrationFromJob(task, job, draft.name) }); }; const draftsFor = (nextRepos: GitHubRepo[], knot: string) => Object.fromEntries( nextRepos.map((repo) => [repo.id, drafts[repo.id] ?? freshDraft(repo, knot)]) ); // the migrator round trip reloads the page, so the rows picked before the redirect are restored // once, then forgotten const restoreStashedPicks = (next: Record): Record => { if (!stash || restoredFromStash) return next; restoredFromStash = true; for (const picked of stash) { const draft = next[picked.id]; if (draft?.migration.status === "idle") { next[picked.id] = { ...draft, selected: true, name: picked.name, description: picked.description, knot: picked.knot }; } } return next; }; const resetDrafts = (nextRepos: GitHubRepo[], initialKnot?: string) => { drafts = restoreStashedPicks(draftsFor(nextRepos, initialKnot || defaultKnot)); syncTasksToDrafts(loadedTasks); }; const select = (id: number, checked: boolean) => { if (running) return; updateDraft(id, { selected: checked }); }; const setAllSelected = (checked: boolean) => { if (!account || running) return; drafts = Object.fromEntries( account.repos.map((repo) => [repo.id, { ...drafts[repo.id], selected: checked }]) ); }; const toggleExpand = (id: number) => { if (expanded.has(id)) expanded.delete(id); else expanded.add(id); }; const collidingNames = (names: string[]): string[] => [...findRepoCollisions(names).values()] .filter((collision) => collision.hasCollision) .map((collision) => collision.canonical); const validateSelections = (picked: GitHubRepo[]) => { for (const repo of picked) { const draft = drafts[repo.id]; if (!draft.knot) throw new Error(`Choose a knot for ${repo.name}.`); if (!isDid(serviceDidForHost(draft.knot))) throw new Error(`Choose a valid knot for ${repo.name}.`); try { validateRepoName(draft.name); } catch (cause) { throw new Error(`${repo.name}: ${messageOf(cause)}`, { cause }); } } const collisions = collidingNames(picked.map((repo) => drafts[repo.id].name)); if (collisions.length) throw new Error( `These repositories would get the same name: ${collisions.join(", ")}. Rename one of them, then migrate.` ); }; // teardown and account switches both bump the generation, so a run holding an old version can // stop early const stale = (version: number): boolean => destroyed || generation !== version; const superseded = (version: number, ownerDid: string): boolean => stale(version) || auth.currentUser?.did !== ownerDid; const assertOwner = (ownerDid: string, version: number) => { if (generation !== version || auth.currentUser?.did !== ownerDid) throw new Error("The active account changed. Try again."); }; const failMigrations = (repos: GitHubRepo[], message: string) => { for (const repo of repos) updateDraft(repo.id, { migration: { status: "error", error: message } }); }; const loadTasks = async (ownerDid: string, version: number) => { try { const agent = await auth.agentFor(ownerDid as Did, { relogin: false }); if (stale(version)) return; const tasks = await listMigrationTasks(agent, options.migratorUrl(), { limit: 20 }); if (stale(version)) return; loadedTasks = tasks; syncTasksToDrafts(tasks); if (tasks.some((task) => task.jobs.some((job) => migrationRunning(job.status)))) { scheduleStatusPoll(); } } catch { // the migrator may want authorization, or be down for a moment } }; const loadAccount = async (ownerDid: string, version: number) => { accountLoading = true; try { const [next, knots] = await Promise.all([ fetchGitHubAccount(options.fetcher?.()), loadKnots() ]); if (superseded(version, ownerDid) || !next) return; assertOwner(ownerDid, version); account = next; resetDrafts(next.repos, knots[0] ?? ""); } catch (cause) { if (generation === version) errorMessage = messageOf(cause); } finally { if (generation === version) accountLoading = false; } }; $effect(() => { const did = auth.currentUser?.did; if (did === accountDid) return; // the first settlement is not an account switch, so a confirmed grant survives it const switched = accountDid !== undefined && did !== accountDid; accountDid = did; const version = ++generation; if (switched) { account = null; drafts = {}; loadedTasks = []; running = false; expanded.clear(); grantConfirmed = false; sessionTaskCreated = false; grantAsked = false; grantedNow = false; } if (did) { void loadAccount(did, version); void loadTasks(did, version); } }); const readStashedPicks = () => { const raw = sessionStorage.getItem(STASH_KEY); if (!raw) return; sessionStorage.removeItem(STASH_KEY); try { stash = JSON.parse(raw) as Stash; } catch {} }; const settleGrantLatch = (oauthError: string | null) => { if (page.url.searchParams.get("migrator") === "granted" && !oauthError) { grantConfirmed = true; grantedNow = true; grantLatch.confirm(); return; } if (oauthError) { grantLatch.clear(); return; } if (grantLatch.restore()) grantConfirmed = true; }; const stripTransportParams = (params: Pick) => { if (!TRANSPORT_PARAMS.some((name) => params.has(name))) return; // sveltekit's replaceState does nothing while the page is still starting up, so the // browser's own is used; nothing reads these parameters off page.url after this point history.replaceState(history.state, "", returnPathFrom(page.url)); }; $effect(() => { if (consumedTransport) return; consumedTransport = true; const oauthError = page.url.searchParams.get("oauth_error"); if (oauthError === "grant_failed") errorMessage = "Authorization didn't complete. Authorize the migrator to continue."; readStashedPicks(); settleGrantLatch(oauthError); stripTransportParams(page.url.searchParams); }); $effect(() => { return () => { destroyed = true; generation++; if (statusTimer) clearTimeout(statusTimer); }; }); const disconnect = async () => { if (running) return; try { const fetchFn = options.fetcher?.() ?? fetch; const response = await fetchFn("/_internal/github", { method: "DELETE" }); if (!response.ok) throw new Error("Unable to disconnect GitHub. Try again."); invalidateGitHubAccount(options.fetcher?.()); grantLatch.clear(); generation++; account = null; errorMessage = ""; } catch (cause) { errorMessage = messageOf(cause); } }; const stashSelections = (picked: GitHubRepo[]) => { const payload: Stash = picked.map((repo) => { const draft = drafts[repo.id]; return { id: repo.id, name: draft.name, description: draft.description, knot: draft.knot }; }); sessionStorage.setItem(STASH_KEY, JSON.stringify(payload)); }; const redirectToGrant = (startUrl: string | null, picked: GitHubRepo[]) => { if (!startUrl) { const error = "Unable to open the migrator's authorization page. Reload this page and try again."; errorMessage = error; failMigrations(picked, error); return; } stashSelections(picked); window.location.assign(startUrl); }; // a refused grant only asks: the picks go back to being selected, and authorize() takes them // along to the migrator once the user says so const askForGrant = (startUrl: string | null, picked: GitHubRepo[]) => { if (!startUrl) { redirectToGrant(startUrl, picked); return; } for (const repo of picked) updateDraft(repo.id, { selected: true, migration: { status: "idle" } }); grantAsked = true; }; const authorize = () => { if (running) return; const did = auth.currentUser?.did; if (!did) { errorMessage = "Sign in to Tangled to authorize the migrator."; return; } redirectToGrant(startUrlFrom(options.migratorUrl(), did), migratable); }; const markSubmitting = (picked: GitHubRepo[]) => { for (const repo of picked) updateDraft(repo.id, { migration: { status: "submitting" } }); }; const migrationInputs = (picked: GitHubRepo[], owner: NonNullable) => picked.map((repo) => ({ ownerDid: owner.did, ownerHandle: owner.handle, knot: drafts[repo.id].knot, repo, name: drafts[repo.id].name, description: drafts[repo.id].description })); // the migrator takes at most MAX_JOBS_PER_TASK repos per task, so picks go out in batches const submitBatch = async ( agent: Awaited>, owner: NonNullable, version: number, publicOrigin: string, picked: GitHubRepo[], inputs: ReturnType, start: number ): Promise<"submitted" | "failed" | "stale" | "grant"> => { const batch = picked.slice(start, start + MAX_JOBS_PER_TASK); try { const task = await importGitHubRepos( agent, options.migratorUrl(), publicOrigin, inputs.slice(start, start + MAX_JOBS_PER_TASK), { fetch: options.fetcher?.(), bobbinUrl: auth.bobbinUrl } ); assertOwner(owner.did, version); sessionTaskCreated = true; loadedTasks = [task, ...loadedTasks.filter((t) => t.id !== task.id)]; for (const repo of batch) adoptSubmittedJob(task, repo); return "submitted"; } catch (cause) { if (superseded(version, owner.did)) return "stale"; if (cause instanceof MigrationGrantRequired) { askForGrant(cause.startUrl, picked.slice(start)); return "grant"; } failMigrations(batch, messageOf(cause)); errorMessage = messageOf(cause); return "failed"; } }; const runQueue = async (picked: GitHubRepo[]) => { if (!account || !user || running || !picked.length) return; const runToken = runGuard.begin(); const owner = { ...user }; const version = generation; const publicOrigin = account.publicOrigin; try { validateSelections(picked); running = true; errorMessage = ""; grantAsked = false; const agent = await auth.agentFor(owner.did); assertOwner(owner.did, version); markSubmitting(picked); const inputs = migrationInputs(picked, owner); for (let start = 0; start < inputs.length; start += MAX_JOBS_PER_TASK) { const outcome = await submitBatch( agent, owner, version, publicOrigin, picked, inputs, start ); if (outcome === "failed") break; if (outcome !== "submitted") return; } pollDelay = POLL_MIN_MS; scheduleStatusPoll(); } catch (cause) { if (superseded(version, owner.did)) return; if (cause instanceof MigrationGrantRequired) { askForGrant(cause.startUrl, picked); return; } failMigrations(picked, messageOf(cause)); errorMessage = messageOf(cause); } finally { if (runGuard.owns(runToken)) running = false; if (generation === version) scheduleStatusPoll(); } }; const migrate = () => void runQueue([...migratable]); // a failed repo goes through createTask again, which brings a fresh grant and github token, // and picks up the knot repo and placeholder record the failed attempt left behind, so it // keeps that attempt's knot const retry = (item: MigrationItem) => { const repo = findRepoForJob({ id: item.migration.jobId, name: item.name }); if (!repo) { errorMessage = `Connect the GitHub account that owns ${item.name} to retry it.`; return; } const failed = loadedTasks .flatMap((task) => task.jobs) .find((job) => job.id === item.migration.jobId); const knot = failed ? hostForServiceDid(failed.knotDid) : null; if (knot) updateDraft(repo.id, { knot }); void runQueue([repo]); }; const statusFingerprint = () => JSON.stringify( repos.map((repo) => { const m = drafts[repo.id]?.migration; return m?.status === "success" ? [m.task.taskId, m.jobStatus] : null; }) ); const runningTaskIds = (): string[] => repos.flatMap((repo) => { const m = drafts[repo.id]?.migration; return m?.status === "success" && migrationRunning(m.jobStatus) ? [m.task.taskId] : []; }); const applyTaskStatus = (task: MigrationTask) => { loadedTasks = loadedTasks.map((t) => (t.id === task.id ? task : t)); for (const [id, migration] of taskStatusPatches(task, repos, drafts)) { updateDraft(id, { migration }); } }; const refreshStatuses = async () => { const owner = auth.currentUser; if (!owner || running || destroyed) return; const version = generation; const watched = runningTaskIds(); if (!watched.length) return; const before = statusFingerprint(); let agent: Awaited>; try { agent = await auth.agentFor(owner.did, { relogin: false }); } catch { return; } let reached = 0; for (const taskId of watched.filter((id, i) => watched.indexOf(id) === i)) { if (stale(version)) return; try { const task = await getMigrationTask(agent, options.migratorUrl(), taskId); reached++; applyTaskStatus(task); } catch {} } const changed = statusFingerprint() !== before; pollDelay = reached < watched.length || !changed ? Math.min(pollDelay * 2, POLL_MAX_MS) : POLL_MIN_MS; }; const scheduleStatusPoll = () => { if (destroyed) return; if (statusTimer) clearTimeout(statusTimer); statusTimer = setTimeout(async () => { statusTimer = undefined; if (destroyed) return; await refreshStatuses(); if (!destroyed && anyRunning) scheduleStatusPoll(); }, pollDelay); }; return { get account() { return account; }, get accountLoading() { return accountLoading; }, get errorMessage() { return errorMessage; }, set errorMessage(v: string) { errorMessage = v; }, get disabled() { return disabled; }, get submitting() { return running; }, get connectUrl() { return connectUrl; }, get connectError() { return connectError; }, get userHandle() { return user?.handle; }, get authorized() { return authorized; }, get grantNeeded() { return grantNeeded; }, authorize, disconnect, get repos() { return repos; }, get drafts() { return drafts; }, get allSelected() { return allSelected; }, get expanded() { return expanded; }, get knotOptions() { return knotOptions; }, get migratable() { return migratable; }, get migrationItems() { return migrationItems; }, get anyRunning() { return anyRunning; }, get anyFailed() { return anyFailed; }, updateDraft, select, setAll: setAllSelected, toggleExpand, migrate, retry }; };