134 lines
5.0 KiB
TypeScript
134 lines
5.0 KiB
TypeScript
// 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 { 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;
|
||
}
|
||
|
||
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 cached list younger than this is served as is. */
|
||
export const GITEA_OVERVIEW_FRESH_MS = 60_000;
|
||
/** A cached list younger than this is served at once and refreshed in the background. */
|
||
export const GITEA_OVERVIEW_STALE_MS = 10 * 60_000;
|
||
|
||
type Loaded = { url: string; bot: { login: string; admin: boolean }; repos: SearchRepo[] };
|
||
type Cache = { at: number; value: Loaded | null; loading: Promise<Loaded> | null };
|
||
const g = globalThis as unknown as { __peppaGiteaOverview?: Cache };
|
||
function cache(): Cache {
|
||
return (g.__peppaGiteaOverview ??= { at: 0, value: null, loading: null });
|
||
}
|
||
|
||
/** Tests: forget the cached list. */
|
||
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));
|
||
return { url: client.baseUrl, bot: { login: me.login, admin: !!me.is_admin }, repos };
|
||
}
|
||
|
||
function refresh(client: GiteaClient): Promise<Loaded> {
|
||
const c = cache();
|
||
c.loading ??= load(client)
|
||
.then((value) => {
|
||
c.value = value;
|
||
c.at = Date.now();
|
||
return value;
|
||
})
|
||
.finally(() => {
|
||
c.loading = null;
|
||
});
|
||
return c.loading;
|
||
}
|
||
|
||
/** Repositories visible to peppa-bot (all of them when it is a site admin), newest first.
|
||
* Cached in the process (PEP-273): fresh for a minute, a stale list is served at once and refreshed
|
||
* in the background; `fresh` waits for a new list. A failed load keeps the previous list. */
|
||
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 };
|
||
}
|
||
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 c = cache();
|
||
const age = (opts.now ?? Date.now()) - c.at;
|
||
let value = c.value;
|
||
let error: string | null = null;
|
||
if (value && !opts.fresh && age < GITEA_OVERVIEW_FRESH_MS) {
|
||
// fresh
|
||
} else if (value && !opts.fresh && age < GITEA_OVERVIEW_STALE_MS) {
|
||
refresh(client).catch(() => {});
|
||
} else {
|
||
try {
|
||
value = await refresh(client);
|
||
} catch (e) {
|
||
error = (e as Error).message;
|
||
}
|
||
}
|
||
if (!value) return { url: client.baseUrl, bot: null, repos: [], error, fetchedAt: null };
|
||
const repos = value.repos.map((r) => ({
|
||
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 ? new Date(r.updated_at) : null,
|
||
sizeKb: r.size ?? 0,
|
||
project: linked.get(r.full_name.toLowerCase()) ?? null,
|
||
}));
|
||
return { url: value.url, bot: value.bot, repos, error, fetchedAt: new Date(c.at) };
|
||
}
|