feat(watch): uptime checks with a public status page per app and owner email through Rally Send (PY2.2)
RYP-E4, dispatch 4.2 PY2.2 (Railyard side): - lib/watch: checks (public https app addresses only; IPs, private names and our own hosts refused), 20 per org, a status page slug each. The box 1 agent reads GET /api/v1/watch/agent/checks (ids and URLs only, bearer WATCH_AGENT_TOKEN) and posts results to /api/v1/watch/agent/results. Two failures in a row turn a check red; each change emails the owner once through Rally Send (product railyard, from status@, idempotency key per change; a failed send is retried on the next result). Older, unknown and future results change nothing. - /status/<slug>: live results only (state, share of the last checks, bars), the check's name and never its address or any host or vendor name. - The Watch screen: add by address, pause or resume, open the status page. - Bridge route uptime (contract cases, uptime_check_keys): a check for the given address, or the app's latest live deploy; the first result is the slot's proof (check_result). - Gated on RAILYARD_WATCH_LIVE (denylist rule railyard-slot-watch): off, no check runs, the pages 404, the nav has no Watch item and the slot answers arriving. The copy test lints each gated surface with the flag and proves it checks the flag first. - Migration 0006 (watch_checks, watch_status; https only, history capped at 90, cascades with the org). Tests: watch 10/10, bridge 25/25, contract 3/3, migration 7/7 (0006 twice on a scratch cluster), watch copy 7/7, console 108/108 with the bundle build, tsc clean, SDK 7/7. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
332446652a
commit
5ccd834941
@ -43,6 +43,10 @@ Usage, Billing), one primary action on each, a pause switch and one-click cancel
|
||||
| `INSIGHTS_API_URL` | var | Insights tenant API base (Wave P PY1.3); empty keeps the Insights page on "No data yet" |
|
||||
| `FLAGS_API_URL` | var | Railyard Flags (Wave P PY2.1): base URL of the flags service on box 2 (through the tunnel). With `FLAGS_ADMIN_TOKEN` set, new flag environments are made there; without them, flags live in the console's own tables (migration 0005), the fallback. |
|
||||
| `FLAGS_ADMIN_TOKEN` | secret | The flags service's instance admin token (`Token ...` auth). Only this console holds it; apps read flags with their public flags key. |
|
||||
| `RAILYARD_WATCH_LIVE` | var | Railyard Watch (Wave P PY2.2). `1` turns on uptime checks, the Watch screen, the public status pages and the alert email. Unset (the default): no check runs and nothing about Watch is shown (denylist rule `railyard-slot-watch`). Set it only after the customer checks stack on box 1 passes its drill. |
|
||||
| `WATCH_AGENT_TOKEN` | secret | Bearer token of the box 1 checks agent (`stacks/gatus-customers/agent.sh`), at least 32 characters; the same value sits in `/etc/products/watch-agent.token` on box 1. Unset keeps the agent API off (503). |
|
||||
| `RALLY_TX_URL` | var | Rally Send transactional endpoint (https) for Watch alert email, product `railyard`. |
|
||||
| `RALLY_TX_KEY` | secret | Rally Send key minted for product `railyard`. Without it, alerts are logged, not sent. |
|
||||
| `INSIGHTS_API_TOKEN` | secret | Bearer token of the Insights tenant API |
|
||||
| `SITES` | KV binding | The edge collector's site entries; written when an app is added and on every plan, add-on or pause change |
|
||||
| `RELAY_URL` | var | Relay's OpenAI-compatible base for the AI gateway (Wave P PY1.4) |
|
||||
|
||||
@ -2,6 +2,7 @@ import { redirect } from "next/navigation";
|
||||
import type { ReactNode } from "react";
|
||||
import { Nav } from "../../components/Nav.tsx";
|
||||
import { currentSession } from "../../lib/current.ts";
|
||||
import { deps } from "../../lib/deps.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@ -9,7 +10,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
if (!(await currentSession())) redirect("/");
|
||||
return (
|
||||
<div className="shell">
|
||||
<Nav />
|
||||
<Nav watch={deps().cfg.watchLive} />
|
||||
<main className="main">{children}</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
30
apps/console/app/(app)/watch/page.tsx
Normal file
30
apps/console/app/(app)/watch/page.tsx
Normal file
@ -0,0 +1,30 @@
|
||||
import { WatchPanel } from "../../../components/WatchPanel.tsx";
|
||||
import { currentSession } from "../../../lib/current.ts";
|
||||
import { deps } from "../../../lib/deps.ts";
|
||||
import { listWithState } from "../../../lib/watch/service.ts";
|
||||
|
||||
// Uptime checks and status pages (Wave P PY2.2, RYP-E4). Checks run every
|
||||
// minute; two failures in a row turn a check red and email the owner.
|
||||
export default async function WatchPage() {
|
||||
const { repo, watch } = deps();
|
||||
if (!watch.live) {
|
||||
return (
|
||||
<>
|
||||
<h1>Watch</h1>
|
||||
<section className="card">
|
||||
<p className="muted">Watch is arriving. Nothing to set up yet.</p>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const s = (await currentSession())!;
|
||||
const [apps, checks] = await Promise.all([repo.listApps(s.org), listWithState(watch, s.org)]);
|
||||
return (
|
||||
<>
|
||||
<h1>Watch</h1>
|
||||
<section className="card">
|
||||
<WatchPanel apps={apps.map((a) => a.name)} checks={checks} />
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -449,3 +449,93 @@ test("flags: the console writes only its own org's environments, for apps it has
|
||||
assert.equal((await consoleSetFlag(flags, repo, other, { app: "shop", env: "production", flag: { key: "banner", enabled: false } }, T0)).status, 404);
|
||||
assert.equal((await flags.store.listEnvs(org.id)).length, 1);
|
||||
});
|
||||
|
||||
// ---- Uptime (PY2.2) -------------------------------------------------------------
|
||||
import { MemoryWatchStore } from "../../../../../lib/watch/store.ts";
|
||||
import { recordResults, type WatchDeps } from "../../../../../lib/watch/service.ts";
|
||||
import { agentList, agentResults, consoleWatch } from "../../../../../lib/watch/http.ts";
|
||||
|
||||
function watchDeps(repo: MemoryRepo): WatchDeps & { sent: string[] } {
|
||||
const sent: string[] = [];
|
||||
return { store: new MemoryWatchStore(), repo, mailer: { send: async (m) => (sent.push(`${m.to}|${m.subject}`), true) }, consoleUrl: "https://railyard.example", agentToken: "agent-token-0123456789abcdef-0123", live: true, sent };
|
||||
}
|
||||
|
||||
test("uptime: a check for the project's address, its status page, the first result is the proof, red emails the owner", async () => {
|
||||
const repo = new MemoryRepo(() => T0);
|
||||
const watch = watchDeps(repo);
|
||||
await call(repo, "orgs", { scribase_org_id: "org_u", name: "U", addon: addon(true, ["uptime"]) });
|
||||
const r = await call(repo, "uptime", { scribase_org_id: "org_u", app: "shop", url: "https://shop.example.com", owner_email: "owner@example.com" }, { extra: { watch } });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.created, true);
|
||||
const check = (r.body.checks as { id: string; status_url: string; state: string }[])[0];
|
||||
assert.match(check.status_url, /^https:\/\/railyard\.example\/status\/shop-/);
|
||||
assert.equal(check.state, "waiting");
|
||||
let proof = await call(repo, "proof", { scribase_org_id: "org_u", slot: "uptime" }, { extra: { watch } });
|
||||
assert.equal(proof.body.state, "no_proof_yet");
|
||||
const at = (m: number) => new Date(T0.getTime() + m * 60_000).toISOString();
|
||||
await recordResults(watch, { results: [{ id: check.id, ok: true, at: at(1), ms: 80 }, { id: check.id, ok: false, at: at(2), ms: 1 }, { id: check.id, ok: false, at: at(3), ms: 1 }] }, new Date(at(3)));
|
||||
proof = await call(repo, "proof", { scribase_org_id: "org_u", slot: "uptime" }, { extra: { watch } });
|
||||
assert.deepEqual(proof.body.proof, { kind: "check_result", id: check.id, at: at(1) });
|
||||
assert.deepEqual(watch.sent, ["owner@example.com|shop is down"]);
|
||||
const again = await call(repo, "uptime", { scribase_org_id: "org_u", app: "shop" }, { extra: { watch } });
|
||||
assert.equal(again.body.created, false);
|
||||
assert.equal((again.body.checks as { state: string }[])[0].state, "down");
|
||||
});
|
||||
|
||||
test("uptime: without a URL the app's latest live deploy is checked; with neither it asks for the address", async () => {
|
||||
const repo = new MemoryRepo(() => T0);
|
||||
const watch = watchDeps(repo);
|
||||
const orgId = (await call(repo, "orgs", { scribase_org_id: "org_d", name: "D", addon: addon(true, ["uptime", "deploy"]) })).body.org_id as string;
|
||||
assert.equal((await call(repo, "uptime", { scribase_org_id: "org_d", app: "shop" }, { extra: { watch } })).status, 400);
|
||||
await addApp(repo, orgId, "shop", T0);
|
||||
await recordDeploy(repo, orgId, parseDeployInput({ app: "shop", branch: "main", framework: "vite", status: "succeeded", url: "https://shop.acct.workers.dev" }) as never, T0);
|
||||
const r = await call(repo, "uptime", { scribase_org_id: "org_d", app: "shop" }, { extra: { watch } });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal((r.body.checks as { url: string }[])[0].url, "https://shop.acct.workers.dev/");
|
||||
});
|
||||
|
||||
test("uptime: 402 outside the add-on, 503 before Watch exists, 400 for a private address", async () => {
|
||||
const repo = new MemoryRepo(() => T0);
|
||||
const watch = watchDeps(repo);
|
||||
await call(repo, "orgs", { scribase_org_id: "org_n", name: "N", addon: addon(true, ["deploy"]) });
|
||||
assert.equal((await call(repo, "uptime", { scribase_org_id: "org_n", app: "shop", url: "https://shop.example.com" }, { extra: { watch } })).status, 402);
|
||||
await call(repo, "orgs", { scribase_org_id: "org_m", name: "M", addon: addon(true, ["uptime"]) });
|
||||
assert.equal((await call(repo, "uptime", { scribase_org_id: "org_m", app: "shop", url: "https://shop.example.com" })).status, 503);
|
||||
assert.equal((await call(repo, "uptime", { scribase_org_id: "org_m", app: "shop", url: "https://10.0.0.5" }, { extra: { watch } })).status, 400);
|
||||
// RAILYARD_WATCH_LIVE off: the slot is arriving, nothing is created.
|
||||
const off = { ...watch, live: false };
|
||||
assert.equal((await call(repo, "uptime", { scribase_org_id: "org_m", app: "shop", url: "https://shop.example.com" }, { extra: { watch: off } })).status, 503);
|
||||
assert.equal((await call(repo, "proof", { scribase_org_id: "org_m", slot: "uptime" }, { extra: { watch: off } })).body.state, "arriving");
|
||||
});
|
||||
|
||||
test("uptime agent API: bearer token only; the list has ids and URLs; results flow in", async () => {
|
||||
const repo = new MemoryRepo(() => T0);
|
||||
const watch = watchDeps(repo);
|
||||
await call(repo, "orgs", { scribase_org_id: "org_a2", name: "A", addon: addon(true, ["uptime"]) });
|
||||
const id = ((await call(repo, "uptime", { scribase_org_id: "org_a2", app: "shop", name: "Shop", url: "https://shop.example.com" }, { extra: { watch } })).body.checks as { id: string }[])[0].id;
|
||||
const auth = { authorization: `Bearer ${watch.agentToken}` };
|
||||
assert.equal((await agentList(watch, new Request("https://c/x"), T0)).status, 401);
|
||||
const list = (await (await agentList(watch, new Request("https://c/x", { headers: auth }), T0)).json()) as { checks: Record<string, unknown>[] };
|
||||
assert.deepEqual(list.checks, [{ id, url: "https://shop.example.com/", interval_s: 60 }]);
|
||||
assert.ok(!JSON.stringify(list).includes("Shop"), "no customer text reaches the checker");
|
||||
const post = await agentResults(watch, new Request("https://c/x", { method: "POST", headers: auth, body: JSON.stringify({ results: [{ id, ok: true, at: T0.toISOString(), ms: 50 }] }) }), T0);
|
||||
assert.equal(((await post.json()) as { accepted: number }).accepted, 1);
|
||||
assert.equal((await agentResults({ ...watch, agentToken: null }, new Request("https://c/x", { method: "POST" }), T0)).status, 503);
|
||||
});
|
||||
|
||||
test("uptime console: only the org's own apps and checks", async () => {
|
||||
const repo = new MemoryRepo(() => T0);
|
||||
const watch = watchDeps(repo);
|
||||
const org = await repo.createOrgForUser({ userId: "w1", email: "w@example.com", name: "W" });
|
||||
await repo.saveEntitlement({ ...(await import("../../../../../lib/types.ts")).emptyEntitlement(org.id, T0), plan: "railyard", status: "active", apps_limit: 3 });
|
||||
await addApp(repo, org.id, "shop", T0);
|
||||
const s = { org: org.id, email: "w@example.com" };
|
||||
assert.equal((await consoleWatch(watch, repo, null, {})).status, 401);
|
||||
assert.equal((await consoleWatch(watch, repo, s, { app: "nope", url: "https://x.example.com" })).status, 404);
|
||||
const ok = await consoleWatch(watch, repo, s, { app: "shop", url: "https://shop.example.com" });
|
||||
assert.equal(ok.status, 200);
|
||||
const id = (ok.body.checks as { id: string }[])[0].id;
|
||||
assert.equal((await watch.store.getCheck(id))?.owner_email, "w@example.com");
|
||||
assert.equal((await consoleWatch(watch, repo, { org: "other", email: "o@example.com" }, { id, paused: true })).status, 404);
|
||||
assert.equal((await consoleWatch(watch, repo, s, { id, paused: true })).status, 200);
|
||||
});
|
||||
|
||||
@ -32,6 +32,7 @@ import { verify, type WebhookHeaders } from "../../../../../lib/standard-webhook
|
||||
import { createApprovedDevice } from "../../../../../lib/tokens.ts";
|
||||
import { emptyEntitlement, type Entitlement } from "../../../../../lib/types.ts";
|
||||
import { ensureEnv, firstRead, FlagsError, listFlags, setFlag, type FlagsDeps } from "../../../../../lib/flags/service.ts";
|
||||
import { createCheck, listWithState, WatchError, type WatchDeps } from "../../../../../lib/watch/service.ts";
|
||||
|
||||
export const CLAIM_TTL_SECONDS = 120;
|
||||
|
||||
@ -49,7 +50,7 @@ export const BRIDGE_SLOTS = {
|
||||
analytics: { pkg: "PY1.3", landed: true, proof: "first_event" },
|
||||
ai: { pkg: "PY1.4", landed: true, proof: "gateway_key" },
|
||||
flags: { pkg: "PY2.1", landed: true, proof: "first_flag_read" },
|
||||
uptime: { pkg: "PY2.2", landed: false, proof: "check_result" },
|
||||
uptime: { pkg: "PY2.2", landed: true, proof: "check_result" },
|
||||
billing: { pkg: "PY2.3", landed: false, proof: "test_purchase" },
|
||||
consent: { pkg: "PY2.5", landed: false, proof: "consent_record" },
|
||||
} as const;
|
||||
@ -68,6 +69,8 @@ export interface BridgeDeps {
|
||||
insightsUrl?: string;
|
||||
/** Railyard Flags (PY2.1); absent in tests that do not need them. */
|
||||
flags?: FlagsDeps;
|
||||
/** Railyard Watch (PY2.2); absent in tests that do not need it. */
|
||||
watch?: WatchDeps;
|
||||
/** P-Y1 transition: accept unbound ids and orgs syncs without `addon.as_of` (RAILYARD_BRIDGE_ACCEPT_LEGACY=1). */
|
||||
acceptLegacy?: boolean;
|
||||
}
|
||||
@ -243,6 +246,7 @@ export async function slotProof(
|
||||
landed: Partial<Record<BridgeSlot, boolean>> = {},
|
||||
insights: InsightsClient | null = null,
|
||||
flags: FlagsDeps | null = null,
|
||||
watch: WatchDeps | null = null,
|
||||
): Promise<SlotState> {
|
||||
const isLanded = landed[slot] ?? BRIDGE_SLOTS[slot].landed;
|
||||
if (!isLanded) {
|
||||
@ -273,6 +277,14 @@ export async function slotProof(
|
||||
? { slot, state: "live", live: true, proof: read, next: null }
|
||||
: { slot, state: "no_proof_yet", live: true, proof: null, next: "Read a flag from the app (or run the add command again) to see the first read here." };
|
||||
}
|
||||
if (slot === "uptime") {
|
||||
if (!watch?.live) return { slot, state: "arriving", live: false, proof: null, next: "This slot is arriving (PY2.2); nothing was changed." };
|
||||
const checks = await listWithState(watch, orgId);
|
||||
const first = checks.filter((c) => c.first_result_at).sort((a, b) => (a.first_result_at! < b.first_result_at! ? -1 : 1))[0];
|
||||
return first
|
||||
? { slot, state: "live", live: true, proof: { kind: "check_result", id: first.id, at: first.first_result_at! }, next: null }
|
||||
: { slot, state: "no_proof_yet", live: true, proof: null, next: checks.length ? "The first result arrives within two minutes." : "Add your app's address to check." };
|
||||
}
|
||||
return { slot, state: "no_proof_yet", live: true, proof: null, next: null };
|
||||
}
|
||||
|
||||
@ -285,7 +297,7 @@ async function proofFor(deps: BridgeDeps, body: Record<string, unknown>): Promis
|
||||
if (!BRIDGE_SLOTS[s].landed) return { status: 200, body: { ...(await slotProof(deps.repo, "", s)) } };
|
||||
const bound = await deps.repo.findScribaseBinding(scribaseOrgId);
|
||||
if (!bound) return { status: 200, body: { slot: s, state: "not_entitled", live: false, proof: null, next: "Turn on the add-on first." } };
|
||||
return { status: 200, body: { ...(await slotProof(deps.repo, bound.org_id, s, {}, deps.insights ?? null, deps.flags ?? null)) } };
|
||||
return { status: 200, body: { ...(await slotProof(deps.repo, bound.org_id, s, {}, deps.insights ?? null, deps.flags ?? null, deps.watch ?? null)) } };
|
||||
}
|
||||
|
||||
async function deploysFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
|
||||
@ -442,7 +454,42 @@ async function flagsFor(deps: BridgeDeps, body: Record<string, unknown>): Promis
|
||||
}
|
||||
}
|
||||
|
||||
export type BridgeRoute = "orgs" | "claims" | "proof" | "deploys" | "sites" | "insights" | "ai" | "ai_usage" | "flags";
|
||||
/**
|
||||
* Uptime for one Scribase project (PY2.2): `{scribase_org_id, app, url?,
|
||||
* name?, owner_email?}`. With a URL (or, without one, the app's latest live
|
||||
* deploy) it adds a check; it always answers the app's checks with their
|
||||
* state and public status page.
|
||||
*/
|
||||
async function uptimeFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
|
||||
const scribaseOrgId = parseOrgRef(body);
|
||||
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
|
||||
const app = typeof body.app === "string" ? normaliseAppName(body.app) : "";
|
||||
if (!/^[a-z0-9][a-z0-9-]{0,39}$/.test(app)) return fail(400, "app must be a project name (letters, numbers, dashes)");
|
||||
const now = deps.now();
|
||||
const who = await entitledOrg(deps.repo, scribaseOrgId, "uptime", now);
|
||||
if ("status" in who) return who;
|
||||
if (!deps.watch || !deps.watch.live) return fail(503, "This slot is arriving (PY2.2). Nothing was changed.");
|
||||
const ownerEmail = typeof body.owner_email === "string" && body.owner_email.length <= 254 ? body.owner_email : null;
|
||||
let url = typeof body.url === "string" && body.url.trim() ? body.url.trim() : null;
|
||||
if (!url) {
|
||||
const railyardApp = await deps.repo.findAppByName(who.orgId, app);
|
||||
const live = railyardApp ? (await deps.repo.listDeploys(who.orgId, railyardApp.id)).find((d) => d.status === "succeeded") : undefined;
|
||||
url = live?.url ?? null;
|
||||
}
|
||||
try {
|
||||
const before = (await deps.watch.store.listChecks(who.orgId)).length;
|
||||
if (url) await createCheck(deps.watch, { orgId: who.orgId, app, name: body.name, url, ownerEmail });
|
||||
const checks = await listWithState(deps.watch, who.orgId, app);
|
||||
if (checks.length === 0) return fail(400, "Give the https address of your app to check, or deploy it first.");
|
||||
const created = (await deps.watch.store.listChecks(who.orgId)).length > before;
|
||||
return { status: 200, body: { app, created, checks } };
|
||||
} catch (e) {
|
||||
if (e instanceof WatchError) return fail(e.status, e.message);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export type BridgeRoute = "orgs" | "claims" | "proof" | "deploys" | "sites" | "insights" | "ai" | "ai_usage" | "flags" | "uptime";
|
||||
|
||||
/**
|
||||
* The route a signed message id names (P-Y1). Scribase sends
|
||||
@ -490,5 +537,7 @@ export async function handleBridge(deps: BridgeDeps, route: BridgeRoute, headers
|
||||
return aiUsageFor(deps, b);
|
||||
case "flags":
|
||||
return flagsFor(deps, b);
|
||||
case "uptime":
|
||||
return uptimeFor(deps, b);
|
||||
}
|
||||
}
|
||||
|
||||
17
apps/console/app/api/v1/bridge/scribase/uptime/route.ts
Normal file
17
apps/console/app/api/v1/bridge/scribase/uptime/route.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { deps } from "../../../../../../lib/deps.ts";
|
||||
import { json } from "../../../../../../lib/http.ts";
|
||||
import { handleBridge } from "../service.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { cfg, repo, sites, insights, flags, watch } = deps();
|
||||
if (!cfg.scribaseBridgeSecret) return json({ error: "bridge_not_configured" }, 503);
|
||||
const r = await handleBridge(
|
||||
{ repo, secret: cfg.scribaseBridgeSecret, consoleUrl: cfg.consoleUrl, now: () => new Date(), sites, insights, insightsUrl: cfg.insightsUrl, acceptLegacy: cfg.bridgeAcceptLegacy, flags, watch },
|
||||
"uptime",
|
||||
{ id: req.headers.get("webhook-id"), timestamp: req.headers.get("webhook-timestamp"), signature: req.headers.get("webhook-signature") },
|
||||
await req.text(),
|
||||
);
|
||||
return json(r.body, r.status);
|
||||
}
|
||||
8
apps/console/app/api/v1/watch/agent/checks/route.ts
Normal file
8
apps/console/app/api/v1/watch/agent/checks/route.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { deps } from "../../../../../../lib/deps.ts";
|
||||
import { agentList } from "../../../../../../lib/watch/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
return agentList(deps().watch, req, new Date());
|
||||
}
|
||||
8
apps/console/app/api/v1/watch/agent/results/route.ts
Normal file
8
apps/console/app/api/v1/watch/agent/results/route.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { deps } from "../../../../../../lib/deps.ts";
|
||||
import { agentResults } from "../../../../../../lib/watch/http.ts";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
return agentResults(deps().watch, req, new Date());
|
||||
}
|
||||
12
apps/console/app/api/watch/route.ts
Normal file
12
apps/console/app/api/watch/route.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { sessionFromRequest } from "../../../lib/current.ts";
|
||||
import { deps } from "../../../lib/deps.ts";
|
||||
import { json, sameOrigin } from "../../../lib/http.ts";
|
||||
import { consoleWatch } from "../../../lib/watch/http.ts";
|
||||
|
||||
// Add, pause or resume an uptime check from the Watch screen (PY2.2).
|
||||
export async function POST(req: Request) {
|
||||
const { cfg, repo, watch } = deps();
|
||||
if (!sameOrigin(req, cfg.consoleUrl)) return json({ error: "Forbidden" }, 403);
|
||||
const r = await consoleWatch(watch, repo, await sessionFromRequest(req), await req.json().catch(() => null));
|
||||
return json(r.body, r.status);
|
||||
}
|
||||
@ -37,6 +37,7 @@ pre { background: #1d2433; color: #e8ecf5; padding: 14px 16px; border-radius: 12
|
||||
.list { list-style: none; padding: 0; margin: 0; }
|
||||
.list li { padding: 12px 0; border-bottom: 1px solid var(--line); display: flex; justify-content: space-between; }
|
||||
.error { color: #b42318; }
|
||||
.ok { color: #1d7a4f; }
|
||||
.center { min-height: 100vh; display: grid; place-items: center; }
|
||||
.switch { display: inline-flex; gap: 4px; background: var(--glass); border-radius: 12px; padding: 4px; border: 1px solid var(--line); }
|
||||
.switch button { border: 0; background: transparent; padding: 7px 12px; border-radius: 9px; cursor: pointer; font: inherit; color: var(--muted); }
|
||||
|
||||
41
apps/console/app/status/[app]/page.tsx
Normal file
41
apps/console/app/status/[app]/page.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { deps } from "../../../lib/deps.ts";
|
||||
import { statusView } from "../../../lib/watch/service.ts";
|
||||
import { SLUG } from "../../../lib/watch/types.ts";
|
||||
|
||||
// A public status page per app (Wave P PY2.2, RYP-E4): live results only,
|
||||
// the check's name and never its address, host or any vendor name.
|
||||
export const revalidate = 30;
|
||||
|
||||
export async function generateMetadata({ params }: { params: { app: string } }) {
|
||||
const check = deps().watch.live && SLUG.test(params.app) ? await deps().watch.store.findCheckBySlug(params.app) : null;
|
||||
return { title: check ? `${check.name} status` : "Status", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function StatusPage({ params }: { params: { app: string } }) {
|
||||
const { watch } = deps();
|
||||
if (!watch.live || !SLUG.test(params.app)) notFound();
|
||||
const check = await watch.store.findCheckBySlug(params.app);
|
||||
if (!check || check.paused) notFound();
|
||||
const view = statusView(check, await watch.store.getStatus(check.id));
|
||||
const tone = view.state === "up" ? "ok" : view.state === "down" ? "error" : "muted";
|
||||
return (
|
||||
<main className="main" style={{ maxWidth: 720, margin: "0 auto" }}>
|
||||
<h1>{view.name}</h1>
|
||||
<section className="card">
|
||||
<h2 className={tone} data-copy-source="railyard watch_status (live results)">
|
||||
{view.label}
|
||||
</h2>
|
||||
{view.uptime ? <p data-copy-source="railyard watch_status (live results)">{view.uptime}</p> : null}
|
||||
{view.lastChecked ? <p className="muted">Last checked {view.lastChecked}</p> : <p className="muted">The first check runs within two minutes.</p>}
|
||||
{view.bars.length ? (
|
||||
<div role="img" aria-label={`Last ${view.bars.length} checks`} style={{ display: "flex", gap: 2, marginTop: 12 }}>
|
||||
{view.bars.map((b) => (
|
||||
<span key={b.at} title={`${b.at.slice(0, 16).replace("T", " ")} UTC: ${b.ok ? "up" : "down"}`} style={{ flex: 1, height: 28, borderRadius: 2, background: b.ok ? "var(--ok, #2f9e6b)" : "var(--error, #c84a4a)" }} />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@ -10,12 +10,14 @@ const LINKS = [
|
||||
{ href: "/billing", label: "Billing" },
|
||||
];
|
||||
|
||||
export function Nav() {
|
||||
/** `watch` adds the Watch screen once RAILYARD_WATCH_LIVE is on (PY2.2). */
|
||||
export function Nav({ watch = false }: { watch?: boolean }) {
|
||||
const path = usePathname();
|
||||
const links = watch ? [...LINKS.slice(0, 3), { href: "/watch", label: "Watch" }, ...LINKS.slice(3)] : LINKS;
|
||||
return (
|
||||
<nav className="nav" aria-label="Main">
|
||||
<div className="brand">Railyard</div>
|
||||
{LINKS.map((l) => (
|
||||
{links.map((l) => (
|
||||
<a key={l.href} href={l.href} aria-current={path?.startsWith(l.href) ? "page" : undefined}>
|
||||
{l.label}
|
||||
</a>
|
||||
|
||||
90
apps/console/components/WatchPanel.tsx
Normal file
90
apps/console/components/WatchPanel.tsx
Normal file
@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
export interface PanelCheck {
|
||||
id: string;
|
||||
app: string;
|
||||
name: string;
|
||||
url: string;
|
||||
paused: boolean;
|
||||
state: string;
|
||||
status_url: string;
|
||||
last_checked_at: string | null;
|
||||
}
|
||||
|
||||
async function post(body: Record<string, unknown>): Promise<string | null> {
|
||||
const res = await fetch("/api/watch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
if (res.ok) return null;
|
||||
return ((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Could not save. Try again.";
|
||||
}
|
||||
|
||||
const LABEL: Record<string, string> = { up: "Up", down: "Down", waiting: "Waiting" };
|
||||
|
||||
/** Uptime checks: add one by address, pause or resume, open the status page (PY2.2). */
|
||||
export function WatchPanel({ apps, checks }: { apps: string[]; checks: PanelCheck[] }) {
|
||||
const router = useRouter();
|
||||
const [app, setApp] = useState(apps[0] ?? "");
|
||||
const [url, setUrl] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const run = async (body: Record<string, unknown>) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const e = await post(body);
|
||||
setBusy(false);
|
||||
if (e) setError(e);
|
||||
else {
|
||||
setUrl("");
|
||||
router.refresh();
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
{checks.length ? (
|
||||
<ul className="list">
|
||||
{checks.map((c) => (
|
||||
<li key={c.id}>
|
||||
<span>
|
||||
<strong>{c.name}</strong> <span className="muted">{c.url}</span>
|
||||
</span>
|
||||
<span className="row">
|
||||
<span className={c.state === "down" ? "error" : c.state === "up" ? "ok" : "muted"}>{c.paused ? "Paused" : LABEL[c.state] ?? c.state}</span>
|
||||
<a href={c.status_url}>Status page</a>
|
||||
<button type="button" disabled={busy} onClick={() => run({ id: c.id, paused: !c.paused })}>
|
||||
{c.paused ? "Resume" : "Pause"}
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="muted">No checks yet. Add your app's address; we check it every minute.</p>
|
||||
)}
|
||||
{apps.length ? (
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run({ app, url });
|
||||
}}
|
||||
>
|
||||
<select aria-label="App" value={app} onChange={(e) => setApp(e.target.value)}>
|
||||
{apps.map((a) => (
|
||||
<option key={a} value={a}>
|
||||
{a}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input type="url" aria-label="Address to check" placeholder="https://your-app.example.com" value={url} onChange={(e) => setUrl(e.target.value)} />
|
||||
<button className="primary" type="submit" disabled={busy || !url.trim()}>
|
||||
{busy ? "Adding" : "Add check"}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="muted">Add an app first.</p>
|
||||
)}
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
50
apps/console/db/migrations/0006_watch.sql
Normal file
50
apps/console/db/migrations/0006_watch.sql
Normal file
@ -0,0 +1,50 @@
|
||||
-- Railyard Watch (Wave P PY2.2, RYP-E4): uptime checks and public status pages.
|
||||
-- Idempotent: every statement can run again without error or change. Not
|
||||
-- applied by agents to any hosted database; the owner applies it after 0005
|
||||
-- (owner step), agents only to a scratch Postgres.
|
||||
--
|
||||
-- watch_checks: one public https URL of one app; slug names its public status
|
||||
-- page. watch_status: the latest state, the last 90 results and the state the
|
||||
-- owner was last emailed about (one email per change).
|
||||
|
||||
create table if not exists railyard.watch_checks (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
org_id uuid not null references railyard.orgs (id) on delete cascade,
|
||||
app text not null check (app ~ '^[a-z0-9][a-z0-9-]{0,39}$'),
|
||||
name text not null check (length(name) between 1 and 60),
|
||||
url text not null check (url ~ '^https://' and length(url) <= 500),
|
||||
slug text not null unique check (slug ~ '^[a-z0-9][a-z0-9-]{2,60}$'),
|
||||
owner_email text check (owner_email is null or (length(owner_email) <= 254 and position('@' in owner_email) > 1)),
|
||||
paused boolean not null default false,
|
||||
created_at timestamptz not null default now(),
|
||||
unique (org_id, app, url)
|
||||
);
|
||||
create index if not exists watch_checks_org_idx on railyard.watch_checks (org_id);
|
||||
create index if not exists watch_checks_active_idx on railyard.watch_checks (created_at) where not paused;
|
||||
|
||||
create table if not exists railyard.watch_status (
|
||||
check_id uuid primary key references railyard.watch_checks (id) on delete cascade,
|
||||
state text not null default 'waiting' check (state in ('waiting', 'up', 'down')),
|
||||
consecutive_failures integer not null default 0 check (consecutive_failures >= 0),
|
||||
first_result_at timestamptz,
|
||||
last_checked_at timestamptz,
|
||||
last_change_at timestamptz,
|
||||
alerted_state text check (alerted_state is null or alerted_state in ('waiting', 'up', 'down')),
|
||||
history jsonb not null default '[]'::jsonb check (jsonb_typeof(history) = 'array' and jsonb_array_length(history) <= 90)
|
||||
);
|
||||
|
||||
alter table railyard.watch_checks enable row level security;
|
||||
alter table railyard.watch_status enable row level security;
|
||||
|
||||
do $$
|
||||
begin
|
||||
if exists (select 1 from pg_roles where rolname = 'anon') then
|
||||
execute 'revoke all on railyard.watch_checks, railyard.watch_status from anon';
|
||||
end if;
|
||||
if exists (select 1 from pg_roles where rolname = 'authenticated') then
|
||||
execute 'revoke all on railyard.watch_checks, railyard.watch_status from authenticated';
|
||||
end if;
|
||||
if exists (select 1 from pg_roles where rolname = 'service_role') then
|
||||
execute 'grant all on railyard.watch_checks, railyard.watch_status to service_role';
|
||||
end if;
|
||||
end $$;
|
||||
@ -40,6 +40,16 @@ export interface Config {
|
||||
bridgeAcceptLegacy: boolean;
|
||||
/** Insights tenant API (PY1.3); null keeps analytics proofs and pages off. */
|
||||
insightsApi: { url: string; token: string } | null;
|
||||
/**
|
||||
* Railyard Watch is shown and run only with RAILYARD_WATCH_LIVE=1 (denylist
|
||||
* rule railyard-slot-watch): set at deploy once the customer checks stack
|
||||
* passes its drill. Off: no checks run, no page, no email.
|
||||
*/
|
||||
watchLive: boolean;
|
||||
/** Railyard Watch (PY2.2): the box 1 agent's bearer token; null keeps the agent API off. */
|
||||
watchAgentToken: string | null;
|
||||
/** Rally Send for alert email (Wave E contract 5.2); null logs alerts instead. */
|
||||
rallySend: { url: string; key: string } | null;
|
||||
/** Railyard Flags backend (PY2.1): the Flagsmith server; null uses Railyard's own tables. */
|
||||
flags: { apiUrl: string; adminToken: string } | null;
|
||||
/** The AI gateway (PY1.4): Relay's tenant key and the sealing key; null keeps the gateway off (503). */
|
||||
@ -83,6 +93,12 @@ export function readConfig(env: Env = process.env): Config {
|
||||
env.INSIGHTS_API_URL?.trim() && env.INSIGHTS_API_TOKEN?.trim()
|
||||
? { url: env.INSIGHTS_API_URL.trim().replace(/\/$/, ""), token: env.INSIGHTS_API_TOKEN.trim() }
|
||||
: null,
|
||||
watchLive: env.RAILYARD_WATCH_LIVE === "1",
|
||||
watchAgentToken: env.WATCH_AGENT_TOKEN?.trim() && env.WATCH_AGENT_TOKEN.trim().length >= 32 ? env.WATCH_AGENT_TOKEN.trim() : null,
|
||||
rallySend:
|
||||
env.RALLY_TX_URL?.trim().startsWith("https://") && env.RALLY_TX_KEY?.trim()
|
||||
? { url: env.RALLY_TX_URL.trim(), key: env.RALLY_TX_KEY.trim() }
|
||||
: null,
|
||||
flags:
|
||||
env.FLAGS_API_URL?.trim() && env.FLAGS_ADMIN_TOKEN?.trim()
|
||||
? { apiUrl: env.FLAGS_API_URL.trim().replace(/\/$/, ""), adminToken: env.FLAGS_ADMIN_TOKEN.trim() }
|
||||
|
||||
@ -11,6 +11,9 @@ import { PostgrestFlagsStore } from "./flags/store.ts";
|
||||
import { TableFlagsBackend } from "./flags/table-backend.ts";
|
||||
import { FlagsmithBackend } from "./flags/flagsmith-backend.ts";
|
||||
import type { FlagsDeps } from "./flags/service.ts";
|
||||
import { PostgrestWatchStore } from "./watch/store.ts";
|
||||
import { noMailer, rallySend } from "./watch/mail.ts";
|
||||
import type { WatchDeps } from "./watch/service.ts";
|
||||
|
||||
export interface Deps {
|
||||
cfg: Config;
|
||||
@ -19,6 +22,7 @@ export interface Deps {
|
||||
sites: SitesStore;
|
||||
insights: InsightsClient | null;
|
||||
flags: FlagsDeps;
|
||||
watch: WatchDeps;
|
||||
}
|
||||
|
||||
function flagsDeps(cfg: Config): FlagsDeps {
|
||||
@ -33,13 +37,22 @@ let cached: Deps | null = null;
|
||||
export function deps(): Deps {
|
||||
if (cached) return cached;
|
||||
const cfg = readConfig();
|
||||
const repo = new PostgrestRepo({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey });
|
||||
cached = {
|
||||
cfg,
|
||||
repo: new PostgrestRepo({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey }),
|
||||
repo,
|
||||
dodo: new Dodo({ base: cfg.dodoBase, apiKey: cfg.dodoApiKey, allowLive: cfg.dodoAllowLive }),
|
||||
sites: kvSites(),
|
||||
insights: cfg.insightsApi ? insightsClient({ apiUrl: cfg.insightsApi.url, token: cfg.insightsApi.token }) : null,
|
||||
flags: flagsDeps(cfg),
|
||||
watch: {
|
||||
store: new PostgrestWatchStore({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey }),
|
||||
repo,
|
||||
mailer: cfg.rallySend ? rallySend(cfg.rallySend) : noMailer,
|
||||
consoleUrl: cfg.consoleUrl,
|
||||
agentToken: cfg.watchAgentToken,
|
||||
live: cfg.watchLive,
|
||||
},
|
||||
};
|
||||
return cached;
|
||||
}
|
||||
|
||||
55
apps/console/lib/watch/http.ts
Normal file
55
apps/console/lib/watch/http.ts
Normal file
@ -0,0 +1,55 @@
|
||||
// HTTP handlers for Railyard Watch (Wave P PY2.2), framework-free.
|
||||
|
||||
import type { Repo } from "../repo.ts";
|
||||
import { agentAuthorized, agentChecks, ARRIVING, createCheck, listWithState, recordResults, WatchError, type WatchDeps } from "./service.ts";
|
||||
|
||||
const reply = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
||||
|
||||
/** GET /api/v1/watch/agent/checks: the box 1 agent's list (bearer WATCH_AGENT_TOKEN). */
|
||||
export async function agentList(deps: WatchDeps, req: Request, now: Date): Promise<Response> {
|
||||
if (!deps.agentToken) return reply({ error: "watch_agent_not_configured" }, 503);
|
||||
if (!agentAuthorized(deps, req.headers.get("authorization"))) return reply({ error: "unauthorized" }, 401);
|
||||
return reply({ checks: await agentChecks(deps, now) });
|
||||
}
|
||||
|
||||
/** POST /api/v1/watch/agent/results: `{results:[{id, ok, at, ms}]}` from the agent. */
|
||||
export async function agentResults(deps: WatchDeps, req: Request, now: Date): Promise<Response> {
|
||||
if (!deps.agentToken) return reply({ error: "watch_agent_not_configured" }, 503);
|
||||
if (!agentAuthorized(deps, req.headers.get("authorization"))) return reply({ error: "unauthorized" }, 401);
|
||||
const body = await req.json().catch(() => null);
|
||||
try {
|
||||
return reply(await recordResults(deps, body, now));
|
||||
} catch (e) {
|
||||
if (e instanceof WatchError) return reply({ error: e.message }, e.status);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/watch (signed-in console user, same origin):
|
||||
* `{app, url, name?}` adds a check for one of the org's apps;
|
||||
* `{id, paused}` pauses or resumes one of the org's checks.
|
||||
*/
|
||||
export async function consoleWatch(
|
||||
deps: WatchDeps,
|
||||
repo: Repo,
|
||||
session: { org: string; email: string } | null,
|
||||
body: unknown,
|
||||
): Promise<{ status: number; body: Record<string, unknown> }> {
|
||||
if (!session) return { status: 401, body: { error: "Sign in again." } };
|
||||
if (!deps.live) return { status: 503, body: { error: ARRIVING } };
|
||||
const b = (body ?? {}) as Record<string, unknown>;
|
||||
try {
|
||||
if (typeof b.id === "string" && typeof b.paused === "boolean") {
|
||||
const c = await deps.store.setPaused(session.org, b.id, b.paused);
|
||||
return c ? { status: 200, body: { check: { id: c.id, paused: c.paused } } } : { status: 404, body: { error: "There is no such check in your organization." } };
|
||||
}
|
||||
if (typeof b.app !== "string" || !(await repo.findAppByName(session.org, b.app))) return { status: 404, body: { error: "Pick one of your apps." } };
|
||||
const email = /@/.test(session.email) && !session.email.endsWith(".invalid") ? session.email : null;
|
||||
const c = await createCheck(deps, { orgId: session.org, app: b.app, name: b.name, url: b.url, ownerEmail: email });
|
||||
return { status: 200, body: { checks: await listWithState(deps, session.org, c.app) } };
|
||||
} catch (e) {
|
||||
if (e instanceof WatchError) return { status: e.status, body: { error: e.message } };
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
42
apps/console/lib/watch/mail.ts
Normal file
42
apps/console/lib/watch/mail.ts
Normal file
@ -0,0 +1,42 @@
|
||||
// Alert email through Rally Send (Wave E contract 5.2): our own transactional
|
||||
// sender, product "railyard". RALLY_TX_URL and RALLY_TX_KEY on the console.
|
||||
|
||||
export interface Mailer {
|
||||
send(msg: { to: string; subject: string; text: string; html: string; idempotencyKey: string; project: string }): Promise<boolean>;
|
||||
}
|
||||
|
||||
type Fetch = typeof fetch;
|
||||
|
||||
export function rallySend(opts: { url: string; key: string; fetchImpl?: Fetch }): Mailer {
|
||||
return {
|
||||
async send(msg) {
|
||||
const res = await (opts.fetchImpl ?? fetch)(opts.url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", authorization: `Bearer ${opts.key}` },
|
||||
body: JSON.stringify({
|
||||
product: "railyard",
|
||||
project: msg.project,
|
||||
to: msg.to,
|
||||
from_local: "status",
|
||||
from_name: "Railyard status",
|
||||
subject: msg.subject,
|
||||
text: msg.text,
|
||||
html: msg.html,
|
||||
idempotency_key: msg.idempotencyKey,
|
||||
tags: ["watch"],
|
||||
}),
|
||||
});
|
||||
if (res.status === 202) return true;
|
||||
console.error(`watch alert not sent: Rally Send answered ${res.status}`);
|
||||
return false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** No sender configured: alerts are logged, never lost silently. */
|
||||
export const noMailer: Mailer = {
|
||||
async send(msg) {
|
||||
console.error(`watch alert not sent (no RALLY_TX_URL): ${msg.subject}`);
|
||||
return false;
|
||||
},
|
||||
};
|
||||
242
apps/console/lib/watch/service.ts
Normal file
242
apps/console/lib/watch/service.ts
Normal file
@ -0,0 +1,242 @@
|
||||
// Railyard Watch service (Wave P PY2.2): checks, the agent's list and
|
||||
// results, state changes with owner email, and the public status view.
|
||||
|
||||
import { access } from "../ladder.ts";
|
||||
import { constantTimeEqual, randomToken } from "../crypto.ts";
|
||||
import type { Repo } from "../repo.ts";
|
||||
import type { Entitlement } from "../types.ts";
|
||||
import type { Mailer } from "./mail.ts";
|
||||
import type { WatchStore } from "./store.ts";
|
||||
import {
|
||||
CHECK_NAME,
|
||||
FAILS_TO_DOWN,
|
||||
HISTORY,
|
||||
MAX_CHECKS_PER_ORG,
|
||||
SLUG,
|
||||
type AgentResult,
|
||||
type Check,
|
||||
type CheckState,
|
||||
type CheckStatus,
|
||||
} from "./types.ts";
|
||||
|
||||
export interface WatchDeps {
|
||||
store: WatchStore;
|
||||
repo: Repo;
|
||||
mailer: Mailer;
|
||||
consoleUrl: string;
|
||||
/** The agent's bearer token (WATCH_AGENT_TOKEN); null keeps the agent API off. */
|
||||
agentToken: string | null;
|
||||
/** RAILYARD_WATCH_LIVE: off, nothing runs and nothing customer-visible is shown. */
|
||||
live: boolean;
|
||||
}
|
||||
|
||||
/** The one answer while Watch is off (neutral copy: the slot is arriving). */
|
||||
export const ARRIVING = "This slot is arriving (PY2.2). Nothing was changed.";
|
||||
|
||||
export class WatchError extends Error {
|
||||
readonly status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
|
||||
const BLOCKED_SUFFIX = /(^|\.)(localhost|local|internal|intranet|lan|home|corp|arpa|invalid|test|example|onion|ereboslab\.com)$/i;
|
||||
|
||||
/** A public https URL we may check from our box, or the reason it is refused. */
|
||||
export function checkUrl(raw: unknown): string | WatchError {
|
||||
if (typeof raw !== "string" || raw.length > 500) return new WatchError(400, "Give the https address of your app, for example https://shop.example.com.");
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(raw.trim());
|
||||
} catch {
|
||||
return new WatchError(400, "That is not a web address. Give the https address of your app.");
|
||||
}
|
||||
if (u.protocol !== "https:") return new WatchError(400, "Only https addresses can be checked.");
|
||||
if (u.username || u.password) return new WatchError(400, "Remove the user name and password from the address.");
|
||||
if (u.port && u.port !== "443" && u.port !== "8443") return new WatchError(400, "Use the standard https port.");
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (!host.includes(".") || IPV4.test(host) || host.startsWith("[") || BLOCKED_SUFFIX.test(host)) {
|
||||
return new WatchError(400, "Give the public name of your app (not an IP address or a private name).");
|
||||
}
|
||||
u.hash = "";
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
/** Whether an org may run checks now: an active plan, or the add-on with the uptime slot. */
|
||||
export function watchAllowed(ent: Entitlement | null, now: Date): boolean {
|
||||
const a = access(ent, now);
|
||||
if (a.state !== "active" && a.state !== "cancelling" && a.state !== "trial") return false;
|
||||
return ent?.plan !== "addon" || (ent.addon_slots ?? []).includes("uptime");
|
||||
}
|
||||
|
||||
function slugFor(app: string): string {
|
||||
const base = app.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "app";
|
||||
return `${base}-${randomToken(6).toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 6).padEnd(6, "0")}`;
|
||||
}
|
||||
|
||||
export async function createCheck(
|
||||
deps: WatchDeps,
|
||||
input: { orgId: string; app: string; name?: unknown; url: unknown; ownerEmail: string | null },
|
||||
): Promise<Check> {
|
||||
if (!deps.live) throw new WatchError(503, ARRIVING);
|
||||
const url = checkUrl(input.url);
|
||||
if (url instanceof WatchError) throw url;
|
||||
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : input.app;
|
||||
if (!CHECK_NAME.test(name)) throw new WatchError(400, "The name can use letters, digits, spaces, dots, dashes and apostrophes (60 at most).");
|
||||
if (input.ownerEmail !== null && !/^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(input.ownerEmail)) throw new WatchError(400, "The owner email is not an address.");
|
||||
const existing = await deps.store.listChecks(input.orgId);
|
||||
const same = existing.find((c) => c.app === input.app && c.url === url);
|
||||
if (same) return same;
|
||||
if (existing.length >= MAX_CHECKS_PER_ORG) throw new WatchError(409, `An organization can have ${MAX_CHECKS_PER_ORG} checks.`);
|
||||
let slug = slugFor(input.app);
|
||||
for (let i = 0; i < 3 && (await deps.store.findCheckBySlug(slug)); i++) slug = slugFor(input.app);
|
||||
if (!SLUG.test(slug)) throw new WatchError(500, "Could not create the check. Try again.");
|
||||
return deps.store.createCheck({ org_id: input.orgId, app: input.app, name, url, slug, owner_email: input.ownerEmail, paused: false });
|
||||
}
|
||||
|
||||
export function statusUrl(deps: Pick<WatchDeps, "consoleUrl">, check: Check): string {
|
||||
return `${deps.consoleUrl}/status/${check.slug}`;
|
||||
}
|
||||
|
||||
export function agentAuthorized(deps: Pick<WatchDeps, "agentToken">, header: string | null): boolean {
|
||||
if (!deps.agentToken || !header?.startsWith("Bearer ")) return false;
|
||||
return constantTimeEqual(header.slice(7).trim(), deps.agentToken);
|
||||
}
|
||||
|
||||
/** The agent's list: id and URL only (no customer text reaches the checker's config). */
|
||||
export async function agentChecks(deps: WatchDeps, now: Date): Promise<{ id: string; url: string; interval_s: number }[]> {
|
||||
if (!deps.live) return [];
|
||||
const checks = await deps.store.activeChecks();
|
||||
const allowed = new Map<string, boolean>();
|
||||
const out: { id: string; url: string; interval_s: number }[] = [];
|
||||
for (const c of checks) {
|
||||
if (!allowed.has(c.org_id)) allowed.set(c.org_id, watchAllowed(await deps.repo.getEntitlement(c.org_id), now));
|
||||
if (allowed.get(c.org_id)) out.push({ id: c.id, url: c.url, interval_s: 60 });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function emptyStatus(checkId: string): CheckStatus {
|
||||
return { check_id: checkId, state: "waiting", consecutive_failures: 0, first_result_at: null, last_checked_at: null, last_change_at: null, alerted_state: null, history: [] };
|
||||
}
|
||||
|
||||
/** The next status after one result (pure). */
|
||||
export function nextStatus(prev: CheckStatus, r: AgentResult): CheckStatus {
|
||||
const failures = r.ok ? 0 : prev.consecutive_failures + 1;
|
||||
let state: CheckState = prev.state;
|
||||
if (r.ok) state = "up";
|
||||
else if (failures >= FAILS_TO_DOWN) state = "down";
|
||||
const history = [...prev.history, { at: r.at, ok: r.ok, ms: Math.max(0, Math.round(r.ms)) }].slice(-HISTORY);
|
||||
return {
|
||||
...prev,
|
||||
state,
|
||||
consecutive_failures: failures,
|
||||
first_result_at: prev.first_result_at ?? r.at,
|
||||
last_checked_at: r.at,
|
||||
last_change_at: state !== prev.state ? r.at : prev.last_change_at,
|
||||
history,
|
||||
};
|
||||
}
|
||||
|
||||
function alertText(check: Check, state: CheckState, statusPage: string): { subject: string; text: string; html: string } {
|
||||
const down = state === "down";
|
||||
const subject = down ? `${check.name} is down` : `${check.name} is back up`;
|
||||
const line = down
|
||||
? `${check.name} did not answer our last two checks. We will email you again when it is back.`
|
||||
: `${check.name} answered our last check again.`;
|
||||
const text = `${line}\n\nStatus page: ${statusPage}\n`;
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
const html = `<p>${esc(line)}</p><p><a href="${esc(statusPage)}">Status page</a></p>`;
|
||||
return { subject, text, html };
|
||||
}
|
||||
|
||||
function parseResult(raw: unknown): AgentResult | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const r = raw as Record<string, unknown>;
|
||||
if (typeof r.id !== "string" || !/^[0-9a-f-]{36}$/.test(r.id)) return null;
|
||||
if (typeof r.ok !== "boolean" || typeof r.at !== "string" || Number.isNaN(Date.parse(r.at))) return null;
|
||||
const ms = typeof r.ms === "number" && Number.isFinite(r.ms) ? r.ms : 0;
|
||||
return { id: r.id, ok: r.ok, at: new Date(r.at).toISOString(), ms };
|
||||
}
|
||||
|
||||
/** Applies the agent's results in time order; emails the owner once per change. */
|
||||
export async function recordResults(deps: WatchDeps, body: unknown, now: Date): Promise<{ accepted: number; ignored: number; emailed: number }> {
|
||||
if (!deps.live) throw new WatchError(503, ARRIVING);
|
||||
const list = (body as { results?: unknown })?.results;
|
||||
if (!Array.isArray(list) || list.length > 5000) throw new WatchError(400, "results must be a list of at most 5000 entries");
|
||||
const results = list.map(parseResult);
|
||||
const valid = results.filter((r): r is AgentResult => r !== null).sort((a, b) => (a.at < b.at ? -1 : 1));
|
||||
let accepted = 0;
|
||||
let emailed = 0;
|
||||
const skew = now.getTime() + 5 * 60_000;
|
||||
for (const r of valid) {
|
||||
if (Date.parse(r.at) > skew) continue;
|
||||
const check = await deps.store.getCheck(r.id);
|
||||
if (!check || check.paused) continue;
|
||||
const prev = (await deps.store.getStatus(r.id)) ?? emptyStatus(r.id);
|
||||
if (prev.last_checked_at && r.at <= prev.last_checked_at) continue;
|
||||
let next = nextStatus(prev, r);
|
||||
const alertable = next.state === "down" || (next.state === "up" && next.alerted_state === "down");
|
||||
if (next.state !== next.alerted_state && alertable && check.owner_email) {
|
||||
const page = statusUrl(deps, check);
|
||||
const msg = alertText(check, next.state, page);
|
||||
const sent = await deps.mailer.send({ to: check.owner_email, ...msg, idempotencyKey: `watch:${check.id}:${next.state}:${next.last_change_at}`, project: check.org_id });
|
||||
if (sent) {
|
||||
next = { ...next, alerted_state: next.state };
|
||||
emailed += 1;
|
||||
}
|
||||
} else if (next.state === "up" && next.alerted_state === null) {
|
||||
next = { ...next, alerted_state: "up" };
|
||||
}
|
||||
await deps.store.saveStatus(next);
|
||||
accepted += 1;
|
||||
}
|
||||
return { accepted, ignored: list.length - accepted, emailed };
|
||||
}
|
||||
|
||||
export interface StatusView {
|
||||
name: string;
|
||||
state: CheckState;
|
||||
label: string;
|
||||
uptime: string | null;
|
||||
lastChecked: string | null;
|
||||
bars: { ok: boolean; at: string }[];
|
||||
}
|
||||
|
||||
/** What /status/<slug> shows: live results only, the check's name, never its address. */
|
||||
export function statusView(check: Check, status: CheckStatus | null): StatusView {
|
||||
const s = status ?? emptyStatus(check.id);
|
||||
const ok = s.history.filter((h) => h.ok).length;
|
||||
const label = s.state === "up" ? "Operational" : s.state === "down" ? "Down" : "Waiting for the first check";
|
||||
return {
|
||||
name: check.name,
|
||||
state: s.state,
|
||||
label,
|
||||
uptime: s.history.length ? `${((ok / s.history.length) * 100).toFixed(s.history.length >= 10 ? 1 : 0)}% of the last ${s.history.length} checks` : null,
|
||||
lastChecked: s.last_checked_at ? `${s.last_checked_at.slice(0, 16).replace("T", " ")} UTC` : null,
|
||||
bars: s.history.map((h) => ({ ok: h.ok, at: h.at })),
|
||||
};
|
||||
}
|
||||
|
||||
/** The org's checks with their state, for the console and the bridge. */
|
||||
export async function listWithState(deps: WatchDeps, orgId: string, app?: string) {
|
||||
const checks = (await deps.store.listChecks(orgId)).filter((c) => !app || c.app === app);
|
||||
return Promise.all(
|
||||
checks.map(async (c) => {
|
||||
const st = await deps.store.getStatus(c.id);
|
||||
return {
|
||||
id: c.id,
|
||||
app: c.app,
|
||||
name: c.name,
|
||||
url: c.url,
|
||||
paused: c.paused,
|
||||
state: st?.state ?? "waiting",
|
||||
first_result_at: st?.first_result_at ?? null,
|
||||
last_checked_at: st?.last_checked_at ?? null,
|
||||
status_url: statusUrl(deps, c),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
110
apps/console/lib/watch/store.ts
Normal file
110
apps/console/lib/watch/store.ts
Normal file
@ -0,0 +1,110 @@
|
||||
// Storage for Railyard Watch: MemoryWatchStore for tests and local dev,
|
||||
// PostgrestWatchStore for the console's Scribase project (migration 0006).
|
||||
|
||||
import type { Check, CheckStatus } from "./types.ts";
|
||||
|
||||
export interface WatchStore {
|
||||
createCheck(input: Omit<Check, "id" | "created_at">): Promise<Check>;
|
||||
listChecks(orgId: string): Promise<Check[]>;
|
||||
getCheck(id: string): Promise<Check | null>;
|
||||
findCheckBySlug(slug: string): Promise<Check | null>;
|
||||
/** Every check that is not paused (the agent's list). */
|
||||
activeChecks(): Promise<Check[]>;
|
||||
setPaused(orgId: string, id: string, paused: boolean): Promise<Check | null>;
|
||||
getStatus(checkId: string): Promise<CheckStatus | null>;
|
||||
saveStatus(status: CheckStatus): Promise<void>;
|
||||
}
|
||||
|
||||
const clone = <T>(v: T): T => structuredClone(v);
|
||||
|
||||
export class MemoryWatchStore implements WatchStore {
|
||||
checks: Check[] = [];
|
||||
statuses = new Map<string, CheckStatus>();
|
||||
async createCheck(input: Omit<Check, "id" | "created_at">) {
|
||||
if (this.checks.some((c) => c.slug === input.slug)) throw new Error("duplicate slug");
|
||||
const row: Check = { ...clone(input), id: crypto.randomUUID(), created_at: new Date().toISOString() };
|
||||
this.checks = [...this.checks, row];
|
||||
return clone(row);
|
||||
}
|
||||
async listChecks(orgId: string) {
|
||||
return clone(this.checks.filter((c) => c.org_id === orgId));
|
||||
}
|
||||
async getCheck(id: string) {
|
||||
return clone(this.checks.find((c) => c.id === id) ?? null);
|
||||
}
|
||||
async findCheckBySlug(slug: string) {
|
||||
return clone(this.checks.find((c) => c.slug === slug) ?? null);
|
||||
}
|
||||
async activeChecks() {
|
||||
return clone(this.checks.filter((c) => !c.paused));
|
||||
}
|
||||
async setPaused(orgId: string, id: string, paused: boolean) {
|
||||
const found = this.checks.find((c) => c.id === id && c.org_id === orgId);
|
||||
if (!found) return null;
|
||||
this.checks = this.checks.map((c) => (c.id === id ? { ...c, paused } : c));
|
||||
return clone({ ...found, paused });
|
||||
}
|
||||
async getStatus(checkId: string) {
|
||||
return clone(this.statuses.get(checkId) ?? null);
|
||||
}
|
||||
async saveStatus(status: CheckStatus) {
|
||||
this.statuses.set(status.check_id, clone(status));
|
||||
}
|
||||
}
|
||||
|
||||
type Fetch = typeof fetch;
|
||||
|
||||
export class PostgrestWatchStore implements WatchStore {
|
||||
base: string;
|
||||
key: string;
|
||||
fetchImpl: Fetch;
|
||||
|
||||
constructor(opts: { url: string; serviceRoleKey: string; fetchImpl?: Fetch }) {
|
||||
this.base = `${opts.url.replace(/\/$/, "")}/rest/v1`;
|
||||
this.key = opts.serviceRoleKey;
|
||||
this.fetchImpl = opts.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async req<T>(method: string, path: string, body?: unknown, prefer?: string): Promise<T[]> {
|
||||
const headers: Record<string, string> = {
|
||||
apikey: this.key,
|
||||
authorization: `Bearer ${this.key}`,
|
||||
"accept-profile": "railyard",
|
||||
"content-profile": "railyard",
|
||||
"content-type": "application/json",
|
||||
};
|
||||
if (prefer) headers.prefer = prefer;
|
||||
const res = await this.fetchImpl(`${this.base}/${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
if (!res.ok) throw new Error(`database ${method} ${path.split("?")[0]} failed with ${res.status}`);
|
||||
const text = await res.text();
|
||||
return text ? (JSON.parse(text) as T[]) : [];
|
||||
}
|
||||
|
||||
async createCheck(input: Omit<Check, "id" | "created_at">) {
|
||||
const rows = await this.req<Check>("POST", "watch_checks", input, "return=representation");
|
||||
if (!rows[0]) throw new Error("could not create the check");
|
||||
return rows[0];
|
||||
}
|
||||
async listChecks(orgId: string) {
|
||||
return this.req<Check>("GET", `watch_checks?org_id=eq.${encodeURIComponent(orgId)}&order=created_at.asc`);
|
||||
}
|
||||
async getCheck(id: string) {
|
||||
return (await this.req<Check>("GET", `watch_checks?id=eq.${encodeURIComponent(id)}&limit=1`))[0] ?? null;
|
||||
}
|
||||
async findCheckBySlug(slug: string) {
|
||||
return (await this.req<Check>("GET", `watch_checks?slug=eq.${encodeURIComponent(slug)}&limit=1`))[0] ?? null;
|
||||
}
|
||||
async activeChecks() {
|
||||
return this.req<Check>("GET", "watch_checks?paused=is.false&order=created_at.asc&limit=10000");
|
||||
}
|
||||
async setPaused(orgId: string, id: string, paused: boolean) {
|
||||
const rows = await this.req<Check>("PATCH", `watch_checks?id=eq.${encodeURIComponent(id)}&org_id=eq.${encodeURIComponent(orgId)}`, { paused }, "return=representation");
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
async getStatus(checkId: string) {
|
||||
return (await this.req<CheckStatus>("GET", `watch_status?check_id=eq.${encodeURIComponent(checkId)}&limit=1`))[0] ?? null;
|
||||
}
|
||||
async saveStatus(status: CheckStatus) {
|
||||
await this.req("POST", "watch_status?on_conflict=check_id", status, "resolution=merge-duplicates,return=minimal");
|
||||
}
|
||||
}
|
||||
53
apps/console/lib/watch/types.ts
Normal file
53
apps/console/lib/watch/types.ts
Normal file
@ -0,0 +1,53 @@
|
||||
// Railyard Watch (Wave P PY2.2, RYP-E4): uptime checks and public status pages.
|
||||
//
|
||||
// A check is one public https URL of one app. The customer checks run on a
|
||||
// Gatus instance of their own on box 1 (never the one behind our own status
|
||||
// page); an agent next to it pulls the list of checks from this console and
|
||||
// pushes each result back. The console keeps the latest results, flips the
|
||||
// state after two failures in a row, emails the owner through Rally Send on
|
||||
// each change, and renders /status/<slug> from live results only.
|
||||
|
||||
export const CHECK_NAME = /^[\p{L}\p{N}][\p{L}\p{N} ._'-]{0,59}$/u;
|
||||
export const SLUG = /^[a-z0-9][a-z0-9-]{2,60}$/;
|
||||
export const HISTORY = 90;
|
||||
export const FAILS_TO_DOWN = 2;
|
||||
export const MAX_CHECKS_PER_ORG = 20;
|
||||
|
||||
export type CheckState = "waiting" | "up" | "down";
|
||||
|
||||
export interface Check {
|
||||
id: string;
|
||||
org_id: string;
|
||||
app: string;
|
||||
name: string;
|
||||
url: string;
|
||||
slug: string;
|
||||
owner_email: string | null;
|
||||
paused: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ResultPoint {
|
||||
at: string;
|
||||
ok: boolean;
|
||||
ms: number;
|
||||
}
|
||||
|
||||
export interface CheckStatus {
|
||||
check_id: string;
|
||||
state: CheckState;
|
||||
consecutive_failures: number;
|
||||
first_result_at: string | null;
|
||||
last_checked_at: string | null;
|
||||
last_change_at: string | null;
|
||||
/** The state the owner was last emailed about. */
|
||||
alerted_state: CheckState | null;
|
||||
history: ResultPoint[];
|
||||
}
|
||||
|
||||
export interface AgentResult {
|
||||
id: string;
|
||||
ok: boolean;
|
||||
at: string;
|
||||
ms: number;
|
||||
}
|
||||
161
apps/console/lib/watch/watch.test.ts
Normal file
161
apps/console/lib/watch/watch.test.ts
Normal file
@ -0,0 +1,161 @@
|
||||
// Railyard Watch (Wave P PY2.2): checks, the agent's list, results with state
|
||||
// changes and owner email through Rally Send, and the public status view.
|
||||
// node --test lib/watch/watch.test.ts
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { MemoryRepo } from "../repo.ts";
|
||||
import { emptyEntitlement } from "../types.ts";
|
||||
import { MemoryWatchStore, PostgrestWatchStore } from "./store.ts";
|
||||
import { rallySend, type Mailer } from "./mail.ts";
|
||||
import { agentAuthorized, agentChecks, checkUrl, createCheck, listWithState, nextStatus, recordResults, statusView, watchAllowed, WatchError, type WatchDeps } from "./service.ts";
|
||||
|
||||
const T0 = new Date("2026-09-29T12:00:00Z");
|
||||
const at = (min: number) => new Date(T0.getTime() + min * 60_000).toISOString();
|
||||
|
||||
function setup() {
|
||||
const repo = new MemoryRepo(() => T0);
|
||||
const store = new MemoryWatchStore();
|
||||
const sent: { to: string; subject: string; idempotencyKey: string; text: string }[] = [];
|
||||
const mailer: Mailer = { send: async (m) => (sent.push(m), true) };
|
||||
const deps: WatchDeps = { store, repo, mailer, consoleUrl: "https://railyard.example", agentToken: "agent-token-0123456789", live: true };
|
||||
return { repo, store, sent, deps };
|
||||
}
|
||||
|
||||
async function addonOrg(repo: MemoryRepo, slots = ["uptime"], active = true) {
|
||||
const org = await repo.createOrgForUser({ userId: crypto.randomUUID(), email: "x@scribase.invalid", name: "Acme" });
|
||||
await repo.saveEntitlement({ ...emptyEntitlement(org.id, T0), plan: "addon", status: active ? "active" : "inactive", addon_slots: slots });
|
||||
return org.id;
|
||||
}
|
||||
|
||||
test("checkUrl takes public https app addresses only", () => {
|
||||
assert.equal(checkUrl("https://shop.example.com/health#x"), "https://shop.example.com/health");
|
||||
for (const bad of ["http://shop.example.com", "https://127.0.0.1", "https://localhost", "https://[::1]/", "https://db.internal", "https://u:p@shop.example.com", "https://shop.example.com:5432", "https://relay.ereboslab.com", "nope", 3, "https://intranet"]) {
|
||||
assert.ok(checkUrl(bad) instanceof WatchError, String(bad));
|
||||
}
|
||||
});
|
||||
|
||||
test("create: one check per app and URL, a status page slug, the per-org cap, only the uptime slot's orgs are checked", async () => {
|
||||
const { repo, deps } = setup();
|
||||
const org = await addonOrg(repo);
|
||||
const c = await createCheck(deps, { orgId: org, app: "shop", url: "https://shop.example.com", ownerEmail: "owner@example.com" });
|
||||
assert.match(c.slug, /^shop-[a-z0-9]{6}$/);
|
||||
assert.equal((await createCheck(deps, { orgId: org, app: "shop", url: "https://shop.example.com", ownerEmail: null })).id, c.id, "idempotent");
|
||||
const other = await addonOrg(repo, ["deploy"]);
|
||||
await createCheck(deps, { orgId: other, app: "blog", url: "https://blog.example.com", ownerEmail: null });
|
||||
const lapsed = await addonOrg(repo, ["uptime"], false);
|
||||
await createCheck(deps, { orgId: lapsed, app: "old", url: "https://old.example.com", ownerEmail: null });
|
||||
assert.deepEqual((await agentChecks(deps, T0)).map((x) => x.url), ["https://shop.example.com/"]);
|
||||
await assert.rejects(createCheck(deps, { orgId: org, app: "shop", url: "http://x.example.com", ownerEmail: null }), (e: WatchError) => e.status === 400);
|
||||
await assert.rejects(createCheck(deps, { orgId: org, app: "shop", name: "<b>", url: "https://y.example.com", ownerEmail: null }), (e: WatchError) => e.status === 400);
|
||||
for (let i = 1; i < 20; i++) await createCheck(deps, { orgId: org, app: `a${i}`, url: `https://a${i}.example.com`, ownerEmail: null });
|
||||
await assert.rejects(createCheck(deps, { orgId: org, app: "one-more", url: "https://z.example.com", ownerEmail: null }), (e: WatchError) => e.status === 409);
|
||||
});
|
||||
|
||||
test("results: red after two failures, one email per change through Rally Send, back up emails once more", async () => {
|
||||
const { repo, deps, sent, store } = setup();
|
||||
const org = await addonOrg(repo);
|
||||
const c = await createCheck(deps, { orgId: org, app: "shop", url: "https://shop.example.com", ownerEmail: "owner@example.com" });
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: true, at: at(0), ms: 120 }] }, new Date(at(0)));
|
||||
assert.equal(sent.length, 0, "first up is not news");
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: false, at: at(1), ms: 10_000 }] }, new Date(at(1)));
|
||||
assert.equal((await store.getStatus(c.id))?.state, "up", "one failure is not down");
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: false, at: at(2), ms: 10_000 }] }, new Date(at(2)));
|
||||
assert.equal((await store.getStatus(c.id))?.state, "down");
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(sent[0].to, "owner@example.com");
|
||||
assert.equal(sent[0].subject, "shop is down");
|
||||
assert.match(sent[0].text, /https:\/\/railyard\.example\/status\/shop-/);
|
||||
assert.doesNotMatch(sent[0].text, /shop\.example\.com/, "the email names no host");
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: false, at: at(3), ms: 10_000 }] }, new Date(at(3)));
|
||||
assert.equal(sent.length, 1, "still down: no second email");
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: true, at: at(4), ms: 90 }, { id: c.id, ok: true, at: at(3.5), ms: 90 }] }, new Date(at(4)));
|
||||
assert.equal(sent.length, 2);
|
||||
assert.equal(sent[1].subject, "shop is back up");
|
||||
// Red within 5 minutes of the app stopping: results every minute, two failures.
|
||||
const status = (await store.getStatus(c.id))!;
|
||||
assert.equal(status.state, "up");
|
||||
assert.equal(status.first_result_at, at(0));
|
||||
});
|
||||
|
||||
test("results: a failed email is retried on the next result with the same idempotency key; stale and foreign results are ignored", async () => {
|
||||
const { repo, deps, store } = setup();
|
||||
const org = await addonOrg(repo);
|
||||
const c = await createCheck(deps, { orgId: org, app: "shop", url: "https://shop.example.com", ownerEmail: "owner@example.com" });
|
||||
const keys: string[] = [];
|
||||
let ok = false;
|
||||
deps.mailer = { send: async (m) => (keys.push(m.idempotencyKey), ok) };
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: false, at: at(0), ms: 1 }, { id: c.id, ok: false, at: at(1), ms: 1 }] }, new Date(at(1)));
|
||||
ok = true;
|
||||
await recordResults(deps, { results: [{ id: c.id, ok: false, at: at(2), ms: 1 }] }, new Date(at(2)));
|
||||
assert.equal(keys.length, 2);
|
||||
assert.equal(keys[0], keys[1]);
|
||||
assert.equal((await store.getStatus(c.id))?.alerted_state, "down");
|
||||
const r = await recordResults(deps, { results: [{ id: c.id, ok: true, at: at(1.5), ms: 1 }, { id: crypto.randomUUID(), ok: true, at: at(3), ms: 1 }, { id: c.id, ok: true, at: at(90), ms: 1 }, { nope: 1 }] }, new Date(at(3)));
|
||||
assert.equal(r.accepted, 0, "older, unknown, future and malformed results change nothing");
|
||||
await assert.rejects(recordResults(deps, { results: "x" }, T0), (e: WatchError) => e.status === 400);
|
||||
});
|
||||
|
||||
test("status view: live results only, the name and never the address", async () => {
|
||||
const { repo, deps, store } = setup();
|
||||
const org = await addonOrg(repo);
|
||||
const c = await createCheck(deps, { orgId: org, app: "shop", name: "Shop", url: "https://shop.example.com", ownerEmail: null });
|
||||
assert.equal(statusView(c, null).label, "Waiting for the first check");
|
||||
await recordResults(deps, { results: Array.from({ length: 10 }, (_, i) => ({ id: c.id, ok: i !== 3, at: at(i), ms: 100 })) }, new Date(at(10)));
|
||||
const v = statusView(c, await store.getStatus(c.id));
|
||||
assert.equal(v.label, "Operational");
|
||||
assert.equal(v.uptime, "90.0% of the last 10 checks");
|
||||
assert.equal(v.bars.length, 10);
|
||||
assert.doesNotMatch(JSON.stringify(v), /example\.com/);
|
||||
const listed = await listWithState(deps, org);
|
||||
assert.equal(listed[0].state, "up");
|
||||
assert.match(listed[0].status_url, /\/status\/shop-/);
|
||||
});
|
||||
|
||||
test("the agent needs its bearer token; nextStatus keeps 90 points", () => {
|
||||
const deps = { agentToken: "agent-token-0123456789", live: true };
|
||||
assert.equal(agentAuthorized(deps, "Bearer agent-token-0123456789"), true);
|
||||
assert.equal(agentAuthorized(deps, "Bearer wrong"), false);
|
||||
assert.equal(agentAuthorized({ agentToken: null }, "Bearer x"), false);
|
||||
let s = { check_id: "c", state: "waiting" as const, consecutive_failures: 0, first_result_at: null, last_checked_at: null, last_change_at: null, alerted_state: null, history: [] };
|
||||
let cur: ReturnType<typeof nextStatus> = s;
|
||||
for (let i = 0; i < 120; i++) cur = nextStatus(cur, { id: "c", ok: true, at: at(i), ms: 1 });
|
||||
assert.equal(cur.history.length, 90);
|
||||
void s;
|
||||
});
|
||||
|
||||
test("watchAllowed: a Railyard plan or the add-on with uptime", () => {
|
||||
assert.equal(watchAllowed(null, T0), false);
|
||||
assert.equal(watchAllowed({ ...emptyEntitlement("o", T0), plan: "railyard", status: "active" }, T0), true);
|
||||
assert.equal(watchAllowed({ ...emptyEntitlement("o", T0), plan: "addon", status: "active", addon_slots: ["deploy"] }, T0), false);
|
||||
});
|
||||
|
||||
test("Rally Send: product railyard, from status, the key only in the header", async () => {
|
||||
const calls: { url: string; init: RequestInit }[] = [];
|
||||
const m = rallySend({ url: "https://vcpeer.example/api/rally/v1/transactional/send", key: "tx-key", fetchImpl: (async (url: string, init: RequestInit) => (calls.push({ url, init }), new Response("{}", { status: 202 }))) as typeof fetch });
|
||||
assert.equal(await m.send({ to: "a@example.com", subject: "s", text: "t", html: "<p>t</p>", idempotencyKey: "watch:1:down:x", project: "org1" }), true);
|
||||
const body = JSON.parse(String(calls[0].init.body));
|
||||
assert.equal(body.product, "railyard");
|
||||
assert.equal(body.from_local, "status");
|
||||
assert.equal(new Headers(calls[0].init.headers).get("authorization"), "Bearer tx-key");
|
||||
assert.ok(!String(calls[0].init.body).includes("tx-key"));
|
||||
});
|
||||
|
||||
test("the PostgREST store: schema railyard; pausing is scoped to the org", async () => {
|
||||
const urls: string[] = [];
|
||||
const store = new PostgrestWatchStore({ url: "https://p", serviceRoleKey: "k", fetchImpl: (async (url: string) => (urls.push(url), new Response("[]", { status: 200 }))) as typeof fetch });
|
||||
assert.equal(await store.setPaused("org1", "c1", true), null);
|
||||
assert.equal(urls[0], "https://p/rest/v1/watch_checks?id=eq.c1&org_id=eq.org1");
|
||||
await store.activeChecks();
|
||||
assert.match(urls[1], /watch_checks\?paused=is\.false/);
|
||||
});
|
||||
|
||||
test("RAILYARD_WATCH_LIVE off: no check is made, the agent gets an empty list, results are refused", async () => {
|
||||
const { repo, deps } = setup();
|
||||
const org = await addonOrg(repo);
|
||||
const c = await createCheck(deps, { orgId: org, app: "shop", url: "https://shop.example.com", ownerEmail: null });
|
||||
const off: WatchDeps = { ...deps, live: false };
|
||||
await assert.rejects(createCheck(off, { orgId: org, app: "blog", url: "https://blog.example.com", ownerEmail: null }), (e: WatchError) => e.status === 503 && /arriving/.test(e.message));
|
||||
assert.deepEqual(await agentChecks(off, T0), []);
|
||||
await assert.rejects(recordResults(off, { results: [{ id: c.id, ok: true, at: at(0), ms: 1 }] }, T0), (e: WatchError) => e.status === 503);
|
||||
});
|
||||
@ -10,7 +10,7 @@
|
||||
"cf:build": "opennextjs-cloudflare build",
|
||||
"cf:deploy": "opennextjs-cloudflare deploy",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "node --test test/*.test.ts app/api/v1/deploys/*.test.ts app/api/v1/bridge/scribase/*.test.ts lib/ai/*.test.ts lib/flags/*.test.ts",
|
||||
"test": "node --test test/*.test.ts app/api/v1/deploys/*.test.ts app/api/v1/bridge/scribase/*.test.ts lib/ai/*.test.ts lib/flags/*.test.ts lib/watch/*.test.ts",
|
||||
"test:bundle": "node --test test/bundle-secrets.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@ -14,6 +14,7 @@ const BRIDGE = join(ROOT, "db/migrations/0002_scribase_bridge.sql");
|
||||
const AI = join(ROOT, "db/migrations/0003_ai_gateway.sql");
|
||||
const ORDER = join(ROOT, "db/migrations/0004_bridge_order.sql");
|
||||
const FLAGS = join(ROOT, "db/migrations/0005_flags.sql");
|
||||
const WATCH = join(ROOT, "db/migrations/0006_watch.sql");
|
||||
const have = spawnSync("pg_ctl", ["--version"]).status === 0 && spawnSync("initdb", ["--version"]).status === 0;
|
||||
|
||||
test("0001 applies twice on a scratch cluster; RLS on; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
|
||||
@ -144,3 +145,28 @@ test("0005 (flags, PY2.1) applies twice; one env per org/app/env; keys and flag
|
||||
const noRls = psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim();
|
||||
assert.equal(noRls, "0");
|
||||
});
|
||||
|
||||
test("0006 (watch, PY2.2) applies twice; https only; one status page per slug; history capped; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
|
||||
const port = String(49000 + Math.floor(Math.random() * 1900));
|
||||
after(() => {
|
||||
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
|
||||
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
|
||||
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
|
||||
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
|
||||
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH]) psql(["-f", f]);
|
||||
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
|
||||
const id = psql(["-c", `insert into railyard.watch_checks (org_id, app, name, url, slug) values ('${org}', 'shop', 'Shop', 'https://shop.example.com/', 'shop-abc123') returning id`]).trim();
|
||||
assert.throws(() => psql(["-c", `insert into railyard.watch_checks (org_id, app, name, url, slug) values ('${org}', 'blog', 'Blog', 'http://blog.example.com/', 'blog-abc123')`]), /check constraint/);
|
||||
assert.throws(() => psql(["-c", `insert into railyard.watch_checks (org_id, app, name, url, slug) values ('${org}', 'blog', 'Blog', 'https://blog.example.com/', 'shop-abc123')`]), /duplicate key/);
|
||||
psql(["-c", `insert into railyard.watch_status (check_id, state, history) values ('${id}', 'up', '[{"at":"2026-09-29T12:00:00Z","ok":true,"ms":80}]')`]);
|
||||
assert.throws(() => psql(["-c", `update railyard.watch_status set state = 'red' where check_id = '${id}'`]), /check constraint/);
|
||||
const big = JSON.stringify(Array.from({ length: 91 }, () => ({ ok: true })));
|
||||
assert.throws(() => psql(["-c", `update railyard.watch_status set history = '${big}' where check_id = '${id}'`]), /check constraint/);
|
||||
psql(["-c", `delete from railyard.orgs where id = '${org}'`]);
|
||||
assert.equal(psql(["-c", "select count(*) from railyard.watch_status"]).trim(), "0");
|
||||
assert.equal(psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim(), "0");
|
||||
});
|
||||
|
||||
45
apps/console/test/watch-copy.test.ts
Normal file
45
apps/console/test/watch-copy.test.ts
Normal file
@ -0,0 +1,45 @@
|
||||
// The Watch screen, the public status page, the alert email and the watch
|
||||
// messages pass the vendored copy denylist, and name no host or engine.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { errors, formatFindings, lintUnits } from "../../../policy/copy-lint.mjs";
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const R = (p: string) => readFileSync(join(ROOT, p), "utf8");
|
||||
const strings = (src: string) =>
|
||||
[...src.replace(/^\s*\/\/.*$/gm, "").matchAll(/["`]([^"`\n]{12,})["`]|>([^<>{}\n]{12,})</g)]
|
||||
.map((m) => (m[1] ?? m[2]).trim())
|
||||
.filter((s) => !/^[\^[/.]|https?:|\$\{|^[a-z-]+:|^watch_|^railyard /.test(s));
|
||||
|
||||
// Watch copy is allowed only with RAILYARD_WATCH_LIVE on (denylist rule
|
||||
// railyard-slot-watch). Every file listed "live" is reachable only behind that
|
||||
// flag (the checks below prove each one tests it); the rest must pass with it off.
|
||||
const LIVE = { RAILYARD_WATCH_LIVE: "1" };
|
||||
for (const [file, surface, flags] of [
|
||||
["app/status/[app]/page.tsx", "marketing", LIVE],
|
||||
["app/(app)/watch/page.tsx", "app-ui", LIVE],
|
||||
["components/WatchPanel.tsx", "app-ui", LIVE],
|
||||
["lib/watch/service.ts", "outbound", LIVE],
|
||||
["lib/watch/http.ts", "api-public", {}],
|
||||
["components/Nav.tsx", "app-ui", {}],
|
||||
] as const) {
|
||||
test(`${file} passes the copy lint (${surface}${flags === LIVE ? ", Watch live" : ""})`, () => {
|
||||
const units = strings(R(file)).map((text) => ({ text, surface, where: file }));
|
||||
const found = errors(lintUnits(units, { flags }));
|
||||
assert.deepEqual(found, [], formatFindings(found));
|
||||
for (const u of units) assert.doesNotMatch(u.text, /gatus|ereboslab|box ?1|hetzner|contabo/i, `${file}: ${u.text}`);
|
||||
});
|
||||
}
|
||||
|
||||
test("every Watch surface linted as live checks the flag first", () => {
|
||||
assert.match(R("app/status/[app]/page.tsx"), /if \(!watch\.live/);
|
||||
assert.match(R("app/(app)/watch/page.tsx"), /if \(!watch\.live\)/);
|
||||
assert.match(R("app/(app)/layout.tsx"), /<Nav watch=\{deps\(\)\.cfg\.watchLive\}/);
|
||||
const svc = R("lib/watch/service.ts");
|
||||
for (const fn of ["createCheck", "agentChecks", "recordResults"]) {
|
||||
assert.match(svc, new RegExp(`function ${fn}[^]*?if \\(!deps\\.live\\)`), fn);
|
||||
}
|
||||
});
|
||||
@ -243,7 +243,8 @@
|
||||
"analytics",
|
||||
"deploy",
|
||||
"ai",
|
||||
"flags"
|
||||
"flags",
|
||||
"uptime"
|
||||
],
|
||||
"renews_at": "2026-10-29T12:00:00Z",
|
||||
"caps": {
|
||||
@ -265,7 +266,8 @@
|
||||
"ai",
|
||||
"analytics",
|
||||
"deploy",
|
||||
"flags"
|
||||
"flags",
|
||||
"uptime"
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -331,6 +333,27 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "uptime check for a project's address",
|
||||
"route": "uptime",
|
||||
"request": {
|
||||
"scribase_org_id": "org_fixture",
|
||||
"app": "shop",
|
||||
"url": "https://shop.example.com",
|
||||
"name": "Shop",
|
||||
"owner_email": "owner@example.com"
|
||||
},
|
||||
"status": 200,
|
||||
"response_keys": [
|
||||
"app",
|
||||
"checks",
|
||||
"created"
|
||||
],
|
||||
"response_match": {
|
||||
"app": "shop",
|
||||
"created": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "lapsed add-on",
|
||||
"route": "orgs",
|
||||
@ -424,6 +447,18 @@
|
||||
"response_keys": [
|
||||
"error"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "uptime after the add-on lapsed",
|
||||
"route": "uptime",
|
||||
"request": {
|
||||
"scribase_org_id": "org_fixture",
|
||||
"app": "shop"
|
||||
},
|
||||
"status": 402,
|
||||
"response_keys": [
|
||||
"error"
|
||||
]
|
||||
}
|
||||
],
|
||||
"unsigned": {
|
||||
@ -469,7 +504,7 @@
|
||||
"month_events",
|
||||
"visitors"
|
||||
],
|
||||
"id_format": "^msg_(orgs|claims|proof|deploys|sites|insights|ai|ai_usage|flags)_[0-9a-f]{24}$",
|
||||
"id_format": "^msg_(orgs|claims|proof|deploys|sites|insights|ai|ai_usage|flags|uptime)_[0-9a-f]{24}$",
|
||||
"wrong_route": {
|
||||
"status": 401,
|
||||
"response_keys": [
|
||||
@ -492,5 +527,16 @@
|
||||
"key",
|
||||
"updated_at",
|
||||
"value"
|
||||
],
|
||||
"uptime_check_keys": [
|
||||
"app",
|
||||
"first_result_at",
|
||||
"id",
|
||||
"last_checked_at",
|
||||
"name",
|
||||
"paused",
|
||||
"state",
|
||||
"status_url",
|
||||
"url"
|
||||
]
|
||||
}
|
||||
|
||||
@ -16,6 +16,8 @@ import { handleBridge } from "../../apps/console/app/api/v1/bridge/scribase/serv
|
||||
import { MemoryFlagsStore } from "../../apps/console/lib/flags/store.ts";
|
||||
import { TableFlagsBackend } from "../../apps/console/lib/flags/table-backend.ts";
|
||||
import type { FlagsDeps } from "../../apps/console/lib/flags/service.ts";
|
||||
import { MemoryWatchStore } from "../../apps/console/lib/watch/store.ts";
|
||||
import type { WatchDeps } from "../../apps/console/lib/watch/service.ts";
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const contract = JSON.parse(readFileSync(join(HERE, "fixtures/scribase-bridge/contract.json"), "utf8"));
|
||||
@ -38,20 +40,25 @@ function flagsDeps(): FlagsDeps {
|
||||
return { store, backend, backends: { table: backend } };
|
||||
}
|
||||
|
||||
async function send(repo: MemoryRepo, route: string, payload: unknown, id: string, secret = SECRET, flags: FlagsDeps = flagsDeps()) {
|
||||
function watchDeps(repo: MemoryRepo): WatchDeps {
|
||||
return { store: new MemoryWatchStore(), repo, mailer: { send: async () => true }, consoleUrl: "https://railyard.example", agentToken: null, live: true };
|
||||
}
|
||||
|
||||
async function send(repo: MemoryRepo, route: string, payload: unknown, id: string, secret = SECRET, flags: FlagsDeps = flagsDeps(), watch: WatchDeps = watchDeps(repo)) {
|
||||
const body = JSON.stringify(payload);
|
||||
const ts = String(Math.floor(NOW.getTime() / 1000));
|
||||
return handleBridge({ repo, secret: SECRET, consoleUrl: "https://railyard.example", now: () => NOW, flags }, route as never, { id, timestamp: ts, signature: await sign(secret, id, ts, body) }, body);
|
||||
return handleBridge({ repo, secret: SECRET, consoleUrl: "https://railyard.example", now: () => NOW, flags, watch }, route as never, { id, timestamp: ts, signature: await sign(secret, id, ts, body) }, body);
|
||||
}
|
||||
|
||||
test("every contract case answers with its status and keys, in order", async () => {
|
||||
const repo = new MemoryRepo(() => NOW);
|
||||
const flags = flagsDeps();
|
||||
const watch = watchDeps(repo);
|
||||
let i = 0;
|
||||
for (const c of contract.cases) {
|
||||
const id = rid(c.route, ++i);
|
||||
assert.match(id, new RegExp(contract.id_format));
|
||||
const r = await send(repo, c.route, c.request, id, SECRET, flags);
|
||||
const r = await send(repo, c.route, c.request, id, SECRET, flags, watch);
|
||||
assert.equal(r.status, c.status, c.name);
|
||||
assert.deepEqual(Object.keys(r.body).sort(), c.response_keys, c.name);
|
||||
if (c.response_match) assert.ok(matches(r.body, c.response_match), `${c.name}: ${JSON.stringify(r.body)}`);
|
||||
@ -66,6 +73,9 @@ test("every contract case answers with its status and keys, in order", async ()
|
||||
if (c.flags_match) assert.ok(matches(items.map((f) => ({ key: f.key, enabled: f.enabled, value: f.value })), c.flags_match), c.name);
|
||||
assert.match(r.body.client_key as string, /^ry_flags_/);
|
||||
}
|
||||
if (c.route === "uptime" && r.status === 200) {
|
||||
for (const k of r.body.checks as Record<string, unknown>[]) assert.deepEqual(Object.keys(k).sort(), contract.uptime_check_keys, c.name);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user