peppa/packages/core/src/gitea-server.ts
peppa-bot ec7345f483
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: failure за 1591с
peppa-ci / ci (pull_request) Failing after 28m44s
PEP-317: страница «Gitea» не ждёт Git-сервер — список из памяти при любом возрасте, переживает перезапуск
Последний список отдаётся сразу (старше минуты — обновление в фоне), хранится в settings
`gitea.overview` и прогревается при старте веба; без списка — «загружается». Ждёт Gitea
только «Получить заново» и «Сделать закрытым».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:13:36 +00:00

176 lines
6.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-169: what the Gitea server holds, as peppa-bot sees it — for the superadmin «Gitea» page.
import { projects, type Db } from "@peppa/db";
import type { GiteaClient, GiteaRepo, GiteaUser } from "./gitea.ts";
import { getSetting, setSetting } from "./settings.ts";
import { giteaForBot } from "./users.ts";
export interface GiteaServerRepo {
fullName: string;
owner: string;
name: string;
description: string;
private: boolean;
empty: boolean;
archived: boolean;
fork: boolean;
defaultBranch: string;
htmlUrl: string;
updatedAt: Date | null;
sizeKb: number;
/** The Peppa project this repository backs, if any. */
project: { key: string; name: string } | null;
}
export interface GiteaServerOverview {
url: string;
bot: { login: string; admin: boolean } | null;
repos: GiteaServerRepo[];
error: string | null;
/** When the shown list was loaded from Gitea (null — never). */
fetchedAt: Date | null;
/** PEP-317: no list yet — it is being loaded in the background, the page does not wait. */
loading: boolean;
}
type SearchRepo = GiteaRepo & { description?: string; archived?: boolean; fork?: boolean; updated_at?: string; size?: number };
const PAGE = 50;
const MAX_PAGES = 40;
/** Pages fetched at once after the first one (PEP-273: sequential pages took 2–6 s). */
const BATCH = 8;
/** A list older than this is refreshed in the background (it is still served at once — PEP-317). */
export const GITEA_OVERVIEW_FRESH_MS = 60_000;
/** PEP-317: the last list survives a restart of the web — `settings` row. */
export const GITEA_OVERVIEW_KEY = "gitea.overview";
/** Only what the page shows — the list is kept in memory and in the database. */
type StoredRepo = Omit<GiteaServerRepo, "project" | "updatedAt"> & { updatedAt: string | null };
type Loaded = { url: string; bot: { login: string; admin: boolean }; repos: StoredRepo[] };
type Stored = Loaded & { at: number };
type Cache = { at: number; value: Loaded | null; loading: Promise<Loaded> | null; error: string | null; restored: boolean };
const g = globalThis as unknown as { __peppaGiteaOverview?: Cache };
function cache(): Cache {
return (g.__peppaGiteaOverview ??= { at: 0, value: null, loading: null, error: null, restored: false });
}
/** Tests: forget the list kept in the process (the one in the database stays — like a restart of the web). */
export function resetGiteaOverviewCache(): void {
g.__peppaGiteaOverview = undefined;
}
async function load(client: GiteaClient): Promise<Loaded> {
const search = (page: number) => client.request<{ ok: boolean; data: SearchRepo[] }>("GET", `/repos/search?limit=${PAGE}&page=${page}&sort=updated&order=desc`).then((r) => r.data ?? []);
const [me, first] = await Promise.all([client.request<GiteaUser>("GET", "/user"), search(1)]);
const found: SearchRepo[] = [...first];
let full = first.length >= PAGE;
for (let from = 2; full && from <= MAX_PAGES; from += BATCH) {
const pages = await Promise.all(Array.from({ length: Math.min(BATCH, MAX_PAGES - from + 1) }, (_, i) => search(from + i)));
for (const data of pages) {
found.push(...data);
if (data.length < PAGE) {
full = false;
break;
}
}
}
// Pages fetched at once can overlap when a repository moves up mid-load.
const seen = new Set<string>();
const repos = found
.filter((r) => !seen.has(r.full_name) && !!seen.add(r.full_name))
.map(
(r): StoredRepo => ({
fullName: r.full_name,
owner: r.owner.login,
name: r.name,
description: r.description ?? "",
private: r.private,
empty: r.empty,
archived: !!r.archived,
fork: !!r.fork,
defaultBranch: r.default_branch,
htmlUrl: r.html_url,
updatedAt: r.updated_at ?? null,
sizeKb: r.size ?? 0,
}),
);
return { url: client.baseUrl, bot: { login: me.login, admin: !!me.is_admin }, repos };
}
function refresh(db: Db, client: GiteaClient): Promise<Loaded> {
const c = cache();
c.loading ??= load(client)
.then((value) => {
c.value = value;
c.at = Date.now();
c.error = null;
const stored: Stored = { ...value, at: c.at };
setSetting(db, GITEA_OVERVIEW_KEY, stored).catch(() => {});
return value;
})
.catch((e: unknown) => {
c.error = (e as Error).message;
throw e;
})
.finally(() => {
c.loading = null;
});
return c.loading;
}
/** Tests: wait for a background load, if one is running. */
export async function giteaOverviewSettled(): Promise<void> {
await cache().loading?.catch(() => {});
}
/** The list saved before the web restarted, once per process. */
async function restore(db: Db): Promise<void> {
const c = cache();
if (c.restored) return;
c.restored = true;
if (c.value) return;
const s = await getSetting<Stored>(db, GITEA_OVERVIEW_KEY).catch(() => null);
if (!s || !Array.isArray(s.repos) || c.value) return;
c.value = { url: s.url, bot: s.bot, repos: s.repos };
c.at = s.at;
}
/** Start of the web (PEP-317): the list is ready before the first visit. Never throws, never waits for Gitea. */
export async function warmGiteaOverview(db: Db): Promise<void> {
try {
await giteaServerOverview(db);
} catch {
// the page will try again
}
}
/** Repositories visible to peppa-bot (all of them when it is a site admin), newest first.
* PEP-273/317: the last list (in the process, else saved in the database) is served at once whatever its age;
* older than a minute it is refreshed in the background. No list at all — `loading`, loaded in the background.
* Only `fresh` waits for Gitea. A failed load keeps the previous list and says why. */
export async function giteaServerOverview(db: Db, opts: { fresh?: boolean; now?: number } = {}): Promise<GiteaServerOverview> {
let client: GiteaClient;
try {
client = giteaForBot();
} catch (e) {
return { url: "", bot: null, repos: [], error: (e as Error).message, fetchedAt: null, loading: false };
}
const c = cache();
await restore(db);
let error: string | null = null;
if (opts.fresh) {
try {
await refresh(db, client);
} catch (e) {
error = (e as Error).message;
}
} else if (!c.value || (opts.now ?? Date.now()) - c.at >= GITEA_OVERVIEW_FRESH_MS) {
error = c.error;
refresh(db, client).catch(() => {});
}
const value = c.value;
if (!value) return { url: client.baseUrl, bot: null, repos: [], error, fetchedAt: null, loading: !!c.loading };
const linked = new Map((await db.select({ key: projects.key, name: projects.name, owner: projects.giteaOwner, repo: projects.giteaRepo }).from(projects)).map((p) => [`${p.owner}/${p.repo}`.toLowerCase(), { key: p.key, name: p.name }]));
const repos = value.repos.map((r) => ({ ...r, updatedAt: r.updatedAt ? new Date(r.updatedAt) : null, project: linked.get(r.fullName.toLowerCase()) ?? null }));
return { url: value.url, bot: value.bot, repos, error, fetchedAt: new Date(c.at), loading: false };
}