Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c84d2de1b | ||
|
|
664f55ee83 | ||
|
|
f5af0f6239 | ||
|
|
baa22f7ea0 | ||
|
|
6cd8ba0b95 | ||
|
|
941688d2c9 | ||
|
|
e780b575fb | ||
|
|
243cabb221 | ||
|
|
dc181533ab | ||
|
|
3c3a6c084f | ||
|
|
aebf27f155 | ||
|
|
85e2f41113 | ||
|
|
4092e194a9 |
No files matched your search
@@ -125,6 +125,24 @@ describe("rematch stops and downgrades a P1001 unreachable database (BIT-32462)"
|
||||
expect(log.calls.some((c) => c.level === "warn" && /gallery not checked/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("logs at info and stops the batch when Postgres is at max_connections (P2037, BIT-33550)", async () => {
|
||||
const log = makeLog();
|
||||
const calls: string[] = [];
|
||||
const db = makeDb(async () => {
|
||||
calls.push("findUnique");
|
||||
throw Object.assign(
|
||||
new Error("Invalid `prisma.sportsFixture.findMany()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"),
|
||||
{ code: "P2037" },
|
||||
);
|
||||
});
|
||||
const service = new ArchiveService({ db, log } as never);
|
||||
const moved = await (service as unknown as { rematch: (sourceId: string) => Promise<number> }).rematch("src-1");
|
||||
expect(calls).toEqual(["findUnique"]);
|
||||
expect(moved).toBe(0);
|
||||
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn" && /gallery not checked/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("still warns on a real per-folder error", async () => {
|
||||
const log = makeLog();
|
||||
const db = makeDb(async () => {
|
||||
@@ -205,6 +223,33 @@ describe("takeOffFutureGames stops and downgrades an unreachable database (BIT-3
|
||||
expect(log.calls.some((c) => c.level === "info" && /connection terminated/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn" && /not moved/.test(c.msg))).toBe(false);
|
||||
});
|
||||
it("logs at info and stops the batch when Postgres is at max_connections (P2037, BIT-33550)", async () => {
|
||||
const log = makeLog();
|
||||
const calls: string[] = [];
|
||||
const db = {
|
||||
cloudFolder: {
|
||||
findMany: async () => [
|
||||
{ id: "f-1", path: "/Future Game", eventId: "evt-1", matchedBy: "NAME", fixtureRejected: false, source: { id: "src-1" } },
|
||||
{ id: "f-2", path: "/Future Game 2", eventId: "evt-2", matchedBy: "NAME", fixtureRejected: false, source: { id: "src-1" } },
|
||||
],
|
||||
},
|
||||
event: {
|
||||
findUnique: async () => {
|
||||
calls.push("findUnique");
|
||||
throw Object.assign(
|
||||
new Error("Invalid `prisma.sportsFixture.findMany()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"),
|
||||
{ code: "P2037" },
|
||||
);
|
||||
},
|
||||
},
|
||||
};
|
||||
const service = new ArchiveService({ db, log } as never);
|
||||
const moved = await (service as unknown as { takeOffFutureGames: () => Promise<number> }).takeOffFutureGames();
|
||||
expect(calls).toEqual(["findUnique"]);
|
||||
expect(moved).toBe(0);
|
||||
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn" && /not moved/.test(c.msg))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("walk recovers from a P2002 race on cloudFile.create (BIT-33532)", () => {
|
||||
@@ -300,3 +345,56 @@ describe("walk recovers from a P2002 race on cloudFile.create (BIT-33532)", () =
|
||||
).rejects.toThrow("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rebuildDirectory skips when another worker holds the advisory lock (BIT-33539)", () => {
|
||||
const makeDb = (lockOk: boolean) => {
|
||||
const calls: string[] = [];
|
||||
const archiveTeamSide = {
|
||||
deleteMany: async () => { calls.push("deleteMany"); return { count: 0 }; },
|
||||
createMany: async () => { calls.push("createMany"); return { count: 1 }; },
|
||||
};
|
||||
const cloudSource = {
|
||||
findUnique: async () => ({ id: "src-1", look: "club", baseUrl: "https://cloud.example" }),
|
||||
updateMany: async () => { calls.push("updateMany"); return { count: 1 }; },
|
||||
};
|
||||
const tx = {
|
||||
$queryRaw: async () => [{ ok: lockOk }],
|
||||
archiveTeamSide,
|
||||
cloudSource: { updateMany: cloudSource.updateMany },
|
||||
};
|
||||
return {
|
||||
calls,
|
||||
db: {
|
||||
cloudSource,
|
||||
sportsTeam: { findMany: async () => [] },
|
||||
archiveClubAlias: { findMany: async () => [] },
|
||||
cloudFolder: {
|
||||
findMany: async () => [
|
||||
{ event: { id: "evt-1", home: "SLB", away: "SCP" } },
|
||||
],
|
||||
},
|
||||
$transaction: async (cb: (tx: typeof tx) => Promise<void>) => cb(tx),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("writes rows when the lock is acquired", async () => {
|
||||
const { calls, db } = makeDb(true);
|
||||
const service = new ArchiveService({ db, log: { info() {}, debug() {}, error() {}, warn() {} } } as never);
|
||||
const sides = await (service as unknown as { rebuildDirectory: (sourceId: string) => Promise<number> }).rebuildDirectory("src-1");
|
||||
expect(sides).toBeGreaterThan(0);
|
||||
expect(calls).toContain("deleteMany");
|
||||
expect(calls).toContain("createMany");
|
||||
expect(calls).toContain("updateMany");
|
||||
});
|
||||
|
||||
it("skips deleteMany and createMany when the lock is held by another worker", async () => {
|
||||
const { calls, db } = makeDb(false);
|
||||
const service = new ArchiveService({ db, log: { info() {}, debug() {}, error() {}, warn() {} } } as never);
|
||||
const sides = await (service as unknown as { rebuildDirectory: (sourceId: string) => Promise<number> }).rebuildDirectory("src-1");
|
||||
expect(sides).toBe(0);
|
||||
expect(calls).not.toContain("deleteMany");
|
||||
expect(calls).not.toContain("createMany");
|
||||
expect(calls).not.toContain("updateMany");
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import type { CloudFolder, CloudSource } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger, IngestService } from "../ingest/service.js";
|
||||
import { ingestWindow } from "../library/events.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { isPostgresAdminShutdown, isPrismaServerUnreachable } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPrismaServerUnreachable, isPrismaTooManyConnections } from "../lib/pg.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
|
||||
import {
|
||||
@@ -658,6 +658,13 @@ export class ArchiveService {
|
||||
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: future-game check stopped, database connection terminated");
|
||||
break;
|
||||
}
|
||||
// The Postgres server is at max_connections and only SUPERUSER slots remain (P2037): every remaining folder
|
||||
// would fail the same way, so stop the batch and let the next verifyAll retry once a slot frees — a warn per
|
||||
// folder pages the error loop for a transient blip (BIT-33550).
|
||||
if (isPrismaTooManyConnections(err)) {
|
||||
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: future-game check stopped, too many database connections");
|
||||
break;
|
||||
}
|
||||
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery on a game still to come not moved");
|
||||
}
|
||||
}
|
||||
@@ -716,6 +723,13 @@ export class ArchiveService {
|
||||
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: gallery check stopped, database connection terminated");
|
||||
break;
|
||||
}
|
||||
// The Postgres server is at max_connections and only SUPERUSER slots remain (P2037): every remaining folder
|
||||
// would fail the same way, so stop this source's batch and let the next verifyAll retry once a slot frees —
|
||||
// logging a warn per folder pages the error loop for a transient blip (BIT-33550).
|
||||
if (isPrismaTooManyConnections(err)) {
|
||||
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: gallery check stopped, too many database connections");
|
||||
break;
|
||||
}
|
||||
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery not checked");
|
||||
report?.errors.push({ path: folder.path, error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
@@ -1451,7 +1465,11 @@ export class ArchiveService {
|
||||
const games = new Map<string, { id: string; home: string; away: string }>();
|
||||
for (const folder of folders) if (folder.event) games.set(folder.event.id, folder.event);
|
||||
const rows = teamSideRows(games.values(), teamMatcher(teams), new Map(aliases.map((alias) => [alias.aliasKey, alias.name])));
|
||||
let stored = rows.length;
|
||||
await db.$transaction(async (tx) => {
|
||||
// Two workers can pick the same due source (BIT-33539): the second skips instead of colliding on the PK.
|
||||
const [locked] = await tx.$queryRaw<{ ok: boolean }[]>`SELECT pg_try_advisory_xact_lock(hashtext(${sourceId})::bigint) AS ok`;
|
||||
if (!locked?.ok) { stored = 0; return; }
|
||||
await tx.archiveTeamSide.deleteMany({ where: { sourceId } });
|
||||
const chunk = 2000;
|
||||
for (let i = 0; i < rows.length; i += chunk) {
|
||||
@@ -1464,7 +1482,7 @@ export class ArchiveService {
|
||||
data: { directoryBuiltAt: new Date(), directoryDirtyAt: null },
|
||||
});
|
||||
}, { timeout: 60_000, maxWait: 60_000 });
|
||||
return rows.length;
|
||||
return stored;
|
||||
}
|
||||
|
||||
/** One archive whose teams were never stored, or have changed. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RenderWorker, type DevelopService } from "./service.js";
|
||||
import { isPostgresAdminShutdown } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPrismaTooManyConnections } from "../lib/pg.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
|
||||
describe("isPostgresAdminShutdown", () => {
|
||||
@@ -18,6 +18,25 @@ describe("isPostgresAdminShutdown", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrismaTooManyConnections", () => {
|
||||
it("matches the P2010 raw-query variant wrapping SQLSTATE 53300 (BIT-33549)", () => {
|
||||
const err = new Error(
|
||||
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `53300`. Message: `sorry, too many clients already`",
|
||||
);
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches the P2037 variant", () => {
|
||||
const err = new Error("Too many database connections opened: sorry, too many clients already");
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match an unrelated query error", () => {
|
||||
expect(isPrismaTooManyConnections(new Error("relation \"photos\" does not exist"))).toBe(false);
|
||||
expect(isPrismaTooManyConnections(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RenderWorker poll error handling", () => {
|
||||
type Level = "info" | "warn";
|
||||
const makeLog = (): IngestLogger & { calls: { level: Level; msg: string }[] } => {
|
||||
@@ -51,6 +70,23 @@ describe("RenderWorker poll error handling", () => {
|
||||
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("logs a 53300 pool-exhaustion error at info, not warn (BIT-33549)", async () => {
|
||||
const log = makeLog();
|
||||
const worker = new RenderWorker(
|
||||
makeService(
|
||||
new Error(
|
||||
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `53300`. Message: `sorry, too many clients already`",
|
||||
),
|
||||
) as DevelopService,
|
||||
{ concurrency: 1, intervalMs: 60_000, log },
|
||||
);
|
||||
worker.start();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
await worker.stop();
|
||||
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("still warns on a real poll failure", async () => {
|
||||
const log = makeLog();
|
||||
const worker = new RenderWorker(makeService(new Error("relation photos does not exist")) as DevelopService, {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Db } from "../db.js";
|
||||
import { Prisma, type PhotoEdit } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { isPostgresAdminShutdown } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPrismaTooManyConnections } from "../lib/pg.js";
|
||||
import { photoUrls } from "../library/serialize.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
|
||||
@@ -223,6 +223,9 @@ export class RenderWorker {
|
||||
// A DB restart or `pg_terminate_backend` (57P01) takes the pooled client mid-`$queryRaw`; the next tick
|
||||
// re-claims a fresh one, so log at info and let the loop continue instead of paging the error loop (BIT-32449).
|
||||
if (isPostgresAdminShutdown(err)) this.opts.log.info({ err: (err as Error).message }, "develop: poll skipped, db connection was reset");
|
||||
// Pool exhaustion (P2037 or P2010 wrapping SQLSTATE 53300 "too many clients already"): every remaining
|
||||
// query would fail the same way, so skip this tick and let the next one retry once a slot frees (BIT-33549).
|
||||
else if (isPrismaTooManyConnections(err)) this.opts.log.info({ err: (err as Error).message }, "develop: poll skipped, too many database connections");
|
||||
else this.opts.log.warn({ err }, "develop: poll failed");
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "./pg.js";
|
||||
import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "./pg.js";
|
||||
|
||||
class PrismaLike extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
@@ -90,6 +90,31 @@ describe("isPrismaServerUnreachable", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrismaTooManyConnections", () => {
|
||||
it("matches a PrismaClientKnownRequestError with code P2037 (BIT-33558)", () => {
|
||||
const err = new PrismaLike(
|
||||
"P2037",
|
||||
"Invalid `prisma.deliveryTarget.findMany()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute",
|
||||
);
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches the 'remaining connection slots are reserved' message without the code", () => {
|
||||
expect(isPrismaTooManyConnections(new Error("Too many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"))).toBe(true);
|
||||
});
|
||||
|
||||
it("matches a P2010 raw-query failure wrapping SQLSTATE 53300 (BIT-33549)", () => {
|
||||
const err = new PrismaLike("P2010", "Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `53300`. Message: `sorry, too many clients already`");
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match an unrelated query error", () => {
|
||||
expect(isPrismaTooManyConnections(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false);
|
||||
expect(isPrismaTooManyConnections(null)).toBe(false);
|
||||
expect(isPrismaTooManyConnections("string")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrismaTransactionTimeout", () => {
|
||||
it("matches a PrismaClientKnownRequestError with code P2028 (BIT-32083)", () => {
|
||||
const err = new PrismaLike(
|
||||
|
||||
@@ -42,14 +42,16 @@ export function isPrismaServerUnreachable(err: unknown): boolean {
|
||||
/**
|
||||
* The Postgres server has no free connection slots for non-superuser roles — every slot is in use and the
|
||||
* remaining ones are reserved for SUPERUSER. Prisma surfaces this as `PrismaClientKnownRequestError` with
|
||||
* code `P2037` and message "Too many database connections opened: …". This is pool exhaustion under concurrent
|
||||
* worker load; the next scheduled tick reclaims a freed slot, so it is transient and must not page the error
|
||||
* loop — the caller should stop the current batch and let the next run retry (BIT-33538).
|
||||
* code `P2037` and message "Too many database connections opened: …", or as `P2010` wrapping the raw
|
||||
* SQLSTATE `53300` ("sorry, too many clients already") when a `$queryRaw` hits the limit. This is pool
|
||||
* exhaustion under concurrent worker load; the next scheduled tick reclaims a freed slot, so it is
|
||||
* transient and must not page the error loop — the caller should stop the current batch and let the next
|
||||
* run retry (BIT-33538, BIT-33549 for the P2010/53300 raw-query variant).
|
||||
*/
|
||||
export function isPrismaTooManyConnections(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
const code = (err as { code?: unknown }).code;
|
||||
return code === "P2037" || /Too many database connections opened/i.test(err.message);
|
||||
return code === "P2037" || /Too many database connections opened|sorry, too many clients already|\b53300\b/i.test(err.message);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+10
-2
@@ -17,6 +17,7 @@ import { DevelopService, RenderWorker } from "./develop/service.js";
|
||||
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
|
||||
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
||||
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
|
||||
import { isPrismaTooManyConnections } from "./lib/pg.js";
|
||||
import { jogaClientFromConfig } from "./sports/joga.js";
|
||||
import { SportsService, SportsWorker } from "./sports/service.js";
|
||||
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
|
||||
@@ -176,8 +177,15 @@ const sports = config.SPORTS_SYNC === "on"
|
||||
})
|
||||
: undefined;
|
||||
|
||||
ensureCloudM19Target(db).catch((err) => log.warn({ err }, "delivery: Cloud M19 profile not created"));
|
||||
ensureCloudW17Target(db).catch((err) => log.warn({ err }, "delivery: Cloud W17 profile not created"));
|
||||
// Pool exhaustion (P2037) during a deploy overlap is transient: the next worker restart retries these
|
||||
// one-shot targets. Log at info so the reporter hook (warn+) does not page the error loop (BIT-33558).
|
||||
const ensureCloudTarget = (fn: Promise<number>, name: string) =>
|
||||
fn.catch((err) => {
|
||||
if (isPrismaTooManyConnections(err)) log.info({ err: (err as Error).message }, `delivery: ${name} profile not created, too many database connections`);
|
||||
else log.warn({ err }, `delivery: ${name} profile not created`);
|
||||
});
|
||||
ensureCloudTarget(ensureCloudM19Target(db), "Cloud M19");
|
||||
ensureCloudTarget(ensureCloudW17Target(db), "Cloud W17");
|
||||
scanner.start();
|
||||
if (secrets) archive.start();
|
||||
autopilot.start();
|
||||
|
||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const info = await load(id);
|
||||
return { title: `Cara · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Cara · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function FacePage({ params }: Params) {
|
||||
|
||||
@@ -5,6 +5,13 @@ import { load } from "./load";
|
||||
/** The archive shell: the page the URL asked for, in its owner's template (`data-look`, archive.css). */
|
||||
export async function ArchiveFrame({ id, start }: { id: string; start?: View }) {
|
||||
const info = await load(id);
|
||||
if (!info) {
|
||||
return (
|
||||
<main className="wrap empty">
|
||||
<p>Temporariamente indisponível. Tenta novamente dentro de uns minutos.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
// On the archive's own address (the middleware rewrote `/g/…` to here) its links stay at the root.
|
||||
const atRoot = (await headers()).get("x-arquivo-root") === "1";
|
||||
return <ArchiveView info={{ ...info, base: atRoot ? "" : `/arquivo/${info.id}` }} start={start} />;
|
||||
|
||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const info = await load(id);
|
||||
return { title: `Galeria · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Galeria · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function GalleryPage({ params }: Params) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it, vi, afterEach } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
notFound: () => {
|
||||
const err = new Error("notFound");
|
||||
err.name = "NotFound";
|
||||
throw err;
|
||||
},
|
||||
}));
|
||||
|
||||
const { load } = await import("./load");
|
||||
|
||||
const archiveBody = {
|
||||
id: "d26ceb8e-c146-4f68-abaf-c79ce3981b2d",
|
||||
name: "Test Archive",
|
||||
cloud: "cloud1",
|
||||
organization: "org1",
|
||||
};
|
||||
|
||||
function mockFetch(responses: Record<string, { status: number; body: unknown }>) {
|
||||
global.fetch = vi.fn(async (url: string | URL) => {
|
||||
const path = new URL(url).pathname;
|
||||
const match = Object.entries(responses).find(([key]) => path.includes(key));
|
||||
if (!match) return new Response("{}", { status: 404 });
|
||||
const { status, body } = match[1];
|
||||
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
describe("archive load — graceful degradation", () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("returns archive info on 200", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 200, body: archiveBody } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).not.toBeNull();
|
||||
expect(info?.name).toBe("Test Archive");
|
||||
});
|
||||
|
||||
it("returns null on 500 (transient error, no throw)", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 500, body: {} } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on 502 (transient error, no throw)", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 502, body: {} } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on 503 (transient error, no throw)", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 503, body: {} } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it("throws notFound on 404", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 404, body: {} } });
|
||||
await expect(load(archiveBody.id)).rejects.toThrow("notFound");
|
||||
});
|
||||
|
||||
it("throws notFound on 400", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 400, body: {} } });
|
||||
await expect(load(archiveBody.id)).rejects.toThrow("notFound");
|
||||
});
|
||||
});
|
||||
@@ -15,10 +15,10 @@ export interface ArchiveInfo {
|
||||
base?: string;
|
||||
}
|
||||
|
||||
export async function load(id: string): Promise<ArchiveInfo> {
|
||||
export async function load(id: string): Promise<ArchiveInfo | null> {
|
||||
if (!/^[0-9a-f-]{36}$/i.test(id)) notFound();
|
||||
const res = await fetch(`${API}/v1/archive/${id}`, { cache: "no-store" });
|
||||
if (res.status === 404 || res.status === 400) notFound();
|
||||
if (!res.ok) throw new Error(`archive ${id}: ${res.status}`);
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as ArchiveInfo;
|
||||
}
|
||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const info = await load(id);
|
||||
return { title: `Pessoa · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Pessoa · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function PersonPage({ params }: Params) {
|
||||
|
||||
@@ -8,7 +8,7 @@ type Params = { params: Promise<{ id: string }>; searchParams: Promise<{ t?: str
|
||||
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const info = await load((await params).id);
|
||||
return { title: `Arquivo · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Arquivo · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-1
@@ -10,7 +10,8 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
the webhook secret from `.env`), checks `ref == refs/heads/main`, and that the push touched a path this
|
||||
container owns (table below). Otherwise it answers 202 and does nothing.
|
||||
3. It runs `infra/deploy/<service>.sh <sha>` under a lock (one deploy at a time per container):
|
||||
- `git fetch` + `git reset --hard <sha>` in `/srv/photoreport`
|
||||
- `git fetch`; a sha that is not the tip of `origin/main` is logged and skipped (exit 0, anti-downgrade, BIT-34038)
|
||||
- `git reset --hard <sha>` in `/srv/photoreport`
|
||||
- `pnpm install --frozen-lockfile` / `cargo build --release -p <crate>` as needed
|
||||
- build only the affected package (`pnpm --filter <pkg> build`)
|
||||
- API only: `prisma migrate deploy`
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
|
||||
const SCRIPT = path.resolve(__dirname, "../../deploy/deploy.sh");
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), "deploy-guard-"));
|
||||
afterAll(() => rmSync(tmp, { recursive: true, force: true }));
|
||||
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd, encoding: "utf8" }).trim();
|
||||
|
||||
describe("deploy.sh anti-downgrade (BIT-34038)", () => {
|
||||
it("skips an old ancestor SHA with exit 0 and leaves the checkout untouched", () => {
|
||||
const origin = path.join(tmp, "origin.git");
|
||||
const work = path.join(tmp, "work");
|
||||
git(tmp, "init", "-q", "--bare", "-b", "main", origin);
|
||||
git(tmp, "clone", "-q", origin, work);
|
||||
git(work, "commit", "-q", "--allow-empty", "-m", "old");
|
||||
const oldSha = git(work, "rev-parse", "HEAD");
|
||||
git(work, "commit", "-q", "--allow-empty", "-m", "new");
|
||||
const tip = git(work, "rev-parse", "HEAD");
|
||||
git(work, "push", "-q", "origin", "main");
|
||||
|
||||
const r = spawnSync("bash", [SCRIPT, "pending", oldSha], {
|
||||
env: { ...process.env, DEPLOY_REPO_DIR: work, DEPLOY_BRANCH: "main" },
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain("SKIP");
|
||||
expect(git(work, "rev-parse", "HEAD")).toBe(tip);
|
||||
|
||||
// The tip itself is deployed (the "workers" service is a no-op build).
|
||||
const ok = spawnSync("bash", [SCRIPT, "workers", tip], {
|
||||
env: { ...process.env, DEPLOY_REPO_DIR: work, DEPLOY_BRANCH: "main" },
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(ok.status).toBe(0);
|
||||
expect(ok.stdout).toContain("succeeded");
|
||||
});
|
||||
});
|
||||
@@ -187,6 +187,17 @@ run_service() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Anti-downgrade (BIT-34038): a redelivered webhook for an older commit is still an ancestor of origin/main, so the
|
||||
# ancestry check in checkout() lets it through and `reset --hard` would move the site backwards (BIT-34036). Only the
|
||||
# tip of origin/main is deployed; anything else is logged and skipped with exit 0 (the receiver reports success, no
|
||||
# action). The newer push has its own webhook. The rollback below goes through checkout() directly, unaffected.
|
||||
git fetch --quiet origin "$BRANCH" || die "git fetch origin $BRANCH failed"
|
||||
TIP="$(git rev-parse "origin/$BRANCH")"
|
||||
if [[ "$SHA" != "$TIP" ]]; then
|
||||
log "SKIP: $SHA is not the tip of origin/$BRANCH ($TIP); refusing to deploy $SERVICE (anti-downgrade)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
PREVIOUS="$(git rev-parse HEAD)"
|
||||
log "deploying $SERVICE: $PREVIOUS -> $SHA"
|
||||
backup_env
|
||||
|
||||
Reference in new issue
Block a user