@niwa-labs/forge 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,158 @@
1
+ /** The repositories the forge watches, the merges the server holds for later, and the pull requests with their pipelines. */
2
+
3
+ import { HostCallError, useAction, useCall } from "@niwa-labs/cockpit-sdk";
4
+ import { Button, CopyValue, DataValue, StateRing } from "@niwa-labs/ui-kit";
5
+
6
+ import { cancelMergeAction, pendingAction, prListAction, repoListAction, repoSyncAction, type ObservedPr, type PendingMerge, type Repo } from "./actions.ts";
7
+ import { CHECKS_LABEL, CHECKS_RING, MODE_LABEL, PIPELINE_RING, PIPELINE_STATUS, PR_STATUS, armedBy, byRepo, cancelInput, pipelineText, prKey, prLabel, repoLabel } from "./pulls.ts";
8
+
9
+ const REFRESH = { refreshOn: { types: ["forge.*"] } };
10
+
11
+ function errorStatus(error: Error): string {
12
+ if (!(error instanceof HostCallError)) return "Проверьте подключение к хосту.";
13
+ if (error.status === 401 || error.status === 403) return "Доступ ограничен.";
14
+ return `Код ответа ${error.status}.`;
15
+ }
16
+
17
+ function RepoRow({ repo }: { repo: Repo }) {
18
+ const sync = useAction(repoSyncAction);
19
+ return (
20
+ <li data-slot="repo-row" className="flex min-w-0 flex-wrap items-center gap-3 py-2">
21
+ <DataValue value={repoLabel(repo)} />
22
+ <Button className="ml-auto" variant="outline" size="sm" disabled={sync.isPending} onClick={() => sync.mutate({ repo: { host: repo.host, path: repo.path } })}>
23
+ Синхронизировать
24
+ </Button>
25
+ {sync.isError ? <span role="alert" className="text-xs text-destructive">Не удалось синхронизировать репозиторий. {errorStatus(sync.error)}</span> : null}
26
+ {sync.data === undefined ? null : <span className="text-xs text-muted-foreground">{sync.data.written} записей обновлено</span>}
27
+ </li>
28
+ );
29
+ }
30
+
31
+ function ArmedCard({ pending, title }: { pending: PendingMerge; title: string | undefined }) {
32
+ const cancel = useAction(cancelMergeAction);
33
+ const input = cancelInput(pending);
34
+ return (
35
+ <li data-slot="armed-merge" data-mode={pending.mode} className="min-w-0" style={{ display: "grid", gridTemplateColumns: "auto minmax(0, 1fr)", alignItems: "start", columnGap: "0.75rem", paddingBlock: "0.6rem" }}>
36
+ <StateRing state="waiting" label="Слияние отложено" />
37
+ <div className="flex min-w-0 flex-col gap-1">
38
+ <span className="break-words text-sm font-medium">
39
+ {prLabel(pending.pr)}
40
+ {title === undefined ? "" : ` · ${title}`}
41
+ </span>
42
+ <p className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">{MODE_LABEL[pending.mode]} <CopyValue value={pending.expectHead} label={`Коммит ${pending.expectHead.slice(0, 8)}`} /></p>
43
+ {input === undefined ? (
44
+ <span className="text-xs text-muted-foreground">Отмена доступна через другое действие</span>
45
+ ) : (
46
+ <div>
47
+ <Button variant="outline" size="sm" disabled={cancel.isPending} onClick={() => cancel.mutate(input)}>
48
+ Отменить слияние
49
+ </Button>
50
+ </div>
51
+ )}
52
+ {cancel.isError ? <span role="alert" className="text-xs text-destructive">Не удалось отменить слияние. {errorStatus(cancel.error)}</span> : null}
53
+ {cancel.data?.cancelled === false ? <span role="status" className="text-xs text-muted-foreground">На сервере уже нет отложенного слияния.</span> : null}
54
+ </div>
55
+ </li>
56
+ );
57
+ }
58
+
59
+ function PrRow({ one, armed }: { one: ObservedPr; armed: PendingMerge | undefined }) {
60
+ return (
61
+ <li data-slot="pr-row" data-state={one.state} className="flex min-w-0 flex-col gap-1 py-2">
62
+ <div className="min-w-0" style={{ display: "grid", gridTemplateColumns: "auto minmax(0, 1fr)", alignItems: "start", columnGap: "0.75rem" }}>
63
+ <StateRing state={CHECKS_RING[one.checks]} label={CHECKS_LABEL[one.checks]} />
64
+ <div className="flex min-w-0 flex-col gap-1">
65
+ <p className="break-words text-sm font-medium">{one.title}</p>
66
+ <p className="desk-tools text-xs text-muted-foreground">
67
+ <CopyValue value={prLabel(one.pr)} />
68
+ <span className="break-all">{one.branch} → {one.base}</span>
69
+ <span>{one.draft ? "Черновик" : PR_STATUS[one.state]}</span>
70
+ {armed === undefined ? null : <span>Слияние отложено</span>}
71
+ <span className={one.checks === "red" ? "font-medium text-destructive" : "font-medium text-foreground"}>{CHECKS_LABEL[one.checks]}</span>
72
+ </p>
73
+ </div>
74
+ </div>
75
+ {one.pipelines.length === 0 ? null : (
76
+ <ul data-slot="pipelines" className="ml-6 flex flex-col gap-0.5">
77
+ {one.pipelines.map((pipeline) => (
78
+ <li key={pipeline.pipeline} className="desk-tools text-xs text-muted-foreground">
79
+ <StateRing state={PIPELINE_RING[pipeline.state]} label={PIPELINE_STATUS[pipeline.state]} />
80
+ <span className="font-mono">{pipelineText(pipeline)}</span>
81
+ <span>{PIPELINE_STATUS[pipeline.state]}</span>
82
+ </li>
83
+ ))}
84
+ </ul>
85
+ )}
86
+ </li>
87
+ );
88
+ }
89
+
90
+ function Failed({ what, error }: { what: string; error: Error }) {
91
+ return <p role="alert" className="text-sm text-destructive">Не удалось загрузить {what}. {errorStatus(error)}</p>;
92
+ }
93
+
94
+ export function ForgePage() {
95
+ const repos = useCall(repoListAction, {}, REFRESH);
96
+ const pending = useCall(pendingAction, {}, REFRESH);
97
+ const prs = useCall(prListAction, {}, REFRESH);
98
+ const titles = new Map((prs.data?.items ?? []).map((one) => [prKey(one.pr), one.title]));
99
+ const armed = armedBy(pending.data?.items ?? []);
100
+ return (
101
+ <div className="desk-page">
102
+ <section className="flex min-w-0 flex-col gap-2">
103
+ {prs.isPending ? (
104
+ <p className="text-sm text-muted-foreground">Загружаем запросы на слияние…</p>
105
+ ) : prs.isError ? (
106
+ <Failed what="запросы на слияние" error={prs.error} />
107
+ ) : prs.data.items.length === 0 ? (
108
+ <p className="text-sm text-muted-foreground">В подключённых репозиториях ещё нет наблюдаемых запросов.</p>
109
+ ) : (
110
+ byRepo(prs.data.items).map((group) => (
111
+ <div key={repoLabel(group.repo)} data-slot="repo-prs" className="flex min-w-0 flex-col gap-1">
112
+ <h4 className="text-xs text-muted-foreground"><DataValue value={repoLabel(group.repo)} /></h4>
113
+ <ul className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
114
+ {group.prs.map((one) => (
115
+ <PrRow key={prKey(one.pr)} one={one} armed={armed.get(prKey(one.pr))} />
116
+ ))}
117
+ </ul>
118
+ </div>
119
+ ))
120
+ )}
121
+ </section>
122
+
123
+ <section className="flex min-w-0 flex-col gap-2">
124
+ <h3 className="text-sm font-semibold text-muted-foreground">Отложенные слияния</h3>
125
+ {pending.isPending ? (
126
+ <p className="text-sm text-muted-foreground">Загружаем отложенные слияния…</p>
127
+ ) : pending.isError ? (
128
+ <Failed what="отложенные слияния" error={pending.error} />
129
+ ) : pending.data.items.length === 0 ? (
130
+ <p className="text-sm text-muted-foreground">Отложенных слияний нет.</p>
131
+ ) : (
132
+ <ul data-slot="armed-merges" className="divide-y rounded-lg border bg-card px-3">
133
+ {pending.data.items.map((one) => (
134
+ <ArmedCard key={one.externalId} pending={one} title={titles.get(prKey(one.pr))} />
135
+ ))}
136
+ </ul>
137
+ )}
138
+ </section>
139
+
140
+ <section className="flex min-w-0 flex-col gap-2">
141
+ <h3 className="text-sm font-semibold text-muted-foreground">Подключённые репозитории</h3>
142
+ {repos.isPending ? (
143
+ <p className="text-sm text-muted-foreground">Загружаем репозитории…</p>
144
+ ) : repos.isError ? (
145
+ <Failed what="репозитории" error={repos.error} />
146
+ ) : repos.data.items.length === 0 ? (
147
+ <p className="text-sm text-muted-foreground">Подключите репозиторий GitLab, чтобы видеть запросы на слияние и проверки.</p>
148
+ ) : (
149
+ <ul data-slot="repos" className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
150
+ {repos.data.items.map((repo) => (
151
+ <RepoRow key={`${repo.host}/${String(repo.projectId)}`} repo={repo} />
152
+ ))}
153
+ </ul>
154
+ )}
155
+ </section>
156
+ </div>
157
+ );
158
+ }
@@ -0,0 +1,103 @@
1
+ /** What the forge page makes of the pull requests, their pipelines and the merges the server holds for later. */
2
+
3
+ import type { WorkState } from "@niwa-labs/ui-kit";
4
+
5
+ import { cancelMergeAction } from "./actions.ts";
6
+ import type { ChecksState, ObservedPr, PendingMerge, PipelineKind, PrPipeline, PrRef, Repo, RunState } from "./actions.ts";
7
+
8
+ /** A pull request as the server names it: `acme/billing!7`. */
9
+ export function prLabel(pr: PrRef): string {
10
+ return `${pr.repo.path}!${String(pr.number)}`;
11
+ }
12
+
13
+ /** One text for one pull request: projects are told apart by their id, which a rename keeps. */
14
+ export function prKey(pr: PrRef): string {
15
+ return `${pr.repo.host}/${String(pr.repo.projectId)}!${String(pr.number)}`;
16
+ }
17
+
18
+ export function repoLabel(repo: Pick<Repo, "host" | "path">): string {
19
+ return `${repo.host}/${repo.path}`;
20
+ }
21
+
22
+ export const CHECKS_RING: Readonly<Record<ChecksState, WorkState>> = { none: "pending", pending: "running", green: "done", red: "failed" };
23
+
24
+ export const CHECKS_LABEL: Readonly<Record<ChecksState, string>> = { none: "Нет проверок", pending: "Проверки идут", green: "Проверки пройдены", red: "Проверки не пройдены" };
25
+
26
+ export const PIPELINE_RING: Readonly<Record<RunState, WorkState>> = {
27
+ created: "pending",
28
+ waiting_for_resource: "waiting",
29
+ preparing: "running",
30
+ pending: "pending",
31
+ running: "running",
32
+ success: "done",
33
+ failed: "failed",
34
+ canceled: "stopped",
35
+ skipped: "skipped",
36
+ manual: "waiting",
37
+ scheduled: "pending",
38
+ };
39
+
40
+ export const PR_STATUS: Readonly<Record<ObservedPr["state"], string>> = {
41
+ open: "Открыт",
42
+ merged: "Слит",
43
+ closed: "Закрыт",
44
+ };
45
+
46
+ export const PIPELINE_STATUS: Readonly<Record<RunState, string>> = {
47
+ created: "Создан",
48
+ waiting_for_resource: "Ждёт ресурса",
49
+ preparing: "Подготовка",
50
+ pending: "В очереди",
51
+ running: "Выполняется",
52
+ success: "Успешно",
53
+ failed: "Ошибка",
54
+ canceled: "Отменён",
55
+ skipped: "Пропущен",
56
+ manual: "Ждёт ручного запуска",
57
+ scheduled: "Запланирован",
58
+ };
59
+
60
+ const KIND_LABEL: Readonly<Record<PipelineKind, string>> = {
61
+ head: "коммит",
62
+ "merge-result": "результат слияния",
63
+ train: "очередь слияния",
64
+ branch: "ветка",
65
+ tag: "тег",
66
+ schedule: "по расписанию",
67
+ };
68
+
69
+ const short = (sha: string): string => sha.slice(0, 8);
70
+
71
+ /** A pipeline in a line: its number, what it ran on, and for a merge result the pair of commits it was made of. */
72
+ export function pipelineText(pipeline: PrPipeline): string {
73
+ const what = KIND_LABEL[pipeline.kind];
74
+ const pair = pipeline.targetSha === undefined ? short(pipeline.sourceSha) : `${short(pipeline.sourceSha)} → ${short(pipeline.targetSha)}`;
75
+ return `#${String(pipeline.pipeline)} ${what} ${pair}`;
76
+ }
77
+
78
+ /** The merges the server holds, by the pull request they are for. */
79
+ export function armedBy(pending: readonly PendingMerge[]): Map<string, PendingMerge> {
80
+ return new Map(pending.map((one) => [prKey(one.pr), one]));
81
+ }
82
+
83
+ export const MODE_LABEL: Readonly<Record<PendingMerge["mode"], string>> = { "auto-merge": "Слияние после успешных проверок", train: "В очереди слияния" };
84
+
85
+ /**
86
+ * What cancelling a merge sends: the input the host gave with it, as it is, and only when the action it names is the one
87
+ * the page knows how to call. A merge held by another action is shown, not cancelled from here.
88
+ */
89
+ export function cancelInput(pending: PendingMerge): { repo: { host: string; path: string }; number: number } | undefined {
90
+ return pending.cancel.action === cancelMergeAction.name ? pending.cancel.input : undefined;
91
+ }
92
+
93
+ /** The pull requests by repository, in the order they came, and each repository where its first pull request stands. */
94
+ export function byRepo(prs: readonly ObservedPr[]): Array<{ repo: Repo; prs: ObservedPr[] }> {
95
+ const groups = new Map<string, { repo: Repo; prs: ObservedPr[] }>();
96
+ for (const one of prs) {
97
+ const key = `${one.pr.repo.host}/${String(one.pr.repo.projectId)}`;
98
+ const group = groups.get(key);
99
+ if (group === undefined) groups.set(key, { repo: one.pr.repo, prs: [one] });
100
+ else group.prs.push(one);
101
+ }
102
+ return [...groups.values()];
103
+ }
package/src/flow.ts ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The script helpers of the forge module: wait for the pipeline of a commit, land a pull request, wait
3
+ * for a pull request to end or for its head to move. They wait for the queries of `./queries.ts`.
4
+ *
5
+ * They run inside a workflow script and use its globals (`call`, `wait`, `now`, `race`), read when a
6
+ * helper is called, so this file imports nothing of the script runtime. Every call a helper makes is
7
+ * labeled from the key it is given: a replay of the script finds each answer where it left it, and
8
+ * two helpers in one script need two keys.
9
+ */
10
+
11
+ import type { TypeQuery } from "@niwa-labs/core";
12
+ import type { z } from "zod";
13
+
14
+ import { forgePipelineRead, forgePrMerge, forgePrRead } from "./actions.ts";
15
+ import type { MergeOutcome, PullRequest } from "./actions.ts";
16
+ import { verdictOf as stateVerdict } from "./normalize.ts";
17
+ import type { Pipeline, PipelineKind, PrClosed, PrMerged } from "./record-types.ts";
18
+ import { mergeDisarmed, pipelineOf, prClosed, prHead, prMerged } from "./queries.ts";
19
+ import type { RepoName } from "./targets.ts";
20
+
21
+ /** A duration as a script writes it: milliseconds, or "500ms", "30s", "5m", "2h", "1d". */
22
+ export type Duration = number | string;
23
+
24
+ interface Labeled {
25
+ label?: string;
26
+ }
27
+
28
+ /** What the helpers take of a script's globals. */
29
+ interface ScriptGlobals {
30
+ call(name: string, input: unknown, opts?: Labeled): Promise<any>;
31
+ wait<D>(query: TypeQuery<D>, opts: { from?: number; timeout?: Duration; label?: string }): Promise<{ data: D; at: number } | { timedOut: true }>;
32
+ now(opts?: Labeled): Promise<number>;
33
+ race<K extends string, T>(name: string, branches: Record<K, () => Promise<T>>): Promise<{ key: K; value: T }>;
34
+ }
35
+
36
+ /** What a wait answers when the data's type does not matter: the branches of a race answer alike. */
37
+ type Waited = { data: unknown; at: number } | { timedOut: true };
38
+
39
+ /** The globals of the script that calls a helper. */
40
+ function script(): ScriptGlobals {
41
+ const globals = globalThis as unknown as Partial<ScriptGlobals>;
42
+ for (const name of ["call", "wait", "now", "race"] as const) {
43
+ if (typeof globals[name] !== "function") throw new Error(`@niwa-labs/forge/flow runs inside a workflow script: "${name}" is not a global here`);
44
+ }
45
+ return globals as ScriptGlobals;
46
+ }
47
+
48
+ const UNITS: Record<string, number> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
49
+
50
+ /** A duration in milliseconds. */
51
+ export function durationMs(duration: Duration): number {
52
+ if (typeof duration === "number") return duration;
53
+ const parsed = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(duration.trim());
54
+ if (parsed === null) throw new TypeError(`not a duration: ${JSON.stringify(duration)} (milliseconds, or a number with ms, s, m, h or d)`);
55
+ return Number(parsed[1]) * (UNITS[parsed[2] as string] as number);
56
+ }
57
+
58
+ /**
59
+ * The repository as the actions name it, `{ host, path }`: a record holds more (the project id), and
60
+ * an action takes no more than its target names.
61
+ */
62
+ function nameOf(repo: RepoName): RepoName {
63
+ return { host: repo.host, path: repo.path };
64
+ }
65
+
66
+ /** How long one wait lasts before the helper reads the server again. */
67
+ const ROUND_MS = 300_000;
68
+
69
+ /** What became of the pipeline of a commit. */
70
+ export type PipelineOutcome = { outcome: "green" | "red" | "timed-out"; pipeline?: number };
71
+
72
+ /**
73
+ * What the latest pipeline of a list says, as the checks of a pull request say it: green or red, or
74
+ * undefined while it is pending (a pipeline that waits on a manual job too) or was skipped.
75
+ */
76
+ function verdictOf(items: readonly Pipeline[]): PipelineOutcome | undefined {
77
+ const latest = [...items].sort((a, b) => b.pipeline - a.pipeline)[0];
78
+ if (latest === undefined) return undefined;
79
+ const verdict = stateVerdict(latest.state);
80
+ return verdict === "green" || verdict === "red" ? { outcome: verdict, pipeline: latest.pipeline } : undefined;
81
+ }
82
+
83
+ /**
84
+ * Wait until the latest pipeline of a commit is green (success) or red (a failure or a cancel), or
85
+ * `timed-out` at the deadline: a pipeline that waits on a manual job is still pending. `kind` takes only pipelines of that kind (a merge result, say),
86
+ * matched by the commit of the change they ran for. The server is read first, so a pipeline that
87
+ * settled before the call answers at once; then the helper waits for the module's records of the
88
+ * commit and reads again, which also keeps the repository polled at its fastest while it waits.
89
+ */
90
+ export async function untilPipeline(
91
+ key: string,
92
+ opts: { repo: RepoName; sha: string; kind?: PipelineKind; deadline: Duration },
93
+ ): Promise<PipelineOutcome> {
94
+ const api = script();
95
+ const started = await api.now({ label: `${key}-start` });
96
+ const until = started + durationMs(opts.deadline);
97
+ const repo = nameOf(opts.repo);
98
+ const query = pipelineOf({ repo, sha: opts.sha, ...(opts.kind === undefined ? {} : { kind: opts.kind }) });
99
+ let from: number | undefined;
100
+ for (let round = 1; ; round += 1) {
101
+ const read = await api.call(forgePipelineRead.name, { repo, sha: opts.sha, ...(opts.kind === undefined ? {} : { kind: opts.kind }) }, { label: `${key}-read-${String(round)}` });
102
+ const settled = verdictOf((read as { items: Pipeline[] }).items);
103
+ if (settled !== undefined) return settled;
104
+ const now = await api.now({ label: `${key}-now-${String(round)}` });
105
+ if (now >= until) return { outcome: "timed-out" };
106
+ const waited = await api.wait(query, {
107
+ ...(from === undefined ? {} : { from }),
108
+ timeout: Math.min(ROUND_MS, until - now),
109
+ label: `${key}-wait-${String(round)}`,
110
+ });
111
+ if (!("timedOut" in waited)) from = waited.at;
112
+ }
113
+ }
114
+
115
+ /** A pull request a helper is given. */
116
+ export interface PrRefGiven {
117
+ readonly repo: RepoName;
118
+ readonly number: number;
119
+ }
120
+
121
+ /** What became of a landing. */
122
+ export type LandOutcome = { outcome: "merged"; sha: string } | { outcome: "refused" | "queued-unknown"; why: string };
123
+
124
+ /**
125
+ * Merge a pull request at the head the caller expects. With `auto`, the server is armed to merge when
126
+ * the pipeline succeeds and the helper waits for the merge, until `deadline` (default 2h): a pull
127
+ * request merged at another head, closed, or called off is refused; still waiting at the deadline is
128
+ * `queued-unknown`, for the server still has it.
129
+ *
130
+ * The module's records of the merge are waited for in rounds, and between rounds the pull request is
131
+ * read from the server (`forge.pr.read` on the repository must be in the script's `uses`): a merge
132
+ * recorded before the waits began, or never recorded because the repository is not watched, is found
133
+ * by the read, and so is a merge the server dropped without a record.
134
+ */
135
+ export async function land(
136
+ key: string,
137
+ opts: { pr: PrRefGiven; expectHead: string; expectTarget?: string; method: "merge" | "squash" | "rebase"; auto?: boolean; deadline?: Duration },
138
+ ): Promise<LandOutcome> {
139
+ const api = script();
140
+ const repo = nameOf(opts.pr.repo);
141
+ const asked = (await api.call(
142
+ forgePrMerge.name,
143
+ { repo, number: opts.pr.number, expectHead: opts.expectHead, ...(opts.expectTarget === undefined ? {} : { expectTarget: opts.expectTarget }), method: opts.method, when: opts.auto === true ? "pipeline" : "now" },
144
+ { label: `${key}-merge` },
145
+ )) as MergeOutcome;
146
+ if (asked.outcome === "merged") return { outcome: "merged", sha: asked.sha };
147
+ if (asked.outcome === "refused") return { outcome: "refused", why: asked.why };
148
+ const pr = { repo, number: opts.pr.number };
149
+ const started = await api.now({ label: `${key}-start` });
150
+ const until = started + durationMs(opts.deadline ?? "2h");
151
+ const mergedAt = (head: string | undefined, sha: string | undefined): LandOutcome =>
152
+ head !== undefined && head !== opts.expectHead
153
+ ? { outcome: "refused", why: `${asked.externalId} was merged at ${head}, not at ${opts.expectHead}` }
154
+ : { outcome: "merged", sha: sha ?? opts.expectHead };
155
+ for (let round = 1; ; round += 1) {
156
+ const now = round === 1 ? started : await api.now({ label: `${key}-now-${String(round)}` });
157
+ if (now >= until && round > 1) return { outcome: "queued-unknown", why: `the server took the merge as ${asked.externalId} and has not made it yet` };
158
+ const timeout = Math.max(1, Math.min(ROUND_MS, until - now));
159
+ const ended = await api.race<"merged" | "closed" | "disarmed", Waited>(`${key}-end-${String(round)}`, {
160
+ merged: () => api.wait(prMerged(pr), { timeout, label: `${key}-merged-${String(round)}` }),
161
+ closed: () => api.wait(prClosed(pr), { timeout, label: `${key}-closed-${String(round)}` }),
162
+ disarmed: () => api.wait(mergeDisarmed(pr), { timeout, label: `${key}-disarmed-${String(round)}` }),
163
+ });
164
+ const waited = ended.value;
165
+ if (!("timedOut" in waited)) {
166
+ if (ended.key === "closed") return { outcome: "refused", why: `${asked.externalId} was closed before the server merged it` };
167
+ if (ended.key === "disarmed") return { outcome: "refused", why: `the merge of ${asked.externalId} was called off` };
168
+ const merged = waited.data as z.output<typeof PrMerged.schema>;
169
+ return mergedAt(merged.head, merged.mergeSha);
170
+ }
171
+ const read = (await api.call(forgePrRead.name, { repo, number: opts.pr.number }, { label: `${key}-read-${String(round)}` })) as PullRequest;
172
+ if (read.state === "merged") return mergedAt(read.head, read.mergeSha);
173
+ if (read.state === "closed") return { outcome: "refused", why: `${asked.externalId} was closed before the server merged it` };
174
+ if (read.state === "open" && !read.autoMerge) return { outcome: "refused", why: `the server no longer holds the merge of ${asked.externalId}` };
175
+ }
176
+ }
177
+
178
+ /** What became of the head of a pull request while a script waited for it to move. */
179
+ export type HeadMove = { moved: true; head: string; previous?: string; at: number } | { moved: false };
180
+
181
+ /**
182
+ * Wait until the head of a pull request moves (new commits, a rebase, a force push) after `from`, a
183
+ * position an earlier wait or read answered, or after the wait began; `moved: false` at the timeout.
184
+ * Without a timeout it waits for ever. It waits for the module's record of the move, so the repository
185
+ * must be watched; `at` is the position to wait on from.
186
+ */
187
+ export async function untilHeadMoved(key: string, opts: { pr: PrRefGiven; from?: number; timeout?: Duration }): Promise<HeadMove> {
188
+ const waited = await script().wait(prHead({ repo: nameOf(opts.pr.repo), number: opts.pr.number }), {
189
+ ...(opts.from === undefined ? {} : { from: opts.from }),
190
+ ...(opts.timeout === undefined ? {} : { timeout: opts.timeout }),
191
+ label: key,
192
+ });
193
+ if ("timedOut" in waited) return { moved: false };
194
+ const { head, previous } = waited.data;
195
+ return { moved: true, head, ...(previous === undefined ? {} : { previous }), at: waited.at };
196
+ }
197
+
198
+ /** How a pull request ended while a script waited for it: merged or closed, and where, or not by the timeout. */
199
+ export type PrEnd =
200
+ | { ended: "merged"; head?: string; mergeSha?: string; by?: string; at: number }
201
+ | { ended: "closed"; by?: string; at: number }
202
+ | { ended: false };
203
+
204
+ /**
205
+ * Wait until a pull request is merged or closed after `from`, a position an earlier wait or read
206
+ * answered, or after the wait began: whichever the module records first answers at once, and the other
207
+ * wait is cancelled. `ended: false` at the timeout; without one it waits for ever. It waits for the
208
+ * module's records, so the repository must be watched; `at` is the position of the record.
209
+ */
210
+ export async function untilPrEnded(key: string, opts: { pr: PrRefGiven; from?: number; timeout?: Duration }): Promise<PrEnd> {
211
+ const api = script();
212
+ const pr = { repo: nameOf(opts.pr.repo), number: opts.pr.number };
213
+ const how = { ...(opts.from === undefined ? {} : { from: opts.from }), ...(opts.timeout === undefined ? {} : { timeout: opts.timeout }) };
214
+ const ended = await api.race<"merged" | "closed", Waited>(key, {
215
+ merged: () => api.wait(prMerged(pr), { ...how, label: `${key}-merged` }),
216
+ closed: () => api.wait(prClosed(pr), { ...how, label: `${key}-closed` }),
217
+ });
218
+ const waited = ended.value;
219
+ if ("timedOut" in waited) return { ended: false };
220
+ if (ended.key === "closed") {
221
+ const { by } = waited.data as z.output<typeof PrClosed.schema>;
222
+ return { ended: "closed", ...(by === undefined ? {} : { by }), at: waited.at };
223
+ }
224
+ const { head, mergeSha, by } = waited.data as z.output<typeof PrMerged.schema>;
225
+ return {
226
+ ended: "merged",
227
+ ...(head === undefined ? {} : { head }),
228
+ ...(mergeSha === undefined ? {} : { mergeSha }),
229
+ ...(by === undefined ? {} : { by }),
230
+ at: waited.at,
231
+ };
232
+ }