import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { createHash } from "node:crypto"; import { test } from "node:test"; import { Miniflare } from "miniflare"; import { publish, markUnavailable } from "../src/publication.js"; const today = "2026-11-15"; const yesterday = "2026-11-14"; async function setup(t) { const mf = new Miniflare({ modules: true, script: 'export default {fetch(){return new Response("ok")}}', compatibilityDate: "2026-07-13", d1Databases: ["DB"], }); t.after(() => mf.dispose()); const DB = await mf.getD1Database("DB"); const schema = await readFile( new URL("../migrations/0001_digest.sql", import.meta.url), "utf8", ); for (const sql of schema .split(";") .map((s) => s.trim()) .filter(Boolean)) await DB.prepare(sql).run(); const objects = new Map(); const missingManifest = { remaining: 0 }; t.mock.method(globalThis, "fetch", async (input, init) => { const req = new Request(input, init); const key = new URL(req.url).pathname.split("/").slice(2).join("/"); const item = objects.get(key); if (req.method === "GET") return item ? new Response(item.body, { headers: { ETag: item.etag } }) : new Response("", { status: 404 }); assert.equal(req.method, "PUT"); if (key === "manifest.json" && missingManifest.remaining > 0) { missingManifest.remaining--; return new Response("TestInterruption", { status: 403, }); } const noMatch = req.headers.get("if-none-match"), match = req.headers.get("if-match"); const body = await req.text(); // Compare immediately before the write, as an object store would. const current = objects.get(key); if ((noMatch === "*" && current) || (match && current?.etag !== match)) return new Response("", { status: 412 }); const etag = '"' + createHash("md5").update(body).digest("hex") + '"'; objects.set(key, { body, etag }); return new Response("", { headers: { ETag: etag } }); }); const env = { DB, S3_BUCKET: "digest-test", S3_ACCESS_KEY_ID: "fake-access-key", S3_SECRET_ACCESS_KEY: "fake-secret", }; async function prepare(date) { const content = { date, publishedAt: null, sections: [ { id: "ai", status: "ok", stories: [ { id: "a", title: "Проверочная запись", url: "https://example.org/release", }, ], }, ], }; const checkpoints = { test: date + "T03:20:00.000Z" }; await DB.prepare( "INSERT INTO editions(issue_date,content,checkpoints,state) VALUES (?,?,?,'ready')", ) .bind(date, JSON.stringify(content), JSON.stringify(checkpoints)) .run(); } const value = (key) => JSON.parse(objects.get(key).body); return { env, prepare, objects, value, missingManifest }; } test("parallel and repeated publication produce one edition, one story, and the original timestamp", async (t) => { const { env, prepare, value, objects } = await setup(t); await prepare(today); await Promise.all([publish(env, today), publish(env, today)]); const chosen = value("editions/" + today + ".json").publishedAt; assert.ok(Date.parse(chosen)); assert.equal((await publish(env, today)).outcome, "already-published"); assert.deepEqual(value("manifest.json").dates, [today]); assert.equal(value("editions/" + today + ".json").publishedAt, chosen); assert.equal( [...objects.keys()].filter((k) => k.startsWith("editions/")).length, 1, ); assert.equal( (await env.DB.prepare("SELECT COUNT(*) n FROM stories").first()).n, 1, ); assert.equal( (await env.DB.prepare("SELECT published_at FROM editions").first()) .published_at, chosen, ); }); test("interruption after uploading an issue retains yesterday and recovers the exact same issue", async (t) => { const { env, prepare, value, missingManifest } = await setup(t); await prepare(yesterday); await publish(env, yesterday); await prepare(today); missingManifest.remaining = 1; await assert.rejects(publish(env, today), /403|TestInterruption/); assert.equal(value("manifest.json").latest, yesterday); const staged = value("editions/" + today + ".json"); assert.equal( (await env.DB.prepare("SELECT success_at FROM sources").first()).success_at, yesterday + "T03:20:00.000Z", ); await publish(env, today); assert.deepEqual(staged, value("editions/" + today + ".json")); assert.equal(value("manifest.json").latest, today); assert.equal( (await env.DB.prepare("SELECT success_at FROM sources").first()).success_at, today + "T03:20:00.000Z", ); }); test("a missing issue retains the previous date and warning until publication recovers", async (t) => { const { env, prepare, value } = await setup(t); await prepare(yesterday); await publish(env, yesterday); assert.equal((await publish(env, today)).outcome, "retry"); await markUnavailable(env, today); assert.equal(value("manifest.json").latest, yesterday); assert.equal(value("manifest.json").warningDate, today); assert.deepEqual(value("manifest.json").dates, [yesterday]); await prepare(today); await publish(env, today); assert.equal(value("manifest.json").warning, undefined); assert.deepEqual(value("manifest.json").dates, [today, yesterday]); });