Compare commits

...
Author SHA1 Message Date
spark 3c84d2de1b Merge pull request 'fix(deploy): skip SHAs that are not the tip of origin/main (BIT-34038)' (#332) from fix/BIT-34038-deploy-anti-downgrade into main
ci / rust (push) Successful in 5m40s
ci / typescript (push) Successful in 11m8s
2026-12-04 23:03:46 +00:00
Tiago NevesandClaude Sonnet 5.5 664f55ee83 fix(deploy): skip SHAs that are not the tip of origin/main (BIT-34038)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 5m4s
ci / typescript (pull_request) Successful in 10m56s
A redelivered webhook for an old ancestor passed the ancestry check and reset the site backwards (BIT-34036). deploy.sh now fetches and skips with exit 0 unless SHA == origin/main tip. Rollback path unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-04 22:37:09 +00:00
spark f5af0f6239 Merge pull request 'fix(worker): downgrade P2037 to info in cloud target ensure at startup (BIT-33558)' (#331) from fix/BIT-33558-cloud-target-p2037-transient into main
ci / rust (push) Successful in 4m55s
ci / typescript (push) Successful in 11m22s
2026-12-04 14:31:09 +00:00
nelson-baptista baa22f7ea0 fix(worker): downgrade P2037 to info in cloud target ensure at startup (BIT-33558)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 9m22s
ci / typescript (pull_request) Successful in 14m46s
The ensureCloudM19Target and ensureCloudW17Target calls fire concurrently
at worker startup. During a deploy overlap (two workers live briefly), the
Postgres server hits max_connections and these one-shot queries get P2037.
The .catch() handler logged at warn with the raw error, which triggered
the reporter's logHooks and paged the error loop.

Follow the same pattern as develop/sports/archive workers: check
isPrismaTooManyConnections and log at info (below the reporter's warn
threshold) so the error loop stays quiet. The targets retry on the next
worker restart.

Also add tests for isPrismaTooManyConnections covering the P2037 code,
the bare message, the P2010/53300 raw-query variant, and negative cases.

Paperclip-Issue: BIT-33558
2026-12-04 14:00:54 +00:00
spark 6cd8ba0b95 Merge pull request 'fix(archive): skip rebuildDirectory when another worker holds the advisory lock (BIT-33539)' (#330) from fix/BIT-33539-archive-rebuild-directory-pk-race into main
ci / rust (push) Successful in 7m30s
ci / typescript (push) Successful in 12m50s
2026-12-04 13:32:29 +00:00
nelson-baptista 941688d2c9 fix(archive): skip rebuildDirectory when another worker holds the advisory lock (BIT-33539)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 4m1s
ci / typescript (pull_request) Successful in 10m53s
Two workers could pick the same due source from rebuildDue (the SELECT
has no locking), both call deleteMany + createMany in overlapping
transactions, and the second commit hit archive_team_sides_pkey with
P2002. Add pg_try_advisory_xact_lock(hashtext(sourceId)) at the start
of the transaction: the second worker skips instead of colliding.

Paperclip-Issue: BIT-33539
2026-12-04 13:20:12 +00:00
tiago-neves e780b575fb Merge pull request 'fix(archive): filter P2037 too-many-connections as transient (BIT-33550)' (#328) from fix/BIT-33550-archive-p2037-transient into main
ci / rust (push) Successful in 9m23s
ci / typescript (push) Failing after 15m56s
2026-12-04 12:57:39 +00:00
spark 243cabb221 fix(develop): treat 53300 pool exhaustion as transient in render poll (BIT-33549)
ci / rust (push) Successful in 6m2s
ci / typescript (push) Failing after 15m11s
The RenderWorker tick only checked isPostgresAdminShutdown (57P01). Extended isPrismaTooManyConnections to also match the P2010/53300 raw-query variant, and added a branch in the tick catch that logs at info and lets the next tick retry.

Paperclip-Issue: BIT-33549
2026-12-04 12:52:09 +00:00
nelson-baptista dc181533ab fix(archive): filter P2037 too-many-connections as transient (BIT-33550)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 8m8s
ci / typescript (pull_request) Successful in 15m6s
The rematch and takeOffFutureGames batch loops already stopped and
downgraded P1001/P2010 (unreachable) and 57P01 (admin shutdown) to info,
but P2037 (Too many database connections opened) fell through to log.warn
and paged the error loop for a transient pool-exhaustion blip.

Add isPrismaTooManyConnections checks to both catch blocks, mirroring the
BIT-33538 pattern in sports/service.ts: stop the batch and let the next
verifyAll retry once a slot frees.

Paperclip-Issue: BIT-33550
2026-12-04 12:18:09 +00:00
nelson-baptista 3c3a6c084f chore(site): trigger redeploy (BIT-33948)
ci / rust (push) Successful in 18m1s
ci / typescript (push) Failing after 21m46s
Paperclip-BIT-33948: nelson-baptista
2026-12-04 12:17:48 +00:00
spark aebf27f155 Merge pull request 'fix(site): degrade gracefully when archive API returns 5xx (BIT-33540)' (#326) from fix/BIT-33540-arquivo-500-graceful-degradation into main
ci / rust (push) Successful in 7m51s
ci / typescript (push) Successful in 14m58s
2026-12-04 11:33:01 +00:00
spark 85e2f41113 Merge pull request 'fix(sports): filter pg client not-queryable as transient (BIT-33527)' (#327) from fix/BIT-33527-pg-client-not-queryable-transient into main
ci / rust (push) Successful in 7m53s
ci / typescript (push) Successful in 14m44s
2026-12-04 11:32:56 +00:00
paula-alves 4092e194a9 fix(site): degrade gracefully when archive API returns 5xx (BIT-33540)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 8m36s
ci / typescript (pull_request) Successful in 14m33s
The /arquivo/[id] route's load() fetched /v1/archive/{id} on every
request and threw 'archive {id}: 500' when the API had a transient
Postgres outage (P2037 pool exhaustion). instrumentation.ts reported
every thrown error to errors.bitreport.pt, creating an error loop.

Return null from load() on 5xx instead of throwing, mirroring the
BIT-33541 pattern. ArchiveFrame renders a minimal 'temporarily
unavailable' shell, and all generateMetadata callers return a default
title when info is null. 404/400 still call notFound() as before.

Paperclip-Issue: BIT-33540
2026-12-04 11:13:41 +00:00
17 changed files with 340 additions and 18 deletions

No files matched your search

+98
View File
@@ -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");
});
});
+20 -2
View File
@@ -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. */
+37 -1
View File
@@ -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, {
+4 -1
View File
@@ -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;
+26 -1
View File
@@ -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(
+6 -4
View File
@@ -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
View File
@@ -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) {
+7
View File
@@ -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");
});
});
+2 -2
View File
@@ -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) {
+1 -1
View File
@@ -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
View File
@@ -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");
});
});
+11
View File
@@ -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