peppa/packages/runner/src/code.ts
2026-11-16 09:52:35 +05:00

106 lines
5.4 KiB
TypeScript

// Project page tabs «Код» and «PR» (PEP-66): what the repo holds right now, asked from Gitea
// with the same clients as describeRepo (owner first, then peppa-bot), cached for a minute,
// never failing the page.
import { m } from "@peppa/shared/i18n";
import { taskCiSummary, taskForCheck, type CiSummary, type GiteaClient, type Project } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { repoAdmins } from "./share.ts";
const TIMEOUT_MS = 5000;
const CACHE_MS = 60_000;
const cache = new Map<string, { at: number; value: unknown }>();
export interface RepoOverview {
url: string;
defaultBranch: string | null;
readme: { path: string; text: string } | null;
branches: Array<{ name: string; sha: string; message: string; date: string | null }>;
commits: Array<{ sha: string; message: string; author: string; date: string; url: string }>;
/** Set when Gitea could not be asked: the tab shows the link and this message. */
error: string | null;
}
export interface OpenPull {
number: number;
title: string;
url: string;
branch: string;
/** Story of the PR (branch `task/<KEY>-<n>` or the story's pr_url) and its checks. */
task: { key: string; title: string; status: string; ci: CiSummary } | null;
}
/** Asks Gitea with the first client that answers in time; `null` if none did. */
async function withRepoClient<T>(db: Db, project: Project, ask: (c: GiteaClient) => Promise<T>): Promise<T | null> {
for (const c of await repoAdmins(db, project)) {
const timeout = new Promise<null>((r) => setTimeout(() => r(null), TIMEOUT_MS).unref());
const v = await Promise.race([ask(c), timeout]).catch(() => null);
if (v !== null) return v;
}
return null;
}
async function cached<T extends { error?: string | null }>(key: string, fresh: boolean | undefined, load: () => Promise<T>): Promise<T> {
const hit = cache.get(key);
if (!fresh && hit && Date.now() - hit.at < CACHE_MS) return hit.value as T;
const value = await load();
if (!value.error) cache.set(key, { at: Date.now(), value });
return value;
}
const firstLine = (s: string) => s.split("\n")[0]!.trim();
/** README of the default branch, branches and the latest commits («Код»). */
export function repoOverview(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<RepoOverview> {
const url = `${loadEnv().GITEA_URL}/${project.giteaOwner}/${project.giteaRepo}`;
return cached(`code:${project.id}`, opts.fresh, async () => {
const o = project.giteaOwner;
const r = project.giteaRepo;
const got = await withRepoClient(db, project, async (c) => {
const repo = await c.getRepo(o, r);
if (!repo) return { missing: true as const };
if (repo.empty) return { missing: false as const, repo, readme: null, branches: [], commits: [] };
const ref = repo.default_branch || "main";
const [readme, branches, commits] = await Promise.all([c.readme(o, r, ref), c.listBranches(o, r), c.listCommits(o, r, ref, 10)]);
return { missing: false as const, repo, readme, branches, commits };
});
// glossary-ignore: вкладки «Код» и «PR» есть только в виде «Инженер»
if (!got) return { url, defaultBranch: null, readme: null, branches: [], commits: [], error: m("Gitea сейчас не отвечает") };
// glossary-ignore: вкладки «Код» и «PR» есть только в виде «Инженер»
if (got.missing) return { url, defaultBranch: null, readme: null, branches: [], commits: [], error: m("Репозиторий не найден в Gitea") };
const def = got.repo.default_branch || "main";
return {
url: got.repo.html_url || url,
defaultBranch: def,
readme: got.readme,
branches: got.branches
.map((b) => ({ name: b.name, sha: b.commit.id, message: firstLine(b.commit.message ?? ""), date: b.commit.timestamp ?? null }))
.sort((a, b) => (a.name === def ? -1 : b.name === def ? 1 : (b.date ?? "").localeCompare(a.date ?? ""))),
commits: got.commits.map((c) => ({ sha: c.sha, message: firstLine(c.commit.message), author: c.author?.login ?? c.commit.author.name, date: c.commit.author.date, url: c.html_url })),
error: null,
};
});
}
/** Open PRs of the repo; a story's PR carries the story and its checks («PR»). */
export async function openPulls(db: Db, project: Project, opts: { fresh?: boolean } = {}): Promise<{ pulls: OpenPull[]; error: string | null }> {
const listed = await cached(`pulls:${project.id}`, opts.fresh, async () => {
const pulls = await withRepoClient(db, project, (c) => c.listOpenPulls(project.giteaOwner, project.giteaRepo));
// glossary-ignore: вкладки «Код» и «PR» есть только в виде «Инженер»
return pulls ? { pulls, error: null } : { pulls: [], error: m("Gitea сейчас не отвечает") };
});
// Story and checks come from Peppa's own DB on every call: they change faster than a minute.
const pulls: OpenPull[] = [];
for (const p of listed.pulls) {
const ref = await taskForCheck(db, project, p.head.ref, p.number);
pulls.push({
number: p.number,
title: p.title,
url: p.html_url,
branch: p.head.ref,
task: ref ? { key: ref.key, title: ref.task.title, status: ref.task.status, ci: await taskCiSummary(db, ref) } : null,
});
}
return { pulls, error: listed.error };
}