Files
mesh-catalog/modules/gitea/index.ts
T
jschoubben 6b17965d98 C5: forge_merged lists a repository's merged pull requests by number
From..to inclusive, each read from the forge one by one, with its merge
commit, when it was merged and the merge call that made it when a kept call
names it merged; at most 768 KB, capped with the next number as the cursor.

Builds: design 47 H2 §812, §811; H-A-402
2026-11-22 00:52:01 +01:00

511 lines
32 KiB
TypeScript

// gitea's events. The tool runtime imports this once the broker is bound. It watches the forge and
// emits what appeared.
//
// Emits (novox/hq ADR 0041/0042):
// module.gitea.repo.created — a repository appeared, however it was made (push, web UI, or tool)
// module.gitea.pull.merged — a pull request was merged, however it was merged (web UI, API, or tool)
// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to, said from the forge's event alone
//
// module.gitea.pull.closed — a pull request closed unmerged: the delivery it was is stopped (novox/hq ADR 0239)
//
// It consumes no event of the controller: no controller judges a merge (ADR 0524 §5, ADR 0571 clause 13), and the two older
// statuses, `mesh/merge-gate` and `mesh/repo-check`, are written for no base that main requires (issue 1301); main
// requires `mesh/check`, the checker's, everywhere, hq included since ADR 0527 §2.
//
// It reads no other module's state: mesh/check, and every act of a delivery part on the forge, arrive as verbs of the seat
// git (seat.ts), asked by the forge bridge (novox/hq design 47 *The seat git*).
//
// No merge check is asked, weighed or written here (design 47 H §764; H-A-28, H-A-100): a merge is one merge call of the
// seat git (mergecall.ts), its members judged by their heads and failed steps alone.
//
// Every pull request the forge holds is announced, whatever its repository: the controller holds the
// module graph and decides what is checked — a repository is never asked to opt in.
//
// issue.opened is emitted from its tool (tools/index.ts). repo.created and pull.merged belong here: a
// repository or a merge is as often made by the web UI or a plain API call, which no tool sees, so
// polling is the only way to catch every path — and the only emitter, so a fact is never announced
// twice. The merge tool announced too until novox/hq issue 250, and every merge it made was heard twice.
//
// The polling is deliberately unhurried: an event a minute late is still an event, whereas hammering
// the forge for an immediacy nobody asked for is not.
import { emit } from "@novox/mesh-sdk/events";
import { registerModuleTools } from "@novox/mesh-sdk/tools";
import { statesAnnouncement } from "./kept.js";
import { state, TAKEN_STATE } from "@novox/mesh-sdk/state";
import { on } from "@novox/mesh-sdk/events";
import { broker } from "@novox/mesh-sdk/messaging";
import { STATUS_STATE, keepStatus, statusTools, viewWaitsFinding, type Follower, type Status } from "@novox/mesh-sdk/views";
import type { CatalogRevisionEvent, RegistrationChangedEvent, RevisionInput } from "@novox/mesh-delivery-contracts-mesh-catalog";
import { CATALOG_REVISION_EVENT, CatalogView, findingValue, unansweredFinding } from "./catalog.js";
import { announce, keepWatermark, readWatermark } from "./announce.js";
import { SEAT_ONLY, sayOnSeat } from "./seatevents.js";
import { FORGE_CONTAINER, seatTools } from "./seat.js";
import { REGISTRATION_CHANGED_EVENT, Registrations } from "./registrations.js";
import { FailedSteps, Heads, readHeads } from "./failedsteps.js";
import { failedStepsTools } from "./tools/failedsteps.js";
import { Calls, callRetentionDays, sayUnsaid } from "./calls.js";
import { Once, askTakenBoundMs, takenState } from "./taken.js";
import { Partials } from "./partials.js";
import { callTools, mergedTool } from "./tools/calls.js";
import { seatPublish } from "@novox/mesh-sdk/runtime";
import { seat as GIT, events as GIT_EVENTS, type BranchMovedEvent, type PullClosedEvent, type PullMergedEvent, type PullUpdatedEvent } from "@novox/mesh-delivery-contracts-git";
import { seat as RUNNER, events as RUNNER_EVENTS, type StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner";
import { run } from "./delivery.js";
import { GiteaAdmin, GiteaClient, movedSince } from "./client.js";
import { actOn } from "./watch.js";
import { HOOK_PATH, HOOK_PORT, Pace, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js";
import { bindInBackground, bindUntilHeld } from "./bind.js";
import { announcementOf } from "./updated.js";
import { ReadAll, readAllTools } from "./readall.js";
import { DeliveredWrites, writeTools } from "./writes.js";
import { TOOLS_ACCOUNT, TOOLS_ORG, meshAccounts } from "./tools-account.js";
import { PACKAGES_TOKEN_REFUSED, keepPackagesToken, packagesToken, renewOnRefusal } from "./packages-account.js";
// Without a way to a token — configured, or mintable with the admin account (token.ts) — there is
// nothing to watch; log and stay quiet rather than crash the runtime. With one, the first poll mints
// or reuses the token, so the runtime's start also shows what it did about it.
let gitea: GiteaClient | null = null;
try {
gitea = GiteaClient.fromEnv();
} catch (err) {
console.log(`[gitea] not watching — ${err instanceof Error ? err.message : String(err)}`);
}
// New repositories, by diffing the repo list. Primed silently on the first look, or a restart would
// re-announce every existing repository as freshly created.
const seen = new Set<string>();
let primed = false;
async function pollRepos(client: GiteaClient): Promise<void> {
const repos = await client.listAllRepos();
for (const repo of repos) {
if (!seen.has(repo.full_name)) {
if (primed) {
await emit("repo.created", {
full_name: repo.full_name,
owner: repo.owner,
name: repo.name,
private: repo.private,
html_url: repo.html_url,
});
}
seen.add(repo.full_name);
}
}
primed = true;
}
// **A merge is announced whoever made it.** The merge tool below emits at the instant it acts; a
// merge made in the forge's own pages or over its API would emit nothing, and the mesh would go on
// believing every module current with its source (novox/hq 04-ISSUES/131). So merged pull requests
// are watched the way repositories are: what the forge holds, asked for on a tick, announced once.
// What has been announced is kept beside the module's state, so a restart does not announce the
// whole history again — and the first tick on a machine with no record announces nothing, because
// everything it sees then predates the watching.
import { join } from "node:path";
// What has been announced is no longer kept in a file (novox/hq ADR 0406 §6, §7, issue 976): an announcement carries a
// message id (announce.ts), so the same merge announced by the poll and by the forge's event, or again after a restart,
// is stored once by the bus — within its de-duplication window, and past it the consumers' idempotence per merge commit
// holds. This process remembers what it announced meanwhile, so it does not ask the forge for the same files twice.
// The one value kept is where the poll last looked from (`since`), in the module's own state: a merge made while this
// module was away, after it, is announced when it is back; one before it is history. With none kept — the first look
// ever — nothing is announced, because everything it sees then predates the watching.
const announced = new Set<string>();
let primedMerges = false;
let since = "";
let watermarkRead = false;
// **Only the repositories that moved** (novox/hq issue 250). A merge is a push, and a push moves the
// repository's update time; asking every repository for its pull requests on every tick took longer than the
// tick itself, so ticks piled up and a merge was announced minutes late. A repository unchanged since a
// minute before the last look is skipped — the minute absorbs the forge's clock against this one.
let lastLook = "";
const MARGIN_MS = 60_000;
async function pollMerged(client: GiteaClient): Promise<void> {
if (!watermarkRead) {
since = await readWatermark();
primedMerges = since !== "";
watermarkRead = true;
}
const began = new Date().toISOString();
const floor = lastLook && primedMerges ? new Date(Date.parse(lastLook) - MARGIN_MS).toISOString() : "";
const repos = movedSince(await client.listAllRepos(), floor);
for (const repo of repos) {
const pulls = await client.listPullRequests(repo.owner, repo.name, { state: "closed", sort: "recentupdate", limit: "20" });
for (const pull of pulls) {
// Closed unmerged (novox/hq ADR 0239): announced once, since the watching began, so its delivery stops.
const closedKey = `closed:${repo.full_name}#${pull.number}`;
if (!pull.merged && pull.state === "closed" && !announced.has(closedKey)) {
if (primedMerges && !!pull.updated_at && !!since && pull.updated_at > since) await announceClosed(client, repo, pull);
announced.add(closedKey);
continue;
}
if (!pull.merged || !pull.merge_commit_sha || announced.has(pull.merge_commit_sha)) continue;
// Announced only if merged since the watching began; recorded either way, so it is looked
// at once.
const fresh = !!pull.merged_at && !!since && pull.merged_at > since;
if (primedMerges && fresh) {
if (await announceMerge(client, repo, pull)) pace.miss(`the merge of ${repo.full_name}#${pull.number}`);
}
else announced.add(pull.merge_commit_sha);
announced.add(pull.merge_commit_sha);
}
}
// The next look starts from this one's start less the margin; kept, so a restart looks from there.
since = primedMerges ? new Date(Date.parse(began) - MARGIN_MS).toISOString() : began;
await keepWatermark(since);
primedMerges = true;
lastLook = began;
}
type RepoOf = { owner: string; name: string; full_name: string; clone_url?: string };
type PullOf = Awaited<ReturnType<GiteaClient["listPullRequests"]>>[number];
/** A pull request closed without a merge, announced once (ADR 0239): by its event, or by the start's pass. */
async function announceClosed(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise<boolean> {
const closedKey = `closed:${repo.full_name}#${pull.number}`;
if (pull.merged || pull.state !== "closed" || announced.has(closedKey)) return false;
announced.add(closedKey);
try {
await announce("pull.closed", { owner: repo.owner, repo: repo.name, number: pull.number, title: pull.title,
head: pull.head, head_sha: pull.head_sha, base: pull.base, html_url: pull.html_url });
} catch (err) {
announced.delete(closedKey);
throw err;
}
console.log(`[gitea] announced ${repo.full_name}#${pull.number} closed unmerged`);
return true;
}
/** **A merge, announced once, whichever path saw it first** (novox/hq issue 729): the poll or the forge's event. */
async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise<boolean> {
if (!pull.merged || !pull.merge_commit_sha || announced.has(pull.merge_commit_sha)) return false;
// Recorded before the first wait, so the other path finds it taken while this one is still asking the forge.
announced.add(pull.merge_commit_sha);
try {
// What it changed, asked for only now: a module is rebuilt because a file inside its own
// directory moved, and without this every module built from a repository is rebuilt for a
// change to any of them (novox/hq 04-ISSUES/131).
const changed = await client.listPullFiles(repo.owner, repo.name, pull.number);
// Which of the directories they are in hold a module at the merge commit (novox/hq issue 278): a
// change inside one is that module's, held or not, and only a file in none is shared code. Not
// said when the list is cut or the forge could not be asked; the mesh then keeps its old rule.
let moduleDirs: string[] | null = null;
if (!changed.truncated) {
try {
moduleDirs = await client.moduleDirsAt(repo.owner, repo.name, pull.merge_commit_sha, changed.paths);
} catch (err) {
console.error(`[gitea] ${repo.full_name}#${pull.number}: which directories hold a module could not be read, ` +
`so the mesh reads its files by the old rule — ${err instanceof Error ? err.message : String(err)}`);
}
}
// The head it merged, and what its head was checked as (novox/hq ADR 0239): the delivery it was, made
// from the forge's word when its owner never heard the head.
let headChecks: Record<string, string> | null = null;
if (pull.head_sha) {
try {
headChecks = await client.commitStatuses(repo.owner, repo.name, pull.head_sha);
} catch (err) {
console.error(`[gitea] ${repo.full_name}#${pull.number}: its head's statuses could not be read — ${err instanceof Error ? err.message : err}`);
}
}
await announce("pull.merged", {
owner: repo.owner,
repo: repo.name,
number: pull.number,
title: pull.title,
body: pull.body,
head_sha: pull.head_sha,
...(headChecks ? { head_checks: headChecks } : {}),
head: pull.head,
base: pull.base,
merge_commit_sha: pull.merge_commit_sha,
merged_at: pull.merged_at,
clone_url: repo.clone_url,
html_url: pull.html_url,
paths: changed.paths,
paths_truncated: changed.truncated,
// Which of them the merge deleted (novox/hq ADR 0236): a module whose manifest went is forgotten,
// not built.
removed: changed.removed,
...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}),
});
// Said, because a trigger that fires silently is indistinguishable from one that did not
// fire (novox/hq 04-ISSUES/131) — this line is how an operator knows the mesh was told.
console.log(`[gitea] announced merge ${repo.full_name}#${pull.number} (${pull.merge_commit_sha.slice(0, 8)}) into ${pull.base}`);
} catch (err) {
announced.delete(pull.merge_commit_sha);
throw err;
}
return true;
}
/** **A pull request's new head, said as pull.updated from the forge's event alone** (design 47 H §764; H-A-100): no
* poll, no pending status and no sibling's weighing. */
async function announceUpdated(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise<void> {
await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull));
console.log(`[gitea] said ${repo.full_name}#${pull.number} at ${String(pull.head_sha ?? "").slice(0, 8)} updated`);
}
/** How fast the polls look: 30 s until the forge's events are heard, five minutes while they are; and what
* gitea_events says of them (webhook.ts). */
const pace = new Pace();
/** Asks the pass over every repository again, shortly and once (set where the pass is made): an event that could not be
* acted on is not lost until the next start. */
let catchUp: () => void = () => {};
if (!gitea) pace.unheard("the forge is not watched: no way to a token", false);
// The states this module keeps and which others may read, said on the bus before it serves (novox/hq ADR 0495 clause 2).
// Said with `emit`, not the SDK's `keeps`, which the toolchain's SDK does not have yet: switch to `keeps` once that SDK is 0.1.15 or later (issue 1852).
await emit("states", statesAnnouncement(process.env.MESH_MODULE || "gitea", process.env.MESH_NODE));
// **The mesh's accounts read every repository** (readall.ts; the operator, 2026-10-26): the tools', the build modules'
// and the machines' agents' (meshAccounts, tools-account.ts), granted with the site
// administrator's login, which the module holds for setting the forge up and uses here for that grant alone. Made on
// first use, so a module whose admin login is missing still serves the rest and the tools say why.
let readAllOnce: ReadAll | null = null;
const readAll = (): ReadAll => (readAllOnce ??= new ReadAll(GiteaAdmin.fromEnv(), meshAccounts(process.env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT)));
// **The merging account writes every repository that builds a registered module** (writes.ts; the operator,
// 2026-10-26; issue 1945): which those are is the catalog half's word, followed below. Made on first use, as readAll.
let writesOnce: DeliveredWrites | null = null;
const writes = (): DeliveredWrites => (writesOnce ??= new DeliveredWrites(GiteaAdmin.fromEnv(),
process.env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT, TOOLS_ORG, (l) => console.log(`[gitea] ${l}`), async (type, body) => { await sayOnSeat(type, body as Record<string, unknown>); }));
// The first view of the catalog half (catalog.ts), made once the module follows it (below). Its status is kept in the
// module's state first-views, which gitea_first_views reads; gitea_first_view_again asks it again by hand (mesh-sdk views).
const firstViews = state<Status>(STATUS_STATE);
const followers: Follower[] = [];
// The first registrations switch merge-pull on (registrations.ts; design 47 §95).
const registrations = new Registrations((verb, input) => broker().request(verb, input), (line) => console.log(`[gitea] ${line}`));
// The failed steps the runner's step-ended said, and the heads that keep them (failedsteps.ts; design 47 §39, §475, §487, §135).
const heldHeads = new Heads();
let reloadHeads: () => Promise<void> = async () => {};
// The merge calls, each written before its first merge (calls.ts; design 47 H §766).
const calls = new Calls(state<unknown>("calls"), () => callRetentionDays(), (line) => console.log(`[gitea] ${line}`));
// Each act of the seat git is taken once by its ask id, the ids kept in the state taken for ask-taken-bound (taken.ts;
// design 47 H2 §775).
const once = new Once(takenState(state<unknown>(TAKEN_STATE), askTakenBoundMs(process.env, (line) => console.log(`[gitea] ${line}`))),
(line) => console.log(`[gitea] ${line}`));
// At the start, every call whose merge-called is not said says it for what landed (§766).
const partials = new Partials(state<unknown>("findings"), calls, (line) => console.log(`[gitea] ${line}`));
void sayUnsaid(calls, seatPublish, (line) => console.log(`[gitea] ${line}`)).catch((err) =>
console.error(`[gitea] the merge calls not said could not be said at the start — ${err instanceof Error ? err.message : err}`));
const failedSteps = new FailedSteps(state<unknown>("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit),
undefined, state<unknown>("findings"));
// The `seen` keys past their 30 days are deleted at the start, as on each step-ended (design 47 §581).
void failedSteps.expireSeen().catch((err) => console.log(`[gitea] the seen keys past 30 days could not be deleted at the start: ${err instanceof Error ? err.message : String(err)}`));
// gitea_events is served whether or not the forge is watched: it says so (novox/hq issue 729). The seat git's verbs are
// served here.
registerModuleTools("gitea", () => [eventsTool(pace), ...readAllTools(readAll), ...writeTools(writes), ...statusTools("gitea", "gitea_first_views", "gitea_first_view_again", followers, firstViews,
async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }),
...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, registered: () => registrations.written, judge: (head) => failedSteps.judge(head),
watched: () => registrations.watched, calls, say: seatPublish, partials, once }) : []),
...callTools(calls, partials, seatPublish, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }),
...(gitea ? [mergedTool(gitea, calls)] : []),
...failedStepsTools(failedSteps, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); })]);
/** What the forge's event asks of the announcer at once (issue 729, 1422): see watch.ts. */
const actOnEvent = (client: GiteaClient, event: ForgeEvent): Promise<void> => actOn<RepoOf, PullOf>(event, {
getRepo: (o, r) => client.getRepo(o, r),
getPull: (o, r, n) => client.getPullRequest(o, r, n) as Promise<PullOf & { state?: string; merged?: boolean }>,
announceUpdated: (repo, pull) => announceUpdated(client, repo, pull),
announceMerge: (repo, pull) => announceMerge(client, repo, pull),
announceClosed: (repo, pull) => announceClosed(client, repo, pull),
});
/**
* **The receiver, and the forge's one system webhook pointing at it** (issue 729). The secret is minted and kept beside
* the token; the webhook is made or corrected with the admin account (ADR 0266: the tools' token holds no admin scope).
* Answers whether events are heard; a forge that refuses is said, and the polls keep their pace.
*/
async function listenForForge(client: GiteaClient): Promise<boolean> {
const stateDir = process.env.MESH_GITEA_STATE_DIR;
const url = process.env.MESH_GITEA_HOOK_URL;
if (!stateDir || !url) {
console.log("[gitea] no webhook receiver: MESH_GITEA_STATE_DIR or MESH_GITEA_HOOK_URL unset, so the polls alone watch the forge");
pace.unheard("MESH_GITEA_STATE_DIR or MESH_GITEA_HOOK_URL unset", false);
return false;
}
try {
const secret = keptSecret(join(stateDir, "webhook.secret"));
const port = Number(process.env.MESH_GITEA_HOOK_PORT ?? HOOK_PORT);
const host = process.env.MESH_GITEA_HOOK_HOST ?? "0.0.0.0";
const server = receiver({ secret, port, heard: (kind, delivery) => pace.heard(kind, delivery),
refused: (reason, from) => pace.refused(reason, from),
// The seat git's forge events are said on the seat (seatevents.ts); the forge's others stay the module's own.
publish: async (event) => {
if (!SEAT_ONLY.has(event.name)) await emit(event.name, event.body);
await sayOnSeat(event.name, event.body as Record<string, unknown>);
},
act: async (event) => {
// A repository made, or one not yet seen readable, is granted read before anything acts on it (readall.ts).
await Promise.resolve().then(() => readAll().onEvent(event)).catch((err) =>
console.error(`[gitea] whether the mesh's accounts read the repository of ${event.name} could not be settled — ${err instanceof Error ? err.message : err}`));
try {
await actOnEvent(client, event);
} catch (err) {
catchUp();
throw err;
}
} });
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(port, host, () => resolve());
});
const hook = await ensureSystemHook(GiteaAdmin.fromEnv(), url.replace(/\/+$/, "") + HOOK_PATH, secret);
pace.listening(host, port, hook.url, hook);
console.log(`[gitea] listening for the forge's events on ${host}:${port}; its system webhook ${hook.id} ${hook.did} ` +
`at ${hook.url} (in place of ${hook.removed.system} system, ${hook.removed.default} default and ` +
`${hook.removed.repository} repository webhook(s)${hook.removed.repositories.length ? ` in ${hook.removed.repositories.join(", ")}` : ""}), ` +
`${hook.events.length} event families, signed`);
return true;
} catch (err) {
const why = err instanceof Error ? err.message : String(err);
pace.unheard(why);
console.error(`[gitea] the forge's events are not heard, so the polls keep their pace — ${why}`);
return false;
}
}
if (gitea) {
const client = gitea;
// A poll that fails says so once, not once a minute: the same reason repeating (the forge not up
// yet, the admin account refused on a restored forge) is one fact, and a recovery is worth a line.
let failing: string | null = null;
const tick = (fn: () => Promise<void>, every: number | (() => number)): void => {
const everyMs = (): number => (typeof every === "number" ? every : every());
// **One pass at a time** (novox/hq issue 250): the next pass is scheduled when this one has ended, so a
// pass that outlasts its interval delays the next instead of running beside it — two passes at once
// could each announce the same merge before either recorded it.
const run = (): void =>
void fn()
.then(() => {
if (failing !== null) console.log("[gitea] watching again");
failing = null;
})
.catch((err) => {
const why = err instanceof Error ? err.message : String(err);
if (why !== failing) console.error(`[gitea] not watching until this clears — ${why}`);
failing = why;
})
.finally(() => setTimeout(run, everyMs()));
run();
};
// **The forge's events first, the polls as the safety net** (novox/hq issue 729): while verified deliveries arrive the
// polls slow to every five minutes and announce only what no event said (Pace); otherwise they keep 30 s.
// **Not awaited** (novox/hq issue 1726): the receiver's set-up asks the forge's admin API, and the runtime kills a bundle
// whose import has not ended in its 10 s handshake and never starts it again; a forge slow to answer while every bundle
// of the node starts left gitea_events served nowhere. The pass below
// runs again once it is listening, so nothing said before is missed; listenForForge says its own failure.
const listenOk = listenForForge(client);
// The start's one pass over every repository (readall.ts), not awaited for the same reason. A forge not answering yet
// is asked again, a minute apart, until one pass has run; after that only the forge's events grant.
// An account of the list the forge does not hold yet (the forge-account provider makes nox-builder and nox-agent when
// their first consumer asks, and the forge sends no event for a user made) is looked for again ten minutes apart
// until every account was granted once; the line of each pass names it.
const readAllAtStart = (): void => void Promise.resolve().then(() => readAll().atStart()).then((r) => {
if (r.absent.length) setTimeout(readAllAtStart, 600_000);
}, (err) => {
console.error(`[gitea] whether the mesh's accounts read every repository could not be settled; asked again in a minute — ${err instanceof Error ? err.message : err}`);
setTimeout(readAllAtStart, 60_000);
});
try {
readAll();
readAllAtStart();
} catch (err) {
console.error(`[gitea] the mesh's accounts are not given read on every repository: no site administrator's login — ${err instanceof Error ? err.message : err}`);
}
// The catalog half, followed: its first view hands every registered module's entry at the start and each newer trunk
// revision what changed, so a repository that builds a registered module is made writable at the start and when its
// first module is registered (writes.ts); a candidate's revision moves nothing, and nothing is granted before the first view.
try {
const w = writes();
const findings = state<unknown>("findings");
const put = async (f: { key: string; value: unknown }) => { await findings.put(f.key, f.value); };
const view = new CatalogView((verb, input: RevisionInput) => broker().request(verb, input), {
said: keepStatus(firstViews),
changed: (key, value, deleted) => w.take({ key, op: deleted ? "delete" : "put", value }),
// Unanswered past its bound, or a revision waited for past mesh-sdk's WAITS_BOUND_MS, is a finding of the module's
// own, which the condition keeper raises (ADR 0615 §6; design 47 *A part with no view says it waits*).
raise: (s) => put(findingValue(unansweredFinding("gitea", s, new Date()))),
clear: async (s) => { await findings.delete(findingValue(unansweredFinding("gitea", s, new Date())).key); },
raiseWaits: (s) => put(findingValue(viewWaitsFinding("gitea", s, new Date()))),
clearWaits: async (s) => { await findings.delete(findingValue(viewWaitsFinding("gitea", s, new Date())).key); },
log: (line) => console.log(`[gitea] ${line}`),
});
followers.push(view.follower);
void bindUntilHeld(CATALOG_REVISION_EVENT, () => on<CatalogRevisionEvent>(CATALOG_REVISION_EVENT, (event) =>
// What is no catalog-revision event is said and taken: asked again, it would be no more readable.
view.hear(event.body).catch((err) => console.error(`[gitea] ${err instanceof Error ? err.message : err}`))));
void view.follower.start().then(() => w.viewed());
void bindUntilHeld(REGISTRATION_CHANGED_EVENT, () => on<RegistrationChangedEvent>(REGISTRATION_CHANGED_EVENT, async (event) => {
try { registrations.hear(event.body); } catch (err) { console.error(`[gitea] ${err instanceof Error ? err.message : err}`); }
// The registrations' watched branches may have changed: asked again, and the heads read again.
await registrations.start();
await reloadHeads().catch((err) => console.error(`[gitea] the watched heads could not be read — ${err instanceof Error ? err.message : err}`));
}));
} catch (err) {
console.error(`[gitea] the merging account is not given write on the delivered repositories: no site administrator's login — ${err instanceof Error ? err.message : err}`);
}
// The runner's step-ended and the heads' moves, heard through durable consumers of the module's own (design 47 §39, §475, §135): a failed
// `required` step is kept, and what no watched branch's head and no open pull request's head names any more is let go.
if (gitea) {
const forge = gitea;
const say = (err: unknown) => console.error(`[gitea] ${err instanceof Error ? err.message : String(err)}`);
reloadHeads = async () => {
const read = await readHeads(forge, registrations.watched, (line) => console.log(`[gitea] ${line}`));
await failedSteps.lost(heldHeads.replace(read.names, read.branches, read.pulls));
};
// The runner's step-ended is said on step-ended.<module>.<branch>.<commit> (the seat's definition).
const stepEnded = `${RUNNER}.${RUNNER_EVENTS.stepEnded}.*.*.*`;
void bindUntilHeld(stepEnded, () => on<StepEndedEvent>(stepEnded, (event) => failedSteps.stepEnded(event.body)));
// A branch's head is read from the forge, never taken from the event (the seat's definition of branch-moved).
void bindUntilHeld(`${GIT}.${GIT_EVENTS.branchMoved}`, () => on<BranchMovedEvent>(`${GIT}.${GIT_EVENTS.branchMoved}`, async (event) => {
const { repository, branch } = event.body;
if (!heldHeads.watches(repository, branch)) return;
const [owner, repo] = repository.split("/");
await failedSteps.lost(heldHeads.branchMoved(repository, branch, await forge.branchHead(owner, repo, branch)));
}));
void bindUntilHeld(`${GIT}.${GIT_EVENTS.pullUpdated}`, () => on<PullUpdatedEvent>(`${GIT}.${GIT_EVENTS.pullUpdated}`, (event) => failedSteps.lost(heldHeads.pullUpdated(event.body))));
for (const name of [GIT_EVENTS.pullClosed, GIT_EVENTS.pullMerged]) {
void bindUntilHeld(`${GIT}.${name}`, () => on<PullClosedEvent | PullMergedEvent>(`${GIT}.${name}`, (event) => failedSteps.lost(heldHeads.pullEnded(event.body))));
}
void registrations.start().then(() => reloadHeads()).catch(say);
}
// Main's rule is put right only when the tools' account's token is minted, and only while the setting keep-main-rules is
// true (mainrules.ts); no timer keeps it (design 47 H §764, H-A-100).
// The package seats' write token (packages-account.ts): minted at the start; after that renewed only when the Go
// bundle that writes with it says the forge refused it (the finding PACKAGES_TOKEN_REFUSED), never on a timer.
try {
const url = process.env.MESH_GITEA_URL ?? "http://127.0.0.1:3000";
const source = packagesToken(url);
const say = (line: string) => console.log(`[gitea] ${line}`);
void keepPackagesToken(source, url).then(say, (err) => console.error(`[gitea] the package seats' write token could not be minted at the start — ${err instanceof Error ? err.message : err}`));
const findings = state<unknown>("findings");
void bindUntilHeld("findings", () => findings.watch(renewOnRefusal(source, url, findings, say), { key: PACKAGES_TOKEN_REFUSED }));
} catch (err) {
console.error(`[gitea] the package seats cannot write — ${err instanceof Error ? err.message : err}`);
}
tick(() => pollRepos(client), 60_000);
// **No timer asks the forge for pull requests or merges** (issue 1422): the forge's events announce them. One pass over
// every repository runs at the start and again once the receiver listens, so what happened while the module was away or
// not yet listening is announced; passes run one at a time, a failed one is asked again a minute later.
let passes: Promise<void> = Promise.resolve();
const pass = (): Promise<void> => (passes = passes.catch(() => {}).then(() =>
pollMerged(client).catch((err) => console.error(`[gitea] the pass over every repository's merges failed — ${err instanceof Error ? err.message : err}`))));
void pass();
let catchUpAsked = false;
catchUp = () => {
if (catchUpAsked) return;
catchUpAsked = true;
setTimeout(() => { catchUpAsked = false; void pass(); }, 30_000);
};
void listenOk.then((ok) => (ok ? pass() : undefined));
// No consumer is bound since ADR 0571 clause 13 took the controller's checked out of this module; a consumer added later
// is bound again until it holds, and not awaited (bind.ts, issue 1793).
bindInBackground([], () => console.log("[gitea] watching for new repositories and merged pull requests"));
}