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

118 lines
5.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.

// glossary-ignore-file: хосты агентов настраивает только суперадмин
// PEP-40: servers runners run on (SSH, no daemon). Reaching them — runner/exec.ts, checks — runner/hosts.ts.
import { m as tr } from "@peppa/shared/i18n";
import { runnerHosts, sessions, type Db, type RunnerHostInfo } from "@peppa/db";
import { and, asc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
export type RunnerHost = typeof runnerHosts.$inferSelect;
export interface RunnerHostView extends RunnerHost {
/** Live runners on the host. */
runners: number;
}
const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/i;
// user@host or host; host: name, IPv4 or [IPv6]. No options smuggled in (a leading "-").
const TARGET_RE = /^(?:[a-z_][a-z0-9._-]{0,31}@)?(?:[a-z0-9][a-z0-9.-]{0,252}|\[[0-9a-f:]+\])$/i;
const WORKDIR_RE = /^[A-Za-z0-9._/~-]{1,200}$/;
export interface HostInput {
name: string;
sshTarget: string;
sshPort?: number;
workdir?: string;
peppaUrl?: string | null;
}
function check(h: Partial<HostInput>) {
if (h.name !== undefined && !NAME_RE.test(h.name)) throw new PeppaError(tr("Имя хоста — латиница, цифры, «.-_», до 40 символов"));
if (h.sshTarget !== undefined && !TARGET_RE.test(h.sshTarget)) throw new PeppaError(tr("SSH-адрес — user@host или host"));
if (h.sshPort !== undefined && !(Number.isInteger(h.sshPort) && h.sshPort > 0 && h.sshPort < 65536)) throw new PeppaError(tr("Порт SSH — от 1 до 65535"));
if (h.workdir !== undefined && (!WORKDIR_RE.test(h.workdir) || h.workdir.split("/").includes(".."))) throw new PeppaError(tr("Каталог на хосте — путь без пробелов и «..»"));
if (h.peppaUrl) {
try {
const u = new URL(h.peppaUrl);
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error();
} catch {
throw new PeppaError(tr("Адрес Peppa FACTORY — http(s)://…"));
}
}
}
export async function createHost(db: Db, h: HostInput): Promise<RunnerHost> {
const v = { ...h, name: h.name.trim(), sshTarget: h.sshTarget.trim(), workdir: h.workdir?.trim() || undefined, peppaUrl: h.peppaUrl?.trim() || null };
check(v);
const [dup] = await db.select({ id: runnerHosts.id }).from(runnerHosts).where(eq(runnerHosts.name, v.name));
if (dup) throw new PeppaError(tr("Хост «{name}» уже есть", { name: v.name }));
const [row] = await db.insert(runnerHosts).values(v).returning();
return row!;
}
export async function updateHost(db: Db, id: number, patch: Partial<HostInput>): Promise<RunnerHost> {
check(patch);
await getHost(db, id);
const [row] = await db.update(runnerHosts).set(patch).where(eq(runnerHosts.id, id)).returning();
return row!;
}
export async function getHost(db: Db, id: number): Promise<RunnerHost> {
const [row] = await db.select().from(runnerHosts).where(eq(runnerHosts.id, id));
if (!row) throw new PeppaError(tr("Хост #{id} не найден", { id }));
return row;
}
/** By id or name. */
export async function findHost(db: Db, ref: string | number): Promise<RunnerHost> {
if (typeof ref === "number" || /^\d+$/.test(ref)) return getHost(db, Number(ref));
const [row] = await db.select().from(runnerHosts).where(eq(runnerHosts.name, ref));
if (!row) throw new PeppaError(tr("Хост «{ref}» не найден", { ref }));
return row;
}
const liveRunners = sql<number>`(select count(*) from sessions s where s.host_id = "runner_hosts"."id" and s.status not in ('done','failed'))`;
export async function listHosts(db: Db, opts: { ids?: number[]; enabled?: boolean } = {}): Promise<RunnerHostView[]> {
if (opts.ids && !opts.ids.length) return [];
const rows = await db
.select({ host: runnerHosts, runners: liveRunners })
.from(runnerHosts)
.where(and(opts.ids ? inArray(runnerHosts.id, opts.ids) : undefined, opts.enabled ? isNull(runnerHosts.disabledAt) : undefined))
.orderBy(asc(runnerHosts.name));
return rows.map((r) => ({ ...r.host, runners: Number(r.runners) }));
}
export async function setHostDisabled(db: Db, id: number, disabled: boolean): Promise<void> {
await getHost(db, id);
await db.update(runnerHosts).set({ disabledAt: disabled ? new Date() : null }).where(eq(runnerHosts.id, id));
}
/** Removes a host with no live runners (finished sessions keep their history, host_id → null). */
export async function deleteHost(db: Db, id: number): Promise<void> {
const [live] = await db
.select({ n: sql<number>`count(*)` })
.from(sessions)
.where(and(eq(sessions.hostId, id), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
if (Number(live?.n ?? 0) > 0) throw new PeppaError(tr("На хосте работают раннеры — остановите их или отключите хост"));
await db.delete(runnerHosts).where(eq(runnerHosts.id, id));
}
/** Result of a check (runner/hosts.ts): online with fresh info, or offline with the error. */
export async function recordHostCheck(db: Db, id: number, r: { ok: true; info: RunnerHostInfo } | { ok: false; error: string }, now = new Date()): Promise<RunnerHost> {
const [row] = await db
.update(runnerHosts)
.set(r.ok ? { status: "online", info: r.info, lastSeenAt: now, lastError: null } : { status: "offline", lastError: r.error.slice(0, 500) })
.where(eq(runnerHosts.id, id))
.returning();
return row!;
}
/** PEP-40: the least busy online, enabled host among `ids`; null when none is available. */
export async function pickHost(db: Db, ids: number[]): Promise<RunnerHostView | null> {
const hosts = (await listHosts(db, { ids, enabled: true })).filter((h) => h.status === "online");
hosts.sort((a, b) => a.runners - b.runners || a.id - b.id);
return hosts[0] ?? null;
}
export const HOST_STATUS_RU: Record<RunnerHost["status"], string> = { unknown: tr("не проверен"), online: tr("онлайн"), offline: tr("офлайн") };