Public: anyone can read this; the crew can change it.

A detached mirror can be reconnected in one click, and a frozen upstream says so #1093

Closed opened this in answer to
Closed without merging

scout/forge:scout/1090-a-detached-mirror-can-be-reconnected-in → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +834 −15
docs/FOLLOWING.md +8
@@ -55,6 +55,14 @@ follow it. `lineageOf` (`core/following.ts`) bounds the walk — sixty
5555 repositories, six levels, thirty standings — and says when it cut something;
5656 a fork the viewer may not read is simply not in their tree.
5757
58 ## A frozen upstream
59
60 When the parent is a mirror whose origin was disconnected, it stopped moving,
61 and "ahead 813, behind 0" would be a lie. The card says instead: "Its upstream
62 is frozen: the origin was disconnected on <date>", with a link to the parent's
63 Reconnect form. Once the mirror is reconnected and synced, the ordinary
64 relationship returns (see `ORIGINS.md`).
65
5866 ## Taking updates
5967
6068 `takeUpdates` (`actions/forks.ts`) is the one button for everything git can do
docs/ORIGINS.md +26
@@ -506,6 +506,32 @@ existing kinds (`push`, `issue.opened`, `pull.opened`, `pull.merged`,
506506 `issue.commented`, …) with `via: "origin"` in the payload. None of them ever
507507 carries token material, a `state`, or a `code`.
508508
509 ## When a token expires, or the origin goes away
510
511 An origin whose token is refused and cannot be refreshed is marked
512 `needsReauth`. Nothing is silent about it: the origins page says "needs
513 re-authorizing; N mirrors are frozen", every mirror it feeds carries the same
514 note on its page, and the owner's feed gets a decision saying so. Re-authorizing
515 is disconnecting that origin and connecting it again.
516
517 Disconnecting keeps each mirror's git objects and its memory of where it came
518 from (`origin_full_name`, `origin_html_url`). Such a **detached mirror** says
519 "Frozen: the origin was disconnected, last fetched <date>" on its page and
520 branches, and a fork that follows it says "its upstream is frozen" instead of
521 a count that stopped being true. `GET /api/v1/repos/:owner/:name` carries
522 `origin: { fullName, detached, frozenSince }`.
523
524 The one click: pick one of your origins **on the same host** under the note and
525 press **Reconnect** (`POST /:owner/:name/settings/origin/reconnect`, or
526 `POST /api/v1/repos/:owner/:name/origin/reconnect { originId }`, admin). The
527 mirror is re-attached, synced, and the fork's relation is true again. Refusals:
528 `not_detached`, `wrong_host` (the host must match the mirror's remembered one),
529 `origin_cannot_see` (that account cannot see the repository), `not_found`.
530
531 Connecting an origin does it for you: every detached mirror of the same host
532 that you administer, and that the new account can see, is re-attached, and the
533 flash names them. Event: `origin.mirror_reattached`.
534
509535 ## Known limits
510536
511537 - **Write-through is inline, not queued.** The request waits on the origin
src/actions/origins.ts +112 −4
@@ -24,6 +24,11 @@ import {
2424 cacheOriginRepos,
2525 createOrigin,
2626 deleteOrigin,
27 detachedMirror,
28 linkRepoToOrigin,
29 listDetachedMirrors,
30 originHost,
31 rememberOriginRepo,
2732 getOriginFor,
2833 listOriginRepos,
2934 listOrigins,
@@ -40,7 +45,7 @@ import {
4045 type Pin,
4146 } from "../core/pins.ts";
4247 import { RateLimiter, type RateLimits } from "../core/ratelimit.ts";
43 import type { Repo } from "../core/repos.ts";
48 import { canAdmin, getRepoById, type Repo } from "../core/repos.ts";
4449 import type { User } from "../core/users.ts";
4550 import { discover } from "../origins/discover.ts";
4651 import { providerForOrigin } from "../origins/credential.ts";
@@ -83,7 +88,7 @@ import {
8388 type Provider,
8489 } from "../origins/types.ts";
8590 import { err, ok, type Result } from "../kernel/result.ts";
86 import { requireUser, requireWriter } from "./access.ts";
91 import { requireRepoAdmin, requireUser, requireWriter } from "./access.ts";
8792
8893 // ---- abuse control ----
8994
@@ -140,7 +145,7 @@ export async function connectOrigin(
140145 app: App,
141146 actor: User | undefined,
142147 input: ConnectInput,
143 ): Promise<Result<Origin, ConnectError>> {
148 ): Promise<Result<Origin & { reattached: Reattached[] }, ConnectError>> {
144149 const user = requireUser(actor);
145150 if (!user.ok) return user;
146151 if (tooManyAttempts(app, user.value.id)) return err("rate_limited");
@@ -166,7 +171,7 @@ export async function connectOrigin(
166171 identity.error.error === "unreachable" ? "unreachable" : "bad_token",
167172 );
168173
169 return storeOrigin(app, user.value, {
174 const stored = storeOrigin(app, user.value, {
170175 kind: found.value.kind,
171176 apiUrl: found.value.apiUrl,
172177 webUrl: found.value.webUrl,
@@ -174,6 +179,108 @@ export async function connectOrigin(
174179 token: input.token.trim(),
175180 authKind: "pat",
176181 });
182 if (!stored.ok) return stored;
183 const reattached = await reattachAll(app, user.value, stored.value);
184 return ok({ ...stored.value, reattached });
185 }
186
187 // ---- reconnecting a detached mirror ----
188
189 export type ReattachError =
190 | "unauthorized"
191 | "not_found"
192 | "not_detached"
193 | "wrong_host"
194 | "origin_cannot_see"
195 | "remote_unknown"
196 | "unreachable";
197
198 /** A mirror brought back, as the flash and the API name it. */
199 export interface Reattached {
200 readonly repoId: string;
201 /** `owner/name` here. */
202 readonly repo: string;
203 }
204
205 /**
206 * Re-attach a detached mirror to an origin of the same host. The repo must
207 * have lost its origin (`origin_full_name` kept, `origin_id` null), the actor
208 * must administer it and own the origin, the origin must be on the host the
209 * mirror remembers, and must be able to see the repository there — a token
210 * that cannot would only freeze it again. Then the link is rewritten, the
211 * picker row remembered (it carries the clone URL the sync fetches from), and
212 * a sync asked for. Admin only: a mirror's origin is its writer's credential.
213 */
214 export async function reattachMirror(
215 app: App,
216 actor: User | undefined,
217 repo: Repo,
218 originId: string,
219 options: { syncNow?: boolean } = {},
220 ): Promise<Result<Reattached, ReattachError>> {
221 const admin = requireRepoAdmin(app, actor, repo);
222 if (!admin.ok) return admin;
223 const user = admin.value;
224 const origin = getOriginFor(app.db, user.id, originId);
225 if (!origin) return err("not_found");
226 const lost = detachedMirror(app.db, repo.id);
227 if (lost === undefined) return err("not_detached");
228 if (lost.host === "" || lost.host !== originHost(origin))
229 return err("wrong_host");
230 // Bind by the remote's id, never by a name that something else may carry.
231 if (lost.remoteId === "") return err("remote_unknown");
232
233 const provider = providerForOrigin(app, origin);
234 if (!provider.ok) return err("not_found");
235 const seen = await provider.value.getRepo(lost.fullName);
236 if (!seen.ok)
237 return err(
238 seen.error.error === "not_found" ? "origin_cannot_see" : "unreachable",
239 );
240
241 if (seen.value.remoteId !== lost.remoteId) return err("origin_cannot_see");
242 // Another request may have re-attached it while the origin answered.
243 if (detachedMirror(app.db, repo.id) === undefined) return err("not_detached");
244 rememberOriginRepo(app.db, origin.id, seen.value);
245 linkRepoToOrigin(app.db, repo.id, {
246 originId: origin.id,
247 fullName: seen.value.fullName,
248 remoteId: seen.value.remoteId,
249 htmlUrl: seen.value.htmlUrl,
250 });
251 app.bus.append({
252 kind: "origin.mirror_reattached",
253 repoId: repo.id,
254 actorId: user.id,
255 payload: { originId: origin.id, fullName: seen.value.fullName },
256 });
257 requestSyncNow(app, origin.id);
258 // The one-click path waits for the first pull, so the page that follows
259 // shows a mirror that is already moving; the sweep path leaves it to the worker.
260 if (options.syncNow === true)
261 await syncOrigin(app, origin, { onlyRepoId: repo.id }).catch(() => {});
262 return ok({ repoId: repo.id, repo: `${repo.ownerName}/${repo.name}` });
263 }
264
265 /**
266 * Every detached mirror of this origin's host that `user` administers, tried
267 * one by one; the ones the origin cannot see stay detached, silently — a new
268 * connection is no place to report the mirrors it was never meant for.
269 */
270 export async function reattachAll(
271 app: App,
272 user: User,
273 origin: Origin,
274 ): Promise<Reattached[]> {
275 const out: Reattached[] = [];
276 for (const lost of listDetachedMirrors(app.db)) {
277 if (lost.host !== originHost(origin)) continue;
278 const repo = getRepoById(app.db, lost.repoId);
279 if (!repo || !canAdmin(app.db, repo, user)) continue;
280 const done = await reattachMirror(app, user, repo, origin.id);
281 if (done.ok) out.push(done.value);
282 }
283 return out;
177284 }
178285
179286 function storeOrigin(
@@ -589,6 +696,7 @@ async function completeConnect(
589696 });
590697 if (!stored.ok)
591698 return { status: "failed", detail: "that account is already connected" };
699 await reattachAll(app, user, stored.value);
592700 return { status: "done", detail: "", originId: stored.value.id };
593701 }
594702
src/core/origins.ts +73
@@ -629,3 +629,76 @@ export function mirrorOf(
629629 .get(originId, fullName);
630630 return row?.id;
631631 }
632
633 // ---- a mirror whose origin went away ----
634
635 /**
636 * What a detached mirror still remembers of where it came from. Deleting an
637 * origin sets `repo.origin_id` NULL and leaves the rest, which is exactly
638 * what lets it be found and re-attached later.
639 */
640 export interface DetachedMirror {
641 readonly repoId: string;
642 /** `owner/name` at the origin. */
643 readonly fullName: string;
644 readonly htmlUrl: string;
645 /** The remembered site (scheme, host, port), or "" when unknown. */
646 readonly host: string;
647 /** The remote repository's id, as remembered; "" when it never was. */
648 readonly remoteId: string;
649 /** The last time anything came in: the day the mirror froze. */
650 readonly frozenSince: string | null;
651 }
652
653 /** The site of a URL (scheme, host, port); "" when it is not one. */
654 export function hostOf(url: string): string {
655 try {
656 const u = new URL(url);
657 return u.protocol === "http:" || u.protocol === "https:" ? u.origin : "";
658 } catch {
659 return "";
660 }
661 }
662
663 interface DetachedRow {
664 id: string;
665 origin_full_name: string;
666 origin_html_url: string | null;
667 origin_remote_id: string | null;
668 last_fetch_at: string | null;
669 }
670
671 const toDetached = (row: DetachedRow): DetachedMirror => ({
672 repoId: row.id,
673 fullName: row.origin_full_name,
674 htmlUrl: row.origin_html_url ?? "",
675 host: hostOf(row.origin_html_url ?? ""),
676 remoteId: row.origin_remote_id ?? "",
677 frozenSince: row.last_fetch_at,
678 });
679
680 const DETACHED_SELECT = `SELECT id, origin_full_name, origin_html_url, origin_remote_id, last_fetch_at
681 FROM repo WHERE origin_id IS NULL AND origin_full_name IS NOT NULL
682 AND origin_full_name != ''`;
683
684 /** The mirror facts of a repo whose origin is gone, or undefined. */
685 export function detachedMirror(
686 db: Database,
687 repoId: string,
688 ): DetachedMirror | undefined {
689 const row = db
690 .query<DetachedRow, [string]>(`${DETACHED_SELECT} AND id = ?1`)
691 .get(repoId);
692 return row ? toDetached(row) : undefined;
693 }
694
695 /** Every detached mirror on the forge, oldest first. */
696 export function listDetachedMirrors(db: Database): DetachedMirror[] {
697 return db
698 .query<DetachedRow, []>(`${DETACHED_SELECT} ORDER BY id`)
699 .all()
700 .map(toDetached);
701 }
702
703 /** An origin's host, comparable with `DetachedMirror.host`. */
704 export const originHost = (origin: Origin): string => hostOf(origin.webUrl);
src/design/activity.ts +1
@@ -125,6 +125,7 @@ const WORDS: Record<string, string> = {
125125 "webhook.deleted": "removed a webhook",
126126 "origin.connected": "connected an origin",
127127 "origin.disconnected": "disconnected an origin",
128 "origin.mirror_reattached": "reconnected a mirror to its origin",
128129 "origin.needs_reauth": "needs to reconnect an origin",
129130 "run.queued": "queued a run",
130131 "run.started": "started a run",
src/feed/items.ts +37
@@ -10,6 +10,7 @@ import type { Database } from "bun:sqlite";
1010 import { listDecidedIn } from "../core/decisions.ts";
1111 import { audienceFilter } from "../core/event_audience.ts";
1212 import { listEventsVisibleTo, type ForgeEvent } from "../core/events.ts";
13 import { listMirrors, listOrigins } from "../core/origins.ts";
1314 import { getIssue } from "../core/issues.ts";
1415 import { getPull, toldBy } from "../core/pulls.ts";
1516 import {
@@ -182,6 +183,7 @@ export function candidatesFor(
182183 });
183184 }
184185 out.push(...watchedCandidates(db, viewer, now));
186 out.push(...reauthCandidates(db, viewer, now));
185187 for (const d of decided) {
186188 const repo = repos.get(d.repoId);
187189 if (!repo) continue;
@@ -201,6 +203,41 @@ export function candidatesFor(
201203 return out;
202204 }
203205
206 /**
207 * An origin that needs re-authorizing is a decision for its owner: until
208 * they act, every mirror it feeds is frozen. It rides on the first frozen
209 * mirror (a candidate belongs to a repository), and says how many there are.
210 */
211 function reauthCandidates(
212 db: Database,
213 viewer: User,
214 now: number,
215 ): Candidate[] {
216 const out: Candidate[] = [];
217 for (const origin of listOrigins(db, viewer.id)) {
218 if (!origin.needsReauth) continue;
219 const mirrors = listMirrors(db, origin.id);
220 const repo = mirrors[0] && getReposByIds(db, [mirrors[0].repoId]).get(mirrors[0].repoId);
221 if (!repo) continue;
222 const host = new URL(origin.webUrl).host;
223 const what = `${origin.login} @ ${host} needs re-authorizing; ${mirrors.length === 1 ? "1 mirror is" : `${mirrors.length} mirrors are`} frozen`;
224 out.push({
225 id: `decision:reauth:${origin.id}`,
226 kind: "decision",
227 repoId: repo.id,
228 app: slug(repo),
229 actorId: null,
230 actor: null,
231 at: new Date(now).toISOString(),
232 link: "/settings/origins",
233 what,
234 urgency: ASK_URGENCY_FLOOR,
235 said: what,
236 });
237 }
238 return out;
239 }
240
204241 type Partial = Omit<Candidate, "actor">;
205242
206243 function fromEvent(
src/http/api.ts +69 −3
@@ -71,6 +71,7 @@ import {
7171 startMirrorJob,
7272 startOAuthConnect,
7373 syncOriginNow,
74 reattachMirror,
7475 syncRepoNow,
7576 unpinRepo,
7677 } from "../actions/origins.ts";
@@ -286,7 +287,11 @@ import { readRunLog, subscribeRunLog } from "../runs/log.ts";
286287 import { blobForRender, commitLog, listRefs, listTree } from "../git/read.ts";
287288 import { repoDir } from "../git/repos.ts";
288289 import type { Result } from "../kernel/result.ts";
289 import { originForRepo, type OriginRepoRow } from "../core/origins.ts";
290 import {
291 detachedMirror,
292 originForRepo,
293 type OriginRepoRow,
294 } from "../core/origins.ts";
290295 import { subscribe as subscribeJob, type MirrorJob } from "../origins/jobs.ts";
291296 import type { Origin } from "../origins/types.ts";
292297 import {
@@ -444,8 +449,27 @@ const NO_COUNTS: RepoCounts = { openIssues: 0, openPulls: 0 };
444449 * page; a single repo pays one grouped query for itself.
445450 */
446451 function repoJson(ctx: Ctx, repo: Repo) {
452 const lost = detachedMirror(ctx.app.db, repo.id);
447453 return {
448454 ...repo,
455 // A mirror says where it comes from and whether that still feeds it.
456 ...(repo.origin !== null
457 ? {
458 origin: {
459 ...repo.origin,
460 detached: false,
461 frozenSince: null,
462 },
463 }
464 : lost !== undefined
465 ? {
466 origin: {
467 fullName: lost.fullName,
468 detached: true,
469 frozenSince: lost.frozenSince,
470 },
471 }
472 : {}),
449473 counts:
450474 repo.counts ??
451475 countsForRepos(ctx.app.db, [repo.id]).get(repo.id) ??
@@ -3540,6 +3564,33 @@ export function apiRoutes(router: Router<Handler>): void {
35403564 );
35413565 });
35423566
3567 // Reconnect a detached mirror to one of the caller's origins on its host.
3568 router.add(
3569 "POST",
3570 "/api/v1/repos/:owner/:name/origin/reconnect",
3571 async (ctx) => {
3572 const denied = requireScope(ctx, "admin");
3573 if (denied) return denied;
3574 const repo = loadRepo(ctx);
3575 if (!repo) return notFound();
3576 const input = await body(ctx.request);
3577 if (typeof input.originId !== "string" || input.originId === "")
3578 return json({ error: "originId is required" }, 400);
3579 const done = await reattachMirror(
3580 ctx.app,
3581 ctx.auth.user,
3582 repo,
3583 input.originId,
3584 { syncNow: true },
3585 );
3586 if (!done.ok)
3587 return done.error === "unauthorized" || done.error === "not_found"
3588 ? respondAccess(done.error, 404)
3589 : json({ error: done.error }, done.error === "unreachable" ? 502 : 409);
3590 return json({ ok: true, repo: done.value.repo });
3591 },
3592 );
3593
35433594 // Sync one mirror. This only pulls, so an ordinary repo writer may ask —
35443595 // it borrows nobody's identity and grants nobody anything.
35453596 router.add("POST", "/api/v1/repos/:owner/:name/sync", async (ctx) => {
@@ -3642,8 +3693,23 @@ export function apiRoutes(router: Router<Handler>): void {
36423693 ? `ssh://git@${host}:${sshPort}/${path}.git`
36433694 : null,
36443695 origin: repo.origin
3645 ? { fullName: repo.origin.fullName, htmlUrl: repo.origin.htmlUrl }
3646 : null,
3696 ? {
3697 fullName: repo.origin.fullName,
3698 htmlUrl: repo.origin.htmlUrl,
3699 detached: false,
3700 frozenSince: null,
3701 }
3702 : (() => {
3703 const lost = detachedMirror(ctx.app.db, repo.id);
3704 return lost === undefined
3705 ? null
3706 : {
3707 fullName: lost.fullName,
3708 htmlUrl: lost.htmlUrl,
3709 detached: true,
3710 frozenSince: lost.frozenSince,
3711 };
3712 })(),
36473713 pinnedAt: pin.createdAt,
36483714 },
36493715 ];
src/http/server.ts +2
@@ -80,6 +80,7 @@ import {
8080 } from "../web/pages/site.ts";
8181 import { confirmPage, searchPage } from "../web/pages/search.ts";
8282 import { followingSubmit } from "../web/pages/following.ts";
83 import { reconnectSubmit } from "../web/pages/frozen.ts";
8384 import { activityAtom } from "../web/feeds.ts";
8485 import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
8586 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
@@ -1032,6 +1033,7 @@ export function buildRouter(): Router<Handler> {
10321033 // A mirror pulls on demand; a pin says "keep this on my machine". Both are
10331034 // ordinary repo-scoped writes, not account-level ones.
10341035 router.add("POST", "/:owner/:name/sync", repoSyncSubmit);
1036 router.add("POST", "/:owner/:name/settings/origin/reconnect", reconnectSubmit);
10351037 router.add("POST", "/:owner/:name/pin", pinSubmit);
10361038
10371039 // Settings (owner-gated inside the handlers).
src/web/pages/branches.ts +2
@@ -15,6 +15,7 @@
1515 * are readable and nothing more, which is the whole rule of a live browse.
1616 */
1717
18 import { frozenNote } from "./frozen.ts";
1819 import { createBranch, deleteBranch } from "../../actions/branches.ts";
1920 import type { Repo } from "../../core/repos.ts";
2021 import { listBranches, type BranchInfo } from "../../git/branches.ts";
@@ -251,6 +252,7 @@ export async function renderBranches(
251252 branchCount: rows.length,
252253 })}
253254 ${banner ?? null}
255 ${scope.repo === undefined ? null : frozenNote(ctx, scope.repo)}
254256 <div class="mt">
255257 ${when(scope.caps.write && scope.repo !== undefined, () =>
256258 createForm(scope, all.length === 0 ? [startFrom] : all, startFrom),
src/web/pages/following.ts +16 −2
@@ -33,6 +33,8 @@ import {
3333 import type { Lineage, LineageNode } from "../../core/following.ts";
3434 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
3535 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
36 import { detachedMirror } from "../../core/origins.ts";
37 import { frozenDate } from "./frozen.ts";
3638 import { field, readForm } from "../form.ts";
3739 import { html, raw, when, type Html } from "../html.ts";
3840 import { flashOrJson } from "../layout.ts";
@@ -175,6 +177,9 @@ export function followingCard(
175177 );
176178 const followers = visibleForks(ctx.app.db, repo.id, ctx.auth.user).length;
177179
180 // A parent whose origin went away has stopped moving: ahead/behind would
181 // be true only of the day it froze, so say that instead.
182 const frozen = detachedMirror(ctx.app.db, parent.id);
178183 const canTake =
179184 relation.state === "behind" ||
180185 (relation.state === "diverged" && relation.clean);
@@ -278,9 +283,18 @@ export function followingCard(
278283 ? badge("proposal ready", { tone: "merged" })
279284 : converge?.kind === "working"
280285 ? badge("converging", { tone: "attn" })
281 : relationBadge(relation)}
286 : frozen !== undefined
287 ? badge("upstream frozen", { tone: "danger" })
288 : relationBadge(relation)}
282289 </div>
283 <p class="following-sentence">${relationSentence(relation)}</p>
290 ${frozen === undefined
291 ? html`<p class="following-sentence">${relationSentence(relation)}</p>`
292 : html`<p class="following-sentence">
293 Its upstream is frozen: the origin was disconnected on
294 ${frozenDate(frozen.frozenSince)}, so ${parentName} has stopped
295 moving and this cannot say how far behind it is.
296 <a href="/${parent.ownerName}/${parent.name}#reconnect">Reconnect</a>
297 </p>`}
284298 ${when(
285299 actions.length > 0,
286300 () => html`<div class="following-actions">${actions}</div>`,
src/web/pages/frozen.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * A mirror that stopped coming in, said where it is seen. Two ways to freeze:
3 * the origin was disconnected (the mirror is *detached* and offers Reconnect),
4 * or the origin is still connected but needs re-authorizing (the mirror says
5 * so, and the fix is on the origins page). One note, shown on the mirror's
6 * home and its branches, so nobody reads a stale mirror as a live one.
7 */
8
9 import { reattachMirror, type ReattachError } from "../../actions/origins.ts";
10 import {
11 detachedMirror,
12 listOrigins,
13 originHost,
14 } from "../../core/origins.ts";
15 import type { Repo } from "../../core/repos.ts";
16 import { canAdmin } from "../../core/repos.ts";
17 import type { Ctx } from "../../http/context.ts";
18 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
19 import { field, readForm } from "../form.ts";
20 import { html, type Html } from "../html.ts";
21 import { flashTo } from "../layout.ts";
22 import { btn, card, icon, selectField } from "../ui.ts";
23 import { accountOnly } from "./origins.ts";
24
25 /** The day a mirror froze, as a date a person can read. */
26 export const frozenDate = (since: string | null): string =>
27 since === null ? "an unknown date" : since.slice(0, 10);
28
29 /** The frozen note and the Reconnect form, or null for a mirror that is fine. */
30 export function frozenNote(ctx: Ctx, repo: Repo): Html | null {
31 const lost = detachedMirror(ctx.app.db, repo.id);
32 if (lost === undefined) {
33 const o = repo.origin;
34 if (o === null) return null;
35 const origin = listOrigins(ctx.app.db, ctx.auth.user?.id ?? "").find(
36 (x) => x.id === o.originId,
37 );
38 if (!origin?.needsReauth) return null;
39 return card(
40 html`<p>
41 ${icon("alert")} Frozen: the origin account
42 <strong>${origin.login}</strong> needs re-authorizing, so nothing new
43 comes in. <a href="/settings/origins">Re-authorize it</a>; this mirror
44 comes back by itself.
45 </p>`,
46 { tone: "danger", id: "reconnect" },
47 );
48 }
49 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
50 const same = admin
51 ? listOrigins(ctx.app.db, ctx.auth.user!.id).filter(
52 (o) => originHost(o) === lost.host,
53 )
54 : [];
55 return card(
56 html`<p>
57 ${icon("alert")} Frozen: the origin was disconnected, last fetched
58 ${frozenDate(lost.frozenSince)}. This mirror still holds
59 <span class="mono">${lost.fullName}</span> as it was, and nothing new
60 comes in.
61 </p>
62 ${admin
63 ? same.length === 0
64 ? html`<p class="mt">
65 <a href="/settings/origins">Connect an origin</a> on
66 <span class="mono">${lost.host}</span>: it reconnects this mirror
67 by itself.
68 </p>`
69 : html`<form
70 method="post"
71 action="${repoBase(repo)}/settings/origin/reconnect"
72 class="mt"
73 >
74 ${selectField({
75 name: "originId",
76 label: "Reconnect to",
77 options: same.map((o) => ({
78 value: o.id,
79 label: `${o.login} @ ${new URL(o.webUrl).host}`,
80 })),
81 })}
82 ${btn("Reconnect", {
83 size: "sm",
84 type: "submit",
85 variant: "primary",
86 icon: "sync",
87 })}
88 </form>
89 <p class="mt small muted">
90 Or <a href="/settings/origins">connect another origin</a>.
91 </p>`
92 : null}`,
93 { tone: "danger", id: "reconnect" },
94 );
95 }
96
97 export const RECONNECT_WORDS: Record<ReattachError, string> = {
98 unauthorized: "Sign in first.",
99 not_found: "No such origin, or no such mirror.",
100 not_detached: "This repository is not a detached mirror.",
101 wrong_host:
102 "That origin is on a different host than the one this mirror came from.",
103 origin_cannot_see:
104 "That origin's account cannot see the repository this mirror came from.",
105 remote_unknown:
106 "This mirror never recorded which repository it came from, so it cannot be bound safely.",
107 unreachable: "The origin could not be reached; try again in a moment.",
108 };
109
110 // POST /:owner/:name/settings/origin/reconnect
111 export async function reconnectSubmit(ctx: Ctx): Promise<Response> {
112 const repo = loadRepo(ctx);
113 if (!repo) return notFoundPage(ctx);
114 const denied = accountOnly(ctx);
115 if (denied) return denied;
116 if (!ctx.auth.user) return signInFirst(ctx);
117 const form = await readForm(ctx, "admin");
118 if (form instanceof Response) return form;
119 const base = repoBase(repo);
120 const done = await reattachMirror(
121 ctx.app,
122 ctx.auth.user,
123 repo,
124 field(form, "originId"),
125 { syncNow: true },
126 );
127 if (!done.ok)
128 return flashTo(ctx, base, {
129 tone: "danger",
130 message: RECONNECT_WORDS[done.error],
131 });
132 return flashTo(ctx, base, {
133 message: "Reconnected. The mirror is syncing from its origin again.",
134 });
135 }
src/web/pages/origins.ts +21 −4
@@ -30,7 +30,7 @@ import {
3030 syncOriginNow,
3131 } from "../../actions/origins.ts";
3232 import { getFlowFor } from "../../origins/oauth.ts";
33 import { getOriginFor, type Origin } from "../../core/origins.ts";
33 import { getOriginFor, listMirrors, type Origin } from "../../core/origins.ts";
3434 import { pinnedRepoIds } from "../../core/pins.ts";
3535 import { getRepo, getReposByIds } from "../../core/repos.ts";
3636 import type { Ctx } from "../../http/context.ts";
@@ -227,7 +227,7 @@ function healthBadge(origin: Origin): Html {
227227 return badge("Healthy", { tone: "success", icon: "check" });
228228 }
229229
230 function originCard(origin: Origin): Html {
230 function originCard(origin: Origin, frozen = 0): Html {
231231 const base = `/settings/origins/${origin.id}`;
232232 return card(
233233 html`<div class="origin-row">
@@ -252,6 +252,16 @@ function originCard(origin: Origin): Html {
252252 origin.lastError !== "",
253253 () => html`<p class="error-note mt">${origin.lastError}</p>`,
254254 )}
255 ${when(
256 origin.needsReauth,
257 () =>
258 html`<p class="error-note mt">
259 This origin needs re-authorizing;
260 ${frozen === 1 ? "one mirror is" : `${frozen} mirrors are`} frozen.
261 Disconnect it and connect it again: its mirrors are reconnected by
262 themselves.
263 </p>`,
264 )}
255265 <div class="bar mt">
256266 <form method="post" action="${base}/sync">
257267 ${btn("Sync now", { size: "sm", icon: "sync" })}
@@ -560,7 +570,7 @@ function originsView(ctx: Ctx, values: ConnectValues): Html {
560570 title: "No origins connected",
561571 note: "Connect GitHub, a Forgejo instance or a Gitea instance and its repositories become mirrorable here.",
562572 })
563 : html`<div class="stack">${origins.map(originCard)}</div>`}
573 : html`<div class="stack">${origins.map((o) => originCard(o, listMirrors(ctx.app.db, o.id).length))}</div>`}
564574 ${card(
565575 html`${tokenSection(values)}
566576 <details
@@ -668,10 +678,17 @@ export async function originConnectToken(ctx: Ctx): Promise<Response> {
668678 return shell(ctx, originsView(ctx, values), 422);
669679 }
670680 return flashTo(ctx, "/settings/origins", {
671 message: `Connected ${connected.value.login} at ${hostLabel(connected.value.webUrl)}.`,
681 message: `Connected ${connected.value.login} at ${hostLabel(connected.value.webUrl)}.${reattachedWords(connected.value.reattached)}`,
672682 });
673683 }
674684
685 /** Which detached mirrors a new connection brought back, as a sentence. */
686 function reattachedWords(reattached: readonly { repo: string }[]): string {
687 if (reattached.length === 0) return "";
688 const names = reattached.map((r) => r.repo).join(", ");
689 return ` Reconnected ${reattached.length === 1 ? "the mirror" : `${reattached.length} mirrors`}: ${names}.`;
690 }
691
675692 function connectMessage(error: string): string {
676693 const words: Record<string, string> = {
677694 unknown_host: "That does not look like a forge this can talk to.",
src/web/pages/repo.ts +2
@@ -13,6 +13,7 @@ import { FORKS_PER_DAY, forkRepo } from "../../actions/repos.ts";
1313 import { forkDrift, takeUpdates, type ForkDrift } from "../../actions/forks.ts";
1414 import { lineageOf } from "../../core/following.ts";
1515 import { followingCard, followingOf, lineageCard } from "./following.ts";
16 import { frozenNote } from "./frozen.ts";
1617 import { pinRepo, syncRepoNow, unpinRepo } from "../../actions/origins.ts";
1718 import {
1819 canAdmin,
@@ -980,6 +981,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
980981 branchCount: refs.branches.length,
981982 })}${noApp}
982983 ${appStrip(ctx, repo)}
984 ${frozenNote(ctx, repo)}
983985 ${following === undefined
984986 ? forkBar(ctx, repo)
985987 : followingCard(ctx, repo, following)}
test/origins-reconnect.test.ts added +324
@@ -0,0 +1,324 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { serve, type Servers } from "../src/http/server.ts";
7 import { forkRepo } from "../src/actions/repos.ts";
8 import { connectOrigin, reattachMirror } from "../src/actions/origins.ts";
9 import { markNeedsReauth } from "../src/core/origins.ts";
10 import { candidatesFor } from "../src/feed/items.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { getUserByName } from "../src/core/users.ts";
13 import { settled } from "../src/origins/jobs.ts";
14 import {
15 newFakeState,
16 serveFakeForge,
17 type FakeForge,
18 } from "./fake-origin.ts";
19 import { proveAll } from "./helpers/verified.ts";
20
21 /**
22 * A mirror whose origin was disconnected: it says so, its fork says its
23 * upstream is frozen, and connecting an origin on the same host (or the one
24 * click) brings it back. The git host is a second real forge; the origin API
25 * is a fake Forgejo whose web root is the host the mirror remembers.
26 */
27
28 const LOGIN = "octo";
29 const TOKEN = "octo-origin-secret-9f2a";
30 const PASSWORD = "alice-login-secret";
31 const auth = `Basic ${Buffer.from(`alice:${PASSWORD}`).toString("base64")}`;
32
33 describe("reconnecting a detached mirror", () => {
34 let dataDir: string;
35 let gitDataDir: string;
36 let app: App;
37 let servers: Servers;
38 let gitApp: App;
39 let gitServers: Servers;
40 let fake: FakeForge;
41 let other: FakeForge;
42
43 const api = (path: string, init: RequestInit = {}) => {
44 const headers = new Headers(init.headers);
45 headers.set("authorization", auth);
46 if (init.body !== undefined) headers.set("content-type", "application/json");
47 return fetch(`${servers.url}${path}`, { ...init, headers });
48 };
49 const alice = () => getUserByName(app.db, "alice")!;
50 const widgets = () => getRepo(app.db, "alice", "widgets")!;
51
52 beforeAll(async () => {
53 dataDir = await mkdtemp(join(tmpdir(), "forge-reconnect-"));
54 gitDataDir = await mkdtemp(join(tmpdir(), "forge-reconnect-git-"));
55 gitApp = createApp({ dataDir: gitDataDir, port: 0 });
56 gitServers = await serve(gitApp);
57 const gitAuth = `Basic ${Buffer.from(`${LOGIN}:${TOKEN}`).toString("base64")}`;
58 const gitJson = { "content-type": "application/json", authorization: gitAuth };
59 await fetch(`${gitServers.url}/api/v1/users`, {
60 method: "POST",
61 headers: { "content-type": "application/json" },
62 body: JSON.stringify({ username: LOGIN, email: "[email protected]", password: TOKEN }),
63 });
64 await fetch(`${gitServers.url}/api/v1/repos`, {
65 method: "POST",
66 headers: gitJson,
67 body: JSON.stringify({ name: "widgets", visibility: "public" }),
68 });
69 await fetch(`${gitServers.url}/api/v1/repos/octo/widgets/contents`, {
70 method: "POST",
71 headers: gitJson,
72 body: JSON.stringify({
73 branch: "main",
74 message: "first",
75 files: [{ path: "README.md", content: "# widgets\n" }],
76 }),
77 });
78
79 const listing = (url: string) => {
80 const state = newFakeState("forgejo", LOGIN, TOKEN);
81 state.repos.push({
82 id: 41,
83 fullName: "octo/widgets",
84 cloneUrl: `${gitServers.url}/octo/widgets.git`,
85 htmlUrl: `${url}/octo/widgets`,
86 defaultBranch: "main",
87 });
88 return state;
89 };
90 // htmlUrl names the fake's own host, which is the host the mirror will
91 // remember; the second forge is a different host.
92 const first = serveFakeForge(listing("http://placeholder"));
93 first.state.repos[0]!.htmlUrl = `${first.url}/octo/widgets`;
94 fake = first;
95 other = serveFakeForge(listing("http://placeholder"));
96
97 app = createApp({ dataDir, port: 0 });
98 servers = await serve(app);
99 await fetch(`${servers.url}/api/v1/users`, {
100 method: "POST",
101 headers: { "content-type": "application/json" },
102 body: JSON.stringify({
103 username: "alice",
104 email: "[email protected]",
105 password: PASSWORD,
106 }),
107 });
108 proveAll(app);
109 });
110
111 afterAll(async () => {
112 fake.stop();
113 other.stop();
114 servers.stop();
115 gitServers.stop();
116 app.close();
117 gitApp.close();
118 await rm(dataDir, { recursive: true, force: true });
119 await rm(gitDataDir, { recursive: true, force: true });
120 });
121
122 const connect = async (forge: FakeForge): Promise<string> => {
123 const made = await api("/api/v1/user/origins", {
124 method: "POST",
125 body: JSON.stringify({ host: forge.url, token: TOKEN }),
126 });
127 expect(made.status).toBe(201);
128 return ((await made.json()) as { id: string }).id;
129 };
130
131 test("a mirror loses its origin: the page, the API and the fork's card say so", async () => {
132 const originId = await connect(fake);
133 const started = await api(`/api/v1/user/origins/${originId}/mirror`, {
134 method: "POST",
135 body: JSON.stringify({ fullName: "octo/widgets" }),
136 });
137 const job = ((await started.json()) as { job: { id: string } }).job;
138 expect((await settled(job.id))?.stage).toBe("done");
139
140 const forked = await forkRepo(app, alice(), widgets(), "widgets-fork");
141 if (!forked.ok) throw new Error(String(forked.error));
142
143 // Healthy: no frozen note, the fork has its ordinary standing.
144 const before = await (await api("/alice/widgets-fork")).text();
145 expect(before).not.toContain("upstream is frozen");
146 expect(before).toContain("Everything here is up to date");
147 expect(await (await api("/alice/widgets")).text()).not.toContain("Frozen:");
148
149 expect((await api(`/api/v1/user/origins/${originId}`, { method: "DELETE" })).status).toBe(200);
150
151 const repo = (await (await api("/api/v1/repos/alice/widgets")).json()) as {
152 origin: { fullName: string; detached: boolean; frozenSince: string | null };
153 };
154 expect(repo.origin.detached).toBe(true);
155 expect(repo.origin.fullName).toBe("octo/widgets");
156 expect(repo.origin.frozenSince).toBeString();
157
158 const page = await (await api("/alice/widgets")).text();
159 expect(page).toContain("Frozen: the origin was disconnected");
160 // No origin on that host is connected, so it offers to connect one.
161 expect(page).not.toContain("/alice/widgets/settings/origin/reconnect");
162 expect(page).toContain("Connect an origin");
163 expect(await (await api("/alice/widgets/branches")).text()).toContain(
164 "Frozen: the origin was disconnected",
165 );
166
167 const card = await (await api("/alice/widgets-fork")).text();
168 expect(card).toContain("Its upstream is frozen");
169 expect(card).toContain("/alice/widgets#reconnect");
170 expect(card).not.toContain("Everything here is up to date");
171 }, 30_000);
172
173 test("a wrong-host origin is refused, and an unknown one is not found", async () => {
174 const wrongId = await connect(other);
175 const refused = await reattachMirror(app, alice(), widgets(), wrongId);
176 expect(refused).toEqual({ ok: false, error: "wrong_host" });
177 const viaApi = await api("/api/v1/repos/alice/widgets/origin/reconnect", {
178 method: "POST",
179 body: JSON.stringify({ originId: wrongId }),
180 });
181 expect(viaApi.status).toBe(409);
182 expect(await viaApi.json()).toEqual({ error: "wrong_host" });
183 expect(await reattachMirror(app, alice(), widgets(), "nope")).toEqual({
184 ok: false,
185 error: "not_found",
186 });
187 // The repo with the right origin offered shows it in the form; this one
188 // is on another host, so the form does not offer it.
189 expect(await (await api("/alice/widgets")).text()).not.toContain(
190 `value="${wrongId}"`,
191 );
192 app.db.query("DELETE FROM origin WHERE id = ?1").run(wrongId);
193 });
194
195 test("the manual Reconnect re-attaches, syncs, and makes the fork's relation true again", async () => {
196 // Connect by hand through the repo-less route: a different login would
197 // be a different account, so add the origin straight to the store.
198 const id = await connectSilently(fake);
199 const page = await (await api("/alice/widgets")).text();
200 expect(page).toContain(`value="${id}"`);
201 expect(page).toContain("/alice/widgets/settings/origin/reconnect");
202
203 // A mirror with no remembered remote id is not bound to a name.
204 const kept = app.db
205 .query<{ r: string }, []>(
206 "SELECT origin_remote_id AS r FROM repo WHERE name = 'widgets'",
207 )
208 .get()!.r;
209 app.db.query("UPDATE repo SET origin_remote_id = NULL WHERE name = 'widgets'").run();
210 expect(await reattachMirror(app, alice(), widgets(), id)).toEqual({
211 ok: false,
212 error: "remote_unknown",
213 });
214 // And a different repository answering to the name is refused.
215 app.db.query("UPDATE repo SET origin_remote_id = 'other-id' WHERE name = 'widgets'").run();
216 expect(await reattachMirror(app, alice(), widgets(), id)).toEqual({
217 ok: false,
218 error: "origin_cannot_see",
219 });
220 app.db.query("UPDATE repo SET origin_remote_id = ?1 WHERE name = 'widgets'").run(kept);
221
222 const missing = await api("/api/v1/repos/alice/widgets/origin/reconnect", {
223 method: "POST",
224 body: "{}",
225 });
226 expect(missing.status).toBe(400);
227
228 const done = await api("/api/v1/repos/alice/widgets/origin/reconnect", {
229 method: "POST",
230 body: JSON.stringify({ originId: id }),
231 });
232 expect(done.status).toBe(200);
233 const repo = (await (await api("/api/v1/repos/alice/widgets")).json()) as {
234 origin: { detached: boolean; fullName: string };
235 };
236 expect(repo.origin.detached).toBe(false);
237 expect(repo.origin.fullName).toBe("octo/widgets");
238 expect(
239 app.db
240 .query("SELECT 1 FROM event WHERE kind = 'origin.mirror_reattached'")
241 .get(),
242 ).not.toBeNull();
243
244 // Again: nothing is detached any more.
245 expect(
246 (await reattachMirror(app, alice(), widgets(), id)),
247 ).toEqual({ ok: false, error: "not_detached" });
248
249 expect(await (await api("/alice/widgets")).text()).not.toContain("Frozen:");
250 const card = await (await api("/alice/widgets-fork")).text();
251 expect(card).not.toContain("Its upstream is frozen");
252 expect(card).toContain("Everything here is up to date");
253 });
254
255 test("connecting an origin again re-attaches every detached mirror of that host and says which", async () => {
256 // Detach again by deleting the origin the last test attached to.
257 const current = widgets().origin!.originId;
258 await api(`/api/v1/user/origins/${current}`, { method: "DELETE" });
259 expect(widgets().origin).toBeNull();
260
261 const connected = await connectOrigin(app, alice(), {
262 host: fake.url,
263 token: TOKEN,
264 });
265 if (!connected.ok) throw new Error(connected.error);
266 expect(connected.value.reattached.map((r) => r.repo)).toEqual([
267 "alice/widgets",
268 ]);
269 expect(widgets().origin?.originId).toBe(connected.value.id);
270
271 // The web connect names them in its flash.
272 await api(`/api/v1/user/origins/${connected.value.id}`, { method: "DELETE" });
273 const posted = await fetch(`${servers.url}/settings/origins/token`, {
274 method: "POST",
275 redirect: "manual",
276 headers: {
277 authorization: auth,
278 origin: servers.url,
279 "content-type": "application/x-www-form-urlencoded",
280 },
281 body: new URLSearchParams({ host: fake.url, token: TOKEN }).toString(),
282 });
283 expect(posted.status).toBe(303);
284 const flash = await (
285 await fetch(`${servers.url}/settings/origins`, {
286 headers: { authorization: auth, cookie: posted.headers.get("set-cookie") ?? "" },
287 })
288 ).text();
289 expect(flash).toContain("alice/widgets");
290 expect(widgets().origin).not.toBeNull();
291 });
292
293 test("an origin that needs re-authorizing is said on the mirror, the origins page and the feed", async () => {
294 const originId = widgets().origin!.originId;
295 markNeedsReauth(app.db, originId, "the token was refused");
296 expect(await (await api("/alice/widgets")).text()).toContain(
297 "needs re-authorizing",
298 );
299 expect(await (await api("/settings/origins")).text()).toContain(
300 "one mirror is",
301 );
302 const items = candidatesFor(app.db, alice(), Date.now());
303 const decision = items.find((c) => c.id === `decision:reauth:${originId}`);
304 expect(decision?.said).toContain("needs re-authorizing; 1 mirror is frozen");
305 expect(decision?.kind).toBe("decision");
306 });
307
308 /** Disconnect nothing: connect `forge` and return its id, for the manual path. */
309 async function connectSilently(forge: FakeForge): Promise<string> {
310 // `connectOrigin` would re-attach on its own — which is the next test's
311 // subject — so store the row without that step.
312 const { createOrigin } = await import("../src/core/origins.ts");
313 const made = createOrigin(app.db, dataDir, {
314 userId: alice().id,
315 kind: "forgejo",
316 apiUrl: forge.apiUrl,
317 webUrl: forge.url,
318 login: LOGIN,
319 token: TOKEN,
320 });
321 if (!made.ok) throw new Error(made.error);
322 return made.value.id;
323 }
324 });
test/origins.test.ts +6 −2
@@ -735,8 +735,12 @@ describe("origins: connecting, mirroring, writing through", () => {
735735 origin: unknown;
736736 };
737737 expect(repo.name).toBe("widgets");
738 // The link is gone; everything it pointed at is still here.
739 expect(repo.origin).toBeNull();
738 // The link is gone, and the repo says so; everything it pointed at is
739 // still here.
740 expect(repo.origin).toMatchObject({
741 fullName: "octo/widgets",
742 detached: true,
743 });
740744 const row = app.db
741745 .query<
742746 { origin_id: string | null; origin_full_name: string | null },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs