PEP-231: перевыкатка продуктов (peppa deploy redeploy), сверка адресов с туннелем сервера, Bugsink и cloudflared в compose
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
52e1bbe56f
commit
9a50d1d6e2
@ -82,6 +82,33 @@ services:
|
||||
TIME_ZONE: Europe/Moscow
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
# PEP-231 (server): Traefik of the server routes bugsink.telecom.quest here by labels; the platform's
|
||||
# containers reach the API by name (BUGSINK_URL=http://peppa-bugsink:8000). On the Mac the file
|
||||
# route infra/traefik/bugsink.yml points at the same container.
|
||||
networks: [default, traefik_default]
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=traefik_default
|
||||
- traefik.http.routers.peppa-bugsink.rule=Host(`${BUGSINK_HOST:-bugsink.telecom.quest}`)
|
||||
- traefik.http.routers.peppa-bugsink.entrypoints=web
|
||||
# PEP-189: above any project's container route.
|
||||
- traefik.http.routers.peppa-bugsink.priority=100000
|
||||
- traefik.http.services.peppa-bugsink.loadbalancer.server.port=8000
|
||||
|
||||
# PEP-231: the server's own Cloudflare tunnel (profile `edge`, not started by default). One ingress
|
||||
# rule — everything to the server's Traefik (PEPPA_EDGE_SERVICE, http://127.0.0.1:8880); which names
|
||||
# come here is decided by DNS (`peppa edge sync`, the watchdog every 5 min). The connector token is a
|
||||
# file made by `peppa edge tunnel <name>` ($PEPPA_HOME/cloudflared/token, 0600), not an env value.
|
||||
cloudflared:
|
||||
image: cloudflare/cloudflared:2025.11.1
|
||||
container_name: peppa-cloudflared
|
||||
profiles: [edge]
|
||||
restart: unless-stopped
|
||||
user: "${PEPPA_UID:-0}:${PEPPA_GID:-0}"
|
||||
network_mode: host
|
||||
command: ["tunnel", "--no-autoupdate", "run", "--token-file", "/etc/cloudflared/token"]
|
||||
volumes:
|
||||
- ${PEPPA_HOME}/cloudflared:/etc/cloudflared:ro
|
||||
|
||||
# Jobs run in containers with the host's docker.sock (image builds, deploys), so the runner is
|
||||
# registered ONLY on Peppa's project repos: on peppa-bot (its repos) and one per repo of another
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
// `peppa` CLI: manage projects, goals, tasks and PM questions until the web UI exists.
|
||||
import { parseArgs } from "node:util";
|
||||
import { resolve } from "node:path";
|
||||
import { join, resolve } from "node:path";
|
||||
import {
|
||||
backupDb,
|
||||
parseAgentPairs,
|
||||
@ -72,7 +72,7 @@ import { createDb, migrateDb } from "@peppa/db";
|
||||
import { checkHost, ensureSshKey, pushImage, sshArgs, tmux } from "@peppa/runner";
|
||||
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
|
||||
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
||||
import { isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||
import { createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||
import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner";
|
||||
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core";
|
||||
@ -80,8 +80,8 @@ import { tidyAgentTasks } from "@peppa/runner";
|
||||
import { installCrashReporting } from "@peppa/core";
|
||||
import { answerAndDeliver, connectCi, importIssues, deployProd, redeployProject, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { loadEnv, peppaHome } from "@peppa/shared";
|
||||
import { stripAsIs } from "@peppa/shared/i18n";
|
||||
|
||||
const USAGE = `peppa — Peppa software factory CLI
|
||||
@ -102,6 +102,8 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa project list
|
||||
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
|
||||
peppa deploy redeploy <KEY|--all> [--dry-run] (healthy staging/prod again on the same commits — PEP-231 move to another docker)
|
||||
peppa edge sync [--dry-run] (PEP-231: platform/product addresses → the server's Cloudflare tunnel; needs CLOUDFLARE_*)
|
||||
peppa edge tunnel <name> (PEP-231: new Cloudflare tunnel; token → $PEPPA_HOME/cloudflared/token, prints the id)
|
||||
peppa release list [KEY]
|
||||
peppa release report [KEY] --sha <sha> -s <deploying|healthy|rolled_back|failed> [--previous <sha>] [--reason <text>]
|
||||
[--log-file <f>] [--commits-file <f>] (prod release step, from scripts/peppa-release.sh)
|
||||
@ -482,10 +484,29 @@ async function main(): Promise<void> {
|
||||
continue;
|
||||
}
|
||||
const tags = await redeployProject(db, p, { reason: "Перезапуск: версия переезжает на сервер Peppa FACTORY", event: "product_redeploy", dryRun: opts["dry-run"], log: (m) => console.log(m) });
|
||||
console.log(`${p.key}: ${tags.length ? tags.join(", ") : "no healthy staging/prod"}${opts["dry-run"] ? " (dry run)" : ""}`);
|
||||
console.log(`${p.key}: ${tags.length ? tags.join(", ") : "nothing tagged (no healthy staging/prod, a deploy is running, or Gitea refused — see above)"}${opts["dry-run"] ? " (dry run)" : ""}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "edge sync": {
|
||||
const cfg = edgeConfig();
|
||||
if (!cfg) throw new PeppaError("Cloudflare is not configured: CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_ZONE_ID, CLOUDFLARE_TUNNEL_ID");
|
||||
const hosts = await edgeHosts(db, cfg.domain);
|
||||
console.log(formatEdgeSync(await syncEdge(cfg, hosts, { dryRun: opts["dry-run"] }), opts["dry-run"]));
|
||||
break;
|
||||
}
|
||||
case "edge tunnel": {
|
||||
const name = args[0];
|
||||
const env = process.env;
|
||||
if (!name || !env.CLOUDFLARE_API_TOKEN || !env.CLOUDFLARE_ACCOUNT_ID) throw new PeppaError("usage: peppa edge tunnel <name> (needs CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID)");
|
||||
const t = await createEdgeTunnel({ api: (env.CLOUDFLARE_API_URL ?? "https://api.cloudflare.com/client/v4").replace(/\/$/, ""), token: env.CLOUDFLARE_API_TOKEN, accountId: env.CLOUDFLARE_ACCOUNT_ID }, name);
|
||||
const dir = join(peppaHome(), "cloudflared");
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
writeFileSync(join(dir, "token"), t.token, { mode: 0o600 });
|
||||
// The token is a secret: only the id is printed.
|
||||
console.log(`tunnel ${name}: CLOUDFLARE_TUNNEL_ID=${t.id} (token → ${join(dir, "token")})`);
|
||||
break;
|
||||
}
|
||||
case "release list": {
|
||||
const [key] = withKey(args, 0);
|
||||
const p = await getProject(db, key);
|
||||
|
||||
165
packages/core/src/edge-dns.ts
Normal file
165
packages/core/src/edge-dns.ts
Normal file
@ -0,0 +1,165 @@
|
||||
// PEP-231: addresses without the Mac. The server has its own Cloudflare tunnel (cloudflared in
|
||||
// compose, profile `edge`) with one ingress rule — everything to the server's Traefik. Which names
|
||||
// reach it is decided by DNS: the platform's address, Bugsink, `<slug>-staging|prod` of every
|
||||
// project and the hosts of recent deploys get a CNAME to `<tunnel>.cfargotunnel.com`. A record
|
||||
// pointing to another tunnel (the Mac's) is moved; any other record (A, AAAA, a foreign CNAME) is
|
||||
// left alone and reported. Nothing is deleted. Without CLOUDFLARE_* nothing happens.
|
||||
import { projects, releases, type Db } from "@peppa/db";
|
||||
import { and, gt, isNotNull, isNull } from "drizzle-orm";
|
||||
|
||||
export interface EdgeConfig {
|
||||
api: string;
|
||||
token: string;
|
||||
accountId: string;
|
||||
zoneId: string;
|
||||
tunnelId: string;
|
||||
/** One level under it only: Cloudflare's certificate covers `*.telecom.quest`. */
|
||||
domain: string;
|
||||
/** Where the tunnel sends everything: the server's Traefik. */
|
||||
service: string;
|
||||
}
|
||||
|
||||
export const EDGE_COMMENT = "peppa-factory";
|
||||
const RECENT_DEPLOY_MS = 30 * 24 * 3600_000;
|
||||
|
||||
/** The configuration from env, or null when Cloudflare is not set up (or PEPPA_EDGE_DNS=off). */
|
||||
export function edgeConfig(env: NodeJS.ProcessEnv = process.env): EdgeConfig | null {
|
||||
if (env.PEPPA_EDGE_DNS === "off") return null;
|
||||
const { CLOUDFLARE_API_TOKEN: token, CLOUDFLARE_ACCOUNT_ID: accountId, CLOUDFLARE_ZONE_ID: zoneId, CLOUDFLARE_TUNNEL_ID: tunnelId } = env;
|
||||
if (!token || !accountId || !zoneId || !tunnelId) return null;
|
||||
return {
|
||||
api: (env.CLOUDFLARE_API_URL ?? "https://api.cloudflare.com/client/v4").replace(/\/$/, ""),
|
||||
token,
|
||||
accountId,
|
||||
zoneId,
|
||||
tunnelId,
|
||||
domain: env.PEPPA_DEPLOY_DOMAIN ?? "telecom.quest",
|
||||
service: env.PEPPA_EDGE_SERVICE ?? "http://127.0.0.1:8880",
|
||||
};
|
||||
}
|
||||
|
||||
/** Same rule as the deploy script: exactly one label under the domain. */
|
||||
export function edgeHostAllowed(host: string, domain: string): boolean {
|
||||
const h = host.toLowerCase().replace(/\.$/, "");
|
||||
if (!h.endsWith(`.${domain}`)) return false;
|
||||
return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(h.slice(0, -domain.length - 1));
|
||||
}
|
||||
|
||||
const hostOf = (url: string | undefined) => {
|
||||
if (!url) return null;
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** Names that must reach the server, sorted. */
|
||||
export async function edgeHosts(db: Db, domain: string, o: { now?: number; env?: NodeJS.ProcessEnv } = {}): Promise<string[]> {
|
||||
const env = o.env ?? process.env;
|
||||
const now = o.now ?? Date.now();
|
||||
const platformKey = env.PEPPA_PLATFORM_KEY ?? "PEP";
|
||||
const names = new Set<string>();
|
||||
for (const h of [hostOf(env.PEPPA_WEB_URL), hostOf(env.BUGSINK_PUBLIC_URL ?? "https://bugsink.telecom.quest")]) if (h) names.add(h);
|
||||
for (const p of await db.select({ slug: projects.slug, key: projects.key }).from(projects).where(isNull(projects.deletedAt))) {
|
||||
if (p.key === platformKey) continue;
|
||||
for (const env of ["staging", "prod"]) names.add(`${p.slug}-${env}.${domain}`);
|
||||
}
|
||||
const recent = await db
|
||||
.select({ host: releases.host })
|
||||
.from(releases)
|
||||
.where(and(isNotNull(releases.host), gt(releases.createdAt, new Date(now - RECENT_DEPLOY_MS))));
|
||||
for (const r of recent) if (r.host) names.add(r.host.toLowerCase());
|
||||
return [...names].filter((h) => edgeHostAllowed(h, domain)).sort();
|
||||
}
|
||||
|
||||
interface CfRecord {
|
||||
id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export class CloudflareError extends Error {}
|
||||
|
||||
async function cf<T>(cfg: EdgeConfig, method: string, path: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(`${cfg.api}${path}`, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${cfg.token}`, "content-type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
const json = (await res.json().catch(() => null)) as { success?: boolean; result?: T; errors?: Array<{ message?: string }> } | null;
|
||||
if (!res.ok || !json?.success) {
|
||||
// Never the token: only the path and Cloudflare's messages.
|
||||
const why = json?.errors?.map((e) => e.message).filter(Boolean).join("; ") || `HTTP ${res.status}`;
|
||||
throw new CloudflareError(`Cloudflare ${method} ${path.replace(/\?.*/, "")}: ${why}`);
|
||||
}
|
||||
return json.result as T;
|
||||
}
|
||||
|
||||
export const tunnelTarget = (cfg: Pick<EdgeConfig, "tunnelId">) => `${cfg.tunnelId}.cfargotunnel.com`;
|
||||
|
||||
export interface EdgeSyncResult {
|
||||
ingress: "ok" | "set" | "planned";
|
||||
ok: string[];
|
||||
created: string[];
|
||||
/** host → the tunnel it pointed to before. */
|
||||
moved: Array<{ host: string; from: string }>;
|
||||
/** host → what is there (left alone). */
|
||||
conflicts: Array<{ host: string; record: string }>;
|
||||
}
|
||||
|
||||
/** The tunnel's only ingress rule: everything to the server's Traefik. */
|
||||
async function syncIngress(cfg: EdgeConfig, dryRun: boolean): Promise<EdgeSyncResult["ingress"]> {
|
||||
const path = `/accounts/${cfg.accountId}/cfd_tunnel/${cfg.tunnelId}/configurations`;
|
||||
const cur = await cf<{ config?: { ingress?: Array<{ hostname?: string; service?: string }> } }>(cfg, "GET", path);
|
||||
const ingress = cur?.config?.ingress ?? [];
|
||||
if (ingress.length === 1 && !ingress[0]!.hostname && ingress[0]!.service === cfg.service) return "ok";
|
||||
if (dryRun) return "planned";
|
||||
await cf(cfg, "PUT", path, { config: { ingress: [{ service: cfg.service }] } });
|
||||
return "set";
|
||||
}
|
||||
|
||||
/** Bring the tunnel's ingress and the DNS of `hosts` to the server's tunnel. */
|
||||
export async function syncEdge(cfg: EdgeConfig, hosts: string[], o: { dryRun?: boolean } = {}): Promise<EdgeSyncResult> {
|
||||
const dryRun = !!o.dryRun;
|
||||
const target = tunnelTarget(cfg);
|
||||
const out: EdgeSyncResult = { ingress: await syncIngress(cfg, dryRun), ok: [], created: [], moved: [], conflicts: [] };
|
||||
const zone = `/zones/${cfg.zoneId}/dns_records`;
|
||||
for (const host of hosts) {
|
||||
const records = await cf<CfRecord[]>(cfg, "GET", `${zone}?name=${encodeURIComponent(host)}`);
|
||||
if (records.length === 0) {
|
||||
if (!dryRun) await cf(cfg, "POST", zone, { type: "CNAME", name: host, content: target, proxied: true, ttl: 1, comment: EDGE_COMMENT });
|
||||
out.created.push(host);
|
||||
continue;
|
||||
}
|
||||
const cname = records.length === 1 && records[0]!.type === "CNAME" ? records[0]! : null;
|
||||
if (cname && cname.content.toLowerCase() === target) {
|
||||
out.ok.push(host);
|
||||
} else if (cname && cname.content.toLowerCase().endsWith(".cfargotunnel.com")) {
|
||||
if (!dryRun) await cf(cfg, "PUT", `${zone}/${cname.id}`, { type: "CNAME", name: host, content: target, proxied: true, ttl: 1, comment: EDGE_COMMENT });
|
||||
out.moved.push({ host, from: cname.content });
|
||||
} else {
|
||||
out.conflicts.push({ host, record: records.map((r) => `${r.type} ${r.content}`).join(", ") });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A new remotely managed tunnel; returns its id and the connector token (keep it secret). */
|
||||
export async function createEdgeTunnel(cfg: Omit<EdgeConfig, "tunnelId" | "zoneId" | "domain" | "service">, name: string): Promise<{ id: string; token: string }> {
|
||||
const full = cfg as EdgeConfig;
|
||||
const t = await cf<{ id: string }>(full, "POST", `/accounts/${cfg.accountId}/cfd_tunnel`, { name, config_src: "cloudflare" });
|
||||
const token = await cf<string>(full, "GET", `/accounts/${cfg.accountId}/cfd_tunnel/${t.id}/token`);
|
||||
return { id: t.id, token };
|
||||
}
|
||||
|
||||
export function formatEdgeSync(r: EdgeSyncResult, dryRun = false): string {
|
||||
const lines = [`${dryRun ? "(dry run) " : ""}ingress: ${r.ingress}`];
|
||||
for (const h of r.created) lines.push(`+ ${h}${dryRun ? " (будет создано)" : ""}`);
|
||||
for (const m of r.moved) lines.push(`~ ${m.host} ← ${m.from}${dryRun ? " (будет переписано)" : ""}`);
|
||||
for (const c of r.conflicts) lines.push(`! ${c.host}: ${c.record} — не трогаю`);
|
||||
lines.push(`уже на сервере: ${r.ok.length}`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
@ -105,3 +105,4 @@ export * from "./observe.ts";
|
||||
export * from "./observe-checks.ts";
|
||||
export * from "./accept-screen.ts";
|
||||
export * from "./accept-digest.ts";
|
||||
export * from "./edge-dns.ts";
|
||||
|
||||
22
packages/runner/src/edge-dns.ts
Normal file
22
packages/runner/src/edge-dns.ts
Normal file
@ -0,0 +1,22 @@
|
||||
// PEP-231: the watchdog keeps the platform's and the products' addresses on the server's tunnel
|
||||
// (core/edge-dns.ts). Every 5 minutes; a no-op without CLOUDFLARE_* in env.
|
||||
import { edgeConfig, edgeHosts, formatEdgeSync, syncEdge, type EdgeSyncResult } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
const EVERY_MS = 5 * 60_000;
|
||||
let last = 0;
|
||||
let lastReport = "";
|
||||
|
||||
export async function edgeDnsTick(db: Db, o: { now?: Date; log?: (m: string) => void; force?: boolean } = {}): Promise<EdgeSyncResult | null> {
|
||||
const cfg = edgeConfig();
|
||||
if (!cfg) return null;
|
||||
const now = (o.now ?? new Date()).getTime();
|
||||
if (!o.force && now - last < EVERY_MS) return null;
|
||||
last = now;
|
||||
const r = await syncEdge(cfg, await edgeHosts(db, cfg.domain, { now }));
|
||||
// Only changes and new conflicts go to the log: the same conflict every 5 minutes is noise.
|
||||
const report = formatEdgeSync(r);
|
||||
if (r.created.length || r.moved.length || r.ingress === "set" || (r.conflicts.length && report !== lastReport)) o.log?.(`edge dns: ${report.replace(/\n/g, "; ")}`);
|
||||
lastReport = report;
|
||||
return r;
|
||||
}
|
||||
@ -76,3 +76,4 @@ export * from "./pick-question.ts";
|
||||
export * from "./review-wanted.ts";
|
||||
export * from "./review-wanted-state.ts";
|
||||
export * from "./delay-actions.ts";
|
||||
export * from "./edge-dns.ts";
|
||||
|
||||
@ -35,6 +35,7 @@ import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
|
||||
import { readyDigestTick } from "./ready-digest.ts";
|
||||
import { stuckTaskTick } from "./stuck-tasks.ts";
|
||||
import { domainGuardTick } from "./domain-guard.ts";
|
||||
import { edgeDnsTick } from "./edge-dns.ts";
|
||||
import { actRunnerTick } from "./act-runner.ts";
|
||||
import { reviewWantedTick } from "./review-wanted.ts";
|
||||
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
|
||||
@ -153,6 +154,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
// PEP-112: changed secrets restart the deployed product; the product agent accepts each deploy.
|
||||
await productRedeployTick(db, { now: opts.now, log }).catch(failed(db, log, "secrets redeploy"));
|
||||
await productReviewTick(db, { log }).catch(failed(db, log, "product review"));
|
||||
// PEP-231: the platform's and the products' addresses lead to the server's tunnel (every 5 min).
|
||||
await edgeDnsTick(db, { now: opts.now, log }).catch(failed(db, log, "edge dns"));
|
||||
// PEP-143: users' reports about Peppa — the feedback agent analyses, superadmins decide.
|
||||
await feedbackTick(db, { now: opts.now, log }).catch(failed(db, log, "feedback"));
|
||||
// Errors of running products (PEP-58): Bugsink poll + incident policies.
|
||||
|
||||
105
packages/testkit/src/mock-cloudflare.ts
Normal file
105
packages/testkit/src/mock-cloudflare.ts
Normal file
@ -0,0 +1,105 @@
|
||||
// Mock Cloudflare API v4 (PEP-231): DNS records of one zone and remotely managed tunnels of one
|
||||
// account — the calls core/edge-dns.ts makes. Envelope `{success, result, errors}` as the real API;
|
||||
// a wrong Bearer token → 403 with an error, like an expired token.
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
export interface MockCfRecord {
|
||||
id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
content: string;
|
||||
proxied?: boolean;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export class MockCloudflare {
|
||||
readonly token = "mock-cf-token";
|
||||
readonly accountId = "mock-account";
|
||||
readonly zoneId = "mock-zone";
|
||||
records: MockCfRecord[] = [];
|
||||
tunnels = new Map<string, { name: string; token: string; config: { ingress: Array<{ hostname?: string; service: string }> } }>();
|
||||
readonly calls: Array<{ method: string; path: string }> = [];
|
||||
/** Every request answers 500 (Cloudflare is down). */
|
||||
down = false;
|
||||
private server: Server | null = null;
|
||||
url = "";
|
||||
|
||||
addRecord(r: Omit<MockCfRecord, "id">): MockCfRecord {
|
||||
const rec = { id: randomUUID(), ...r };
|
||||
this.records.push(rec);
|
||||
return rec;
|
||||
}
|
||||
|
||||
addTunnel(name: string, ingress: Array<{ hostname?: string; service: string }> = []): string {
|
||||
const id = randomUUID();
|
||||
this.tunnels.set(id, { name, token: `mock-tunnel-secret-${id}`, config: { ingress } });
|
||||
return id;
|
||||
}
|
||||
|
||||
env(tunnelId: string): Record<string, string> {
|
||||
return { CLOUDFLARE_API_URL: this.url, CLOUDFLARE_API_TOKEN: this.token, CLOUDFLARE_ACCOUNT_ID: this.accountId, CLOUDFLARE_ZONE_ID: this.zoneId, CLOUDFLARE_TUNNEL_ID: tunnelId };
|
||||
}
|
||||
|
||||
async start(): Promise<this> {
|
||||
this.server = createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (c) => chunks.push(c));
|
||||
req.on("end", () => {
|
||||
const u = new URL(req.url ?? "/", "http://x");
|
||||
const method = req.method ?? "GET";
|
||||
this.calls.push({ method, path: u.pathname });
|
||||
const send = (status: number, result: unknown, errors: Array<{ code: number; message: string }> = []) =>
|
||||
res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify({ success: status < 300, result: status < 300 ? result : null, errors, messages: [] }));
|
||||
if (this.down) return send(500, null, [{ code: 10000, message: "Internal error" }]);
|
||||
if (req.headers.authorization !== `Bearer ${this.token}`) return send(403, null, [{ code: 10000, message: "Authentication error" }]);
|
||||
const body = chunks.length ? (JSON.parse(Buffer.concat(chunks).toString()) as Record<string, unknown>) : {};
|
||||
let m: RegExpExecArray | null;
|
||||
if ((m = /^\/zones\/([^/]+)\/dns_records(?:\/([^/]+))?$/.exec(u.pathname))) {
|
||||
if (m[1] !== this.zoneId) return send(404, null, [{ code: 7003, message: "Could not route to /zones" }]);
|
||||
const id = m[2];
|
||||
if (method === "GET" && !id) {
|
||||
const name = u.searchParams.get("name");
|
||||
return send(200, this.records.filter((r) => !name || r.name === name));
|
||||
}
|
||||
if (method === "POST" && !id) {
|
||||
if (this.records.some((r) => r.name === body.name && (r.type === "CNAME" || body.type === "CNAME")))
|
||||
return send(400, null, [{ code: 81053, message: "An A, AAAA, or CNAME record with that host already exists." }]);
|
||||
return send(200, this.addRecord({ type: String(body.type), name: String(body.name), content: String(body.content), proxied: !!body.proxied, comment: body.comment as string | undefined }));
|
||||
}
|
||||
if (method === "PUT" && id) {
|
||||
const r = this.records.find((x) => x.id === id);
|
||||
if (!r) return send(404, null, [{ code: 81044, message: "Record does not exist." }]);
|
||||
Object.assign(r, { type: String(body.type), name: String(body.name), content: String(body.content), proxied: !!body.proxied, comment: body.comment as string | undefined });
|
||||
return send(200, r);
|
||||
}
|
||||
}
|
||||
if ((m = /^\/accounts\/([^/]+)\/cfd_tunnel(?:\/([^/]+))?(?:\/(configurations|token))?$/.exec(u.pathname))) {
|
||||
if (m[1] !== this.accountId) return send(404, null, [{ code: 7003, message: "Could not route to /accounts" }]);
|
||||
const [, , id, sub] = m;
|
||||
if (method === "POST" && !id) {
|
||||
const tid = this.addTunnel(String(body.name));
|
||||
return send(200, { id: tid, name: body.name });
|
||||
}
|
||||
const t = id ? this.tunnels.get(id) : undefined;
|
||||
if (!t) return send(404, null, [{ code: 1003, message: "Tunnel not found" }]);
|
||||
if (sub === "token" && method === "GET") return send(200, t.token);
|
||||
if (sub === "configurations" && method === "GET") return send(200, { tunnel_id: id, config: t.config });
|
||||
if (sub === "configurations" && method === "PUT") {
|
||||
t.config = (body.config as typeof t.config) ?? { ingress: [] };
|
||||
return send(200, { tunnel_id: id, config: t.config });
|
||||
}
|
||||
}
|
||||
send(404, null, [{ code: 7000, message: "No route for that URI" }]);
|
||||
});
|
||||
});
|
||||
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
|
||||
this.url = `http://127.0.0.1:${(this.server!.address() as AddressInfo).port}`;
|
||||
return this;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
|
||||
}
|
||||
}
|
||||
206
packages/testkit/test/server-edge.test.ts
Normal file
206
packages/testkit/test/server-edge.test.ts
Normal file
@ -0,0 +1,206 @@
|
||||
// PEP-231: products and addresses without the Mac — redeploy of healthy versions on the same
|
||||
// commits (`peppa deploy redeploy`), the server's Cloudflare tunnel and the DNS sync (mock-cloudflare),
|
||||
// compose services for Bugsink on the server and cloudflared.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { events, releases } from "@peppa/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { MockCloudflare } from "../src/mock-cloudflare.ts";
|
||||
import { MockGitea } from "../src/mock-gitea.ts";
|
||||
import { core, db, runner, teardown } from "./helpers.ts";
|
||||
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
const run = promisify(execFile);
|
||||
let n = 0;
|
||||
async function proj(slug?: string) {
|
||||
n++;
|
||||
return core.createProject(db, { slug: slug ?? `mock-edge-${n}`, key: `MED${String.fromCharCode(64 + n)}`, name: `Edge ${n}`, giteaOwner: "peppa-bot", giteaRepo: slug ?? `mock-edge-${n}`, workspacePath: `/tmp/mock-edge-${n}` });
|
||||
}
|
||||
const fakeGitea = () => {
|
||||
const tags: Array<{ repo: string; tag: string; sha: string; message: string }> = [];
|
||||
return { tags, client: { createTag: async (_o: string, repo: string, tag: string, sha: string, message: string) => void tags.push({ repo, tag, sha, message }) } as never };
|
||||
};
|
||||
|
||||
after(teardown);
|
||||
|
||||
describe("PEP-231: продукты перевыкатываются на тех же коммитах", () => {
|
||||
test("Scenario: Перевыкатка всех проектов", async () => {
|
||||
const p = await proj();
|
||||
await db.insert(releases).values([
|
||||
{ projectId: p.id, env: "staging", sha: "abc1234", status: "healthy", host: `${p.slug}-staging.telecom.quest`, tasks: [] },
|
||||
{ projectId: p.id, env: "prod", sha: "abc1234", status: "healthy", host: `${p.slug}-prod.telecom.quest`, tasks: [] },
|
||||
{ projectId: p.id, env: "preview", sha: "fff0000", status: "healthy", host: `${p.slug}-pr3.telecom.quest`, prNumber: 3, tasks: [] },
|
||||
]);
|
||||
const g = fakeGitea();
|
||||
const tags = await runner.redeployProject(db, p, { client: g.client, reason: "move", event: "product_redeploy" });
|
||||
assert.equal(tags.length, 2, "staging and prod, not the preview");
|
||||
assert.match(g.tags[0]!.tag, /^deploy-staging-\d{17}$/);
|
||||
assert.match(g.tags[1]!.tag, /^deploy-prod-\d{17}$/);
|
||||
assert.deepEqual(g.tags.map((t) => t.sha), ["abc1234", "abc1234"]);
|
||||
const ev = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "product_redeploy")));
|
||||
assert.equal(ev.length, 1);
|
||||
});
|
||||
|
||||
test("Scenario: Пробный запуск", async () => {
|
||||
const p = await proj();
|
||||
await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "bcd2345", status: "healthy", host: null, tasks: [] });
|
||||
const g = fakeGitea();
|
||||
const plan = await runner.redeployProject(db, p, { client: g.client, reason: "move", event: "product_redeploy", dryRun: true });
|
||||
assert.equal(plan.length, 1);
|
||||
assert.match(plan[0]!, /^deploy-staging-\d{17} → bcd2345$/);
|
||||
assert.equal(g.tags.length, 0);
|
||||
});
|
||||
|
||||
test("Scenario: Выкладка уже идёт", async () => {
|
||||
const p = await proj();
|
||||
await db.insert(releases).values([
|
||||
{ projectId: p.id, env: "staging", sha: "cde3456", status: "healthy", tasks: [] },
|
||||
{ projectId: p.id, env: "prod", sha: "cde3456", status: "healthy", tasks: [] },
|
||||
{ projectId: p.id, env: "staging", sha: "def4567", status: "deploying", tasks: [] },
|
||||
]);
|
||||
const g = fakeGitea();
|
||||
await runner.redeployProject(db, p, { client: g.client, reason: "move", event: "product_redeploy" });
|
||||
assert.deepEqual(g.tags.map((t) => t.tag.replace(/-\d+$/, "")), ["deploy-prod"]);
|
||||
});
|
||||
|
||||
test("CLI peppa deploy redeploy --all через mock-gitea ставит теги", async () => {
|
||||
const gitea = await new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-edge-")), "gitea")).start();
|
||||
try {
|
||||
gitea.addUser({ id: 9001, login: "peppa-bot", token: "mock-bot-token" } as never);
|
||||
const p = await proj("mock-edge-cli");
|
||||
gitea.addRepo("peppa-bot", "mock-edge-cli", { files: { "README.md": "x" } });
|
||||
const sha = gitea.sha("peppa-bot", "mock-edge-cli", "main");
|
||||
await db.insert(releases).values({ projectId: p.id, env: "staging", sha, status: "healthy", tasks: [] });
|
||||
const { stdout } = await run(join(ROOT, "packages/cli/bin/peppa"), ["deploy", "redeploy", p.key], { env: { ...process.env, GITEA_URL: gitea.url, GITEA_TOKEN: "mock-bot-token" } });
|
||||
assert.match(stdout, new RegExp(`${p.key}: deploy-staging-\\d{17}`));
|
||||
const dry = await run(join(ROOT, "packages/cli/bin/peppa"), ["deploy", "redeploy", "--all", "--dry-run"], { env: { ...process.env, GITEA_URL: gitea.url, GITEA_TOKEN: "mock-bot-token" } });
|
||||
assert.match(dry.stdout, /\(dry run\)/);
|
||||
} finally {
|
||||
await gitea.stop();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-231: адреса ведут на туннель сервера", () => {
|
||||
let cf: MockCloudflare;
|
||||
let tunnel: string;
|
||||
let macTunnel: string;
|
||||
let cfg: NonNullable<ReturnType<typeof core.edgeConfig>>;
|
||||
before(async () => {
|
||||
cf = await new MockCloudflare().start();
|
||||
macTunnel = cf.addTunnel("mac", [{ hostname: "git.telecom.quest", service: "http://localhost:3000" }, { service: "http://localhost:80" }]);
|
||||
tunnel = cf.addTunnel("peppa-server");
|
||||
cfg = core.edgeConfig({ ...cf.env(tunnel), PEPPA_WEB_URL: "https://peppa.telecom.quest" })!;
|
||||
});
|
||||
after(() => cf.stop());
|
||||
|
||||
test("edgeHosts: адрес платформы, Bugsink, staging/prod проектов, недавние выкладки, один уровень", async () => {
|
||||
const p = await proj("mrv");
|
||||
await db.insert(releases).values([
|
||||
{ projectId: p.id, env: "preview", sha: "1", status: "healthy", host: "mrv-pr7.telecom.quest", tasks: [] },
|
||||
{ projectId: p.id, env: "preview", sha: "2", status: "healthy", host: "a.b.telecom.quest", tasks: [] },
|
||||
{ projectId: p.id, env: "preview", sha: "3", status: "healthy", host: "other.example.com", tasks: [] },
|
||||
]);
|
||||
const hosts = await core.edgeHosts(db, "telecom.quest", { env: { PEPPA_WEB_URL: "https://peppa.telecom.quest", PEPPA_PLATFORM_KEY: "PEP" } });
|
||||
for (const h of ["peppa.telecom.quest", "bugsink.telecom.quest", "mrv-staging.telecom.quest", "mrv-prod.telecom.quest", "mrv-pr7.telecom.quest"]) assert.ok(hosts.includes(h), h);
|
||||
assert.ok(!hosts.includes("a.b.telecom.quest"), "Scenario: Имя глубже одного уровня");
|
||||
assert.ok(!hosts.includes("other.example.com"));
|
||||
});
|
||||
|
||||
test("Scenario: Новой записи нет; Адрес смотрел на туннель Mac; Чужая запись", async () => {
|
||||
cf.addRecord({ type: "CNAME", name: "peppa.telecom.quest", content: `${macTunnel}.cfargotunnel.com`, proxied: true });
|
||||
cf.addRecord({ type: "A", name: "bugsink.telecom.quest", content: "1.2.3.4" });
|
||||
const hosts = ["bugsink.telecom.quest", "mrv-staging.telecom.quest", "peppa.telecom.quest"];
|
||||
|
||||
const dry = await core.syncEdge(cfg, hosts, { dryRun: true });
|
||||
assert.equal(dry.ingress, "planned");
|
||||
assert.deepEqual(dry.created, ["mrv-staging.telecom.quest"]);
|
||||
assert.equal(cf.records.length, 2, "dry run changes nothing");
|
||||
assert.deepEqual(cf.tunnels.get(tunnel)!.config.ingress, []);
|
||||
|
||||
const r = await core.syncEdge(cfg, hosts);
|
||||
assert.equal(r.ingress, "set");
|
||||
assert.deepEqual(cf.tunnels.get(tunnel)!.config.ingress, [{ service: "http://127.0.0.1:8880" }]);
|
||||
assert.equal(cf.tunnels.get(macTunnel)!.config.ingress.length, 2, "the Mac's tunnel is not touched");
|
||||
const rec = (name: string) => cf.records.find((x) => x.name === name)!;
|
||||
assert.deepEqual([rec("mrv-staging.telecom.quest").type, rec("mrv-staging.telecom.quest").content, rec("mrv-staging.telecom.quest").proxied], ["CNAME", `${tunnel}.cfargotunnel.com`, true]);
|
||||
assert.equal(rec("peppa.telecom.quest").content, `${tunnel}.cfargotunnel.com`);
|
||||
assert.deepEqual(r.moved, [{ host: "peppa.telecom.quest", from: `${macTunnel}.cfargotunnel.com` }]);
|
||||
assert.equal(rec("bugsink.telecom.quest").content, "1.2.3.4");
|
||||
assert.deepEqual(r.conflicts.map((c) => c.host), ["bugsink.telecom.quest"]);
|
||||
|
||||
const again = await core.syncEdge(cfg, hosts);
|
||||
assert.equal(again.ingress, "ok");
|
||||
assert.deepEqual([again.created, again.moved, again.ok], [[], [], ["mrv-staging.telecom.quest", "peppa.telecom.quest"]]);
|
||||
});
|
||||
|
||||
test("ошибка Cloudflare — понятное исключение без токена", async () => {
|
||||
await assert.rejects(core.syncEdge({ ...cfg, token: "wrong-secret-token" }, ["x.telecom.quest"]), (e: Error) => /Authentication error/.test(e.message) && !e.message.includes("wrong-secret-token"));
|
||||
cf.down = true;
|
||||
try {
|
||||
await assert.rejects(core.syncEdge(cfg, ["x.telecom.quest"]), /Internal error/);
|
||||
} finally {
|
||||
cf.down = false;
|
||||
}
|
||||
});
|
||||
|
||||
test("Scenario: Cloudflare не настроен — тик вачдога ничего не спрашивает", async () => {
|
||||
const before = cf.calls.length;
|
||||
for (const k of ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_ZONE_ID", "CLOUDFLARE_TUNNEL_ID"]) delete process.env[k];
|
||||
assert.equal(await runner.edgeDnsTick(db, { force: true }), null);
|
||||
assert.equal(core.edgeConfig({ ...cf.env(tunnel), PEPPA_EDGE_DNS: "off" }), null);
|
||||
assert.equal(cf.calls.length, before);
|
||||
});
|
||||
|
||||
test("тик вачдога с настройкой — сверка, раз в 5 минут", async () => {
|
||||
Object.assign(process.env, cf.env(tunnel));
|
||||
try {
|
||||
const r = await runner.edgeDnsTick(db, { force: true });
|
||||
assert.ok(r);
|
||||
assert.ok(cf.records.some((x) => x.name === "mrv-prod.telecom.quest" && x.comment === core.EDGE_COMMENT));
|
||||
assert.equal(await runner.edgeDnsTick(db), null, "throttled");
|
||||
} finally {
|
||||
for (const k of Object.keys(cf.env(tunnel))) delete process.env[k];
|
||||
}
|
||||
});
|
||||
|
||||
test("CLI peppa edge tunnel: токен в файл 0600, в выводе только id", async () => {
|
||||
const env = { ...process.env, CLOUDFLARE_API_URL: cf.url, CLOUDFLARE_API_TOKEN: cf.token, CLOUDFLARE_ACCOUNT_ID: cf.accountId };
|
||||
const { stdout } = await run(join(ROOT, "packages/cli/bin/peppa"), ["edge", "tunnel", "peppa-new"], { env });
|
||||
const id = /CLOUDFLARE_TUNNEL_ID=([\w-]+)/.exec(stdout)?.[1];
|
||||
assert.ok(id && cf.tunnels.has(id));
|
||||
const secret = cf.tunnels.get(id)!.token;
|
||||
assert.ok(!stdout.includes(secret));
|
||||
const file = join(process.env.PEPPA_HOME!, "cloudflared", "token");
|
||||
assert.equal(readFileSync(file, "utf8"), secret);
|
||||
const { statSync } = await import("node:fs");
|
||||
assert.equal(statSync(file).mode & 0o777, 0o600);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-231: compose для сервера", () => {
|
||||
const compose = readFileSync(join(ROOT, "infra/docker-compose.yml"), "utf8");
|
||||
const block = (name: string) => {
|
||||
const m = new RegExp(`\\n ${name}:\\n([\\s\\S]*?)(?=\\n [a-z-]+:\\n|\\nvolumes:)`).exec(compose);
|
||||
assert.ok(m, name);
|
||||
return m[1]!;
|
||||
};
|
||||
test("Bugsink в сети Traefik с маршрутом по меткам выше маршрутов проектов", () => {
|
||||
const b = block("bugsink");
|
||||
assert.match(b, /traefik_default/);
|
||||
assert.match(b, /traefik\.http\.routers\.peppa-bugsink\.rule=Host\(`\$\{BUGSINK_HOST:-bugsink\.telecom\.quest\}`\)/);
|
||||
assert.match(b, /priority=100000/);
|
||||
});
|
||||
test("cloudflared — только в профиле edge, токен файлом", () => {
|
||||
const c = block("cloudflared");
|
||||
assert.match(c, /profiles: \[edge\]/);
|
||||
assert.match(c, /--token-file/);
|
||||
assert.match(c, /network_mode: host/);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user