commit 9a947558e14bcb5f54d949445fad6aaccfb6aebc
parent 7a520a7e2c872b5e00471940e5a207b607ca879b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 10:58:31 -0400
pacing guard: unit tests for the queue gap, the fresh-jar rule, X as a service and its no-request Recheck
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 238 insertions(+), 0 deletions(-)
diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts
@@ -124,3 +124,40 @@ test("Recheck (archive.today): the request that met the check, again; a check st
await rm(paths.transcriptsDir, { recursive: true, force: true });
}
});
+
+test("Recheck (X): no request to X — stale until the login is renewed after the alert, then clean", async () => {
+ const paths = await tmpPaths();
+ try {
+ const { noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", url: "https://x.com/a", channel: "a" });
+ const raisedAt = (await readServiceCookieState(paths)).services.x?.raisedAt;
+ assert.ok(raisedAt, "one challenge raises the X alert");
+ const asked: string[] = [];
+ let login = { source: "profile" as const, renewedAt: new Date(Date.parse(raisedAt!) - 60_000).toISOString(), loggedIn: true };
+ const deps = {
+ runYtdlp: async () => {
+ asked.push("yt-dlp");
+ return { exitCode: 0, stderrTail: "", archiveLine: null };
+ },
+ loadForumPage: async () => {
+ asked.push("page");
+ return { html: "" };
+ },
+ xLogin: async () => login,
+ };
+ const stale = await recheckServiceCookies({ paths, service: "x", deps });
+ assert.equal(stale.result, "stale");
+ assert.match(stale.message, /Refresh cookies/);
+ assert.match(stale.message, /Recheck sends X no request/);
+ assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.x), true);
+
+ login = { source: "profile", renewedAt: new Date(Date.parse(raisedAt!) + 60_000).toISOString(), loggedIn: true };
+ const clean = await recheckServiceCookies({ paths, service: "x", deps });
+ assert.equal(clean.result, "clean");
+ const after = (await readServiceCookieState(paths)).services.x;
+ assert.equal(after?.clearedBy, "recheck");
+ assert.deepEqual(asked, [], "Recheck asked nothing of anyone");
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/jobs/networkGuard.test.ts b/common/jobs/networkGuard.test.ts
@@ -0,0 +1,63 @@
+// The network guard's pure rules (plans/pacing-guard.md); the job funnel
+// end to end is pacingGuard.test.ts.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/networkGuard.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { ageText, emptyQueueRefusal, xJarVerdict } from "./networkGuard";
+
+const NOW = Date.parse("2026-10-23T03:00:00Z");
+const at = (msAgo: number) => new Date(NOW - msAgo).toISOString();
+
+test("the empty queue is refused for a network kind only", () => {
+ assert.match(emptyQueueRefusal("fetch-posts", "") ?? "", /^Fetch posts sends requests to a platform/);
+ assert.match(emptyQueueRefusal("sync", "") ?? "", /never runs unqueued/);
+ assert.equal(emptyQueueRefusal("fetch-posts", "platform:twitter"), null);
+ assert.equal(emptyQueueRefusal("evict-clips", ""), null);
+ assert.equal(emptyQueueRefusal("auto-download", ""), null);
+});
+
+test("the fresh-jar rule (profile source)", () => {
+ const v = (ageMs: number, authed = true, max = 60) =>
+ xJarVerdict({
+ source: "profile",
+ status: { hasCookies: true, cookiesUpdatedAt: at(ageMs), looksAuthenticated: authed },
+ maxAgeMinutes: max,
+ now: NOW,
+ });
+ assert.deepEqual(v(59 * 60_000), { ok: true });
+ assert.deepEqual(v(16 * 24 * 3600_000), {
+ ok: false,
+ message:
+ "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.",
+ });
+ assert.match((v(61 * 60_000) as { message: string }).message, /61 min ago/);
+ assert.match((v(60_000, false) as { message: string }).message, /holds no login/);
+ // 0 turns the rule off.
+ assert.deepEqual(v(16 * 24 * 3600_000, true, 0), { ok: true });
+ const none = xJarVerdict({
+ source: "profile",
+ status: { hasCookies: false, looksAuthenticated: false },
+ maxAgeMinutes: 60,
+ now: NOW,
+ });
+ assert.match((none as { message: string }).message, /No X cookie jar/);
+});
+
+test("the browser source cannot be checked: proceed, and say so", () => {
+ const v = xJarVerdict({
+ source: "browser",
+ status: { hasCookies: false, looksAuthenticated: false },
+ maxAgeMinutes: 60,
+ now: NOW,
+ });
+ assert.equal(v.ok, true);
+ assert.match((v as { note?: string }).note ?? "", /cannot be read here/);
+});
+
+test("ageText", () => {
+ assert.equal(ageText(45 * 60_000), "45 min");
+ assert.equal(ageText(3 * 3600_000), "3 h");
+ assert.equal(ageText(16 * 24 * 3600_000), "16 days");
+});
diff --git a/common/jobs/queueGap.test.ts b/common/jobs/queueGap.test.ts
@@ -0,0 +1,122 @@
+// The gap between two jobs on one platform queue (plans/pacing-guard.md).
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/queueGap.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ clearQueueGaps,
+ gapReason,
+ lastQueueEnd,
+ noteQueueJobEnd,
+ queueGapFor,
+ queueGapLine,
+ queueGapPlatform,
+ queueGapWait,
+ waitForQueueGap,
+ waitText,
+} from "./queueGap";
+import { jobGapSecondsFor, sanitizePacing } from "../lib/settingsSchema";
+
+async function jobsDir() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "queue-gap-"));
+ return { jobsDir: path.join(root, ".jobs") };
+}
+
+test("only platform: queues have a gap", () => {
+ assert.equal(queueGapPlatform("platform:twitter"), "twitter");
+ assert.equal(queueGapPlatform("platform:megaphone.fm"), "megaphone.fm");
+ assert.equal(queueGapPlatform("clips:youtube"), null);
+ assert.equal(queueGapPlatform("transcription"), null);
+ assert.equal(queueGapPlatform(""), null);
+});
+
+test("the gap: the operator's per platform, else the built-in per platform, else default", () => {
+ delete process.env.E2E_JOB_GAP_SECONDS;
+ assert.deepEqual(jobGapSecondsFor(undefined, "twitter"), { seconds: 300, key: "twitter" });
+ assert.deepEqual(jobGapSecondsFor(undefined, "xenforo"), { seconds: 60, key: "xenforo" });
+ assert.deepEqual(jobGapSecondsFor(undefined, "bluesky"), { seconds: 60, key: "bluesky" });
+ assert.deepEqual(jobGapSecondsFor(undefined, "youtube"), { seconds: 20, key: "default" });
+ const pacing = sanitizePacing({ jobGapSeconds: { twitter: 600, default: 45, "Bad Key": 3, youtube: -1 } });
+ assert.deepEqual(pacing.jobGapSeconds, { twitter: 600, default: 45 });
+ assert.deepEqual(jobGapSecondsFor(pacing, "twitter"), { seconds: 600, key: "twitter" });
+ // A platform with a built-in keeps it over the operator's default.
+ assert.deepEqual(jobGapSecondsFor(pacing, "xenforo"), { seconds: 60, key: "xenforo" });
+ assert.deepEqual(jobGapSecondsFor(pacing, "megaphone.fm"), { seconds: 45, key: "default" });
+ assert.deepEqual(sanitizePacing({ jobGapSeconds: { twitter: 10 ** 9 } }).jobGapSeconds, { twitter: 86400 });
+});
+
+test("E2E_JOB_GAP_SECONDS replaces the built-ins only; a set value still applies", () => {
+ process.env.E2E_JOB_GAP_SECONDS = "0";
+ try {
+ assert.equal(queueGapFor(undefined, "twitter").seconds, 0);
+ assert.equal(queueGapFor({ jobGapSeconds: { twitter: 3 } }, "twitter").seconds, 3);
+ } finally {
+ delete process.env.E2E_JOB_GAP_SECONDS;
+ }
+});
+
+test("the sentence", () => {
+ assert.equal(
+ gapReason("twitter", { seconds: 300, key: "twitter" }),
+ "X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)",
+ );
+ assert.equal(waitText(252_000), "4m12s");
+ assert.equal(waitText(45_000), "45s");
+ assert.equal(
+ queueGapLine({ until: 0, remainingMs: 252_000, reason: "X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)" }),
+ "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)",
+ );
+});
+
+test("no end yet: no wait; an end: wait out the rest; the end is persisted and read back after a restart", async () => {
+ delete process.env.E2E_JOB_GAP_SECONDS;
+ const paths = await jobsDir();
+ const q = "platform:twitter";
+ assert.equal(await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_000_000 }), null);
+ await noteQueueJobEnd(paths, q, 1_000_000);
+ const w = await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_048_000 });
+ assert.equal(w?.remainingMs, 252_000);
+ assert.equal(await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_300_000 }), null);
+ const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8"));
+ assert.equal(file.ends[q], 1_000_000);
+ clearQueueGaps(); // the restart
+ assert.equal(await lastQueueEnd(paths, q), 1_000_000);
+ // Not a platform queue: nothing noted.
+ await noteQueueJobEnd(paths, "transcription", 5);
+ assert.equal(await lastQueueEnd(paths, "transcription"), undefined);
+});
+
+test("waitForQueueGap waits, logs once per wait, tells the row, clears it", async () => {
+ const paths = await jobsDir();
+ const q = "platform:xenforo";
+ let now = 10_000_000;
+ await noteQueueJobEnd(paths, q, now);
+ now += 15_000;
+ const lines: string[] = [];
+ const seen: (string | null)[] = [];
+ const waited = await waitForQueueGap({
+ paths,
+ queueKey: q,
+ pacing: () => undefined,
+ onLog: (l) => lines.push(l),
+ onWait: (w) => seen.push(w ? w.reason : null),
+ clock: { now: () => now, sleep: async (ms) => void (now += ms) },
+ });
+ assert.equal(waited, 45_000);
+ assert.deepEqual(lines, ["waiting 45s: Forum jobs are spaced 1 min apart (pacing.jobGapSeconds.xenforo)"]);
+ assert.deepEqual(seen, ["Forum jobs are spaced 1 min apart (pacing.jobGapSeconds.xenforo)", null]);
+});
+
+test("waitForQueueGap rejects on abort", async () => {
+ const paths = await jobsDir();
+ const q = "platform:twitter";
+ await noteQueueJobEnd(paths, q, Date.now());
+ const ac = new AbortController();
+ const p = waitForQueueGap({ paths, queueKey: q, pacing: () => undefined, signal: ac.signal });
+ setTimeout(() => ac.abort(), 10);
+ await assert.rejects(p, { name: "AbortError" });
+});
diff --git a/common/lib/serviceCookies.test.ts b/common/lib/serviceCookies.test.ts
@@ -248,3 +248,19 @@ test("the view: a stale banner with its fix; OK again offers the stopped jobs, b
const after = buildServiceCookieAlerts(state, { now: T0 + 180_000 + OK_AGAIN_SHOW_MS + 1, statusOf: (id) => statuses[id] });
assert.equal(after.alerts.some((a) => a.service === "rumble"), false);
});
+
+// plans/pacing-guard.md: X is a service, its family "x", Recheck always offered.
+test("X is a cookie-alert service: key, label, family, fix; one challenge raises it", async () => {
+ const sc = await import("./serviceCookies");
+ assert.equal(sc.isServiceKey("x"), true);
+ assert.equal(sc.serviceLabel("x"), "X");
+ assert.equal(sc.serviceFamily("x"), "x");
+ assert.match(sc.serviceFixText("x"), /Refresh cookies/);
+ const state = sc.emptyServiceCookieState();
+ const r = sc.applyServiceCookieSignal(state, { service: "x", kind: "challenge", line: "[twitter][warning] Cloudflare challenge" }, {}, Date.parse("2026-10-23T03:00:00Z"));
+ assert.equal(r.raisedNow, true);
+ const view = sc.buildServiceCookieAlerts(state, { now: Date.parse("2026-10-23T03:01:00Z") });
+ assert.equal(view.alerts[0]?.service, "x");
+ assert.equal(view.alerts[0]?.canRecheck, true);
+ assert.match(view.alerts[0]?.headline ?? "", /^X needs fresh cookies: /);
+});