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 8d8573e53a fix(sports): filter pg client not-queryable as transient (BIT-33527)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 5m47s
ci / typescript (pull_request) Successful in 11m37s
A pooled pg Client that had a connection error (socket closed, server
restart, network blip) is marked not-queryable by node-postgres before
Prisma's adapter-pg runs the next query on it. The message
"Client has encountered a connection error and is not queryable" has no
Prisma error code, so the existing isPrismaConnectionClosed (P1017) check
does not catch it. The rejection escapes to the SportsWorker fillRegister
and tick catch blocks, logs as warn, and pages the error loop.

- Add isPgClientNotQueryable to lib/pg.ts and downgrade the error to info
  in fillRegister and tick (same pattern as BIT-32810, BIT-32083).
- Add the message to isTransientDatabaseError in reporter.ts so any other
  code path that lets it propagate to a generic log.error is also
  suppressed (same safety-net pattern as BIT-33537 for P2037).
- Add unit tests for the new helper and the reporter filter.

Paperclip-Issue: BIT-33527
2026-12-04 11:20:20 +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
paula-alves 03459fda8d fix(site): degrade gracefully when site API returns 500 (BIT-33541)
ci / rust (push) Successful in 9m6s
ci / typescript (push) Successful in 14m54s
The root layout and home page SSR fetch /v1/public/site on every
request. When the API has a transient Postgres outage (P2037 pool
exhaustion), it returns 500 and the site rethrows, which
instrumentation.ts reports to errors.bitreport.pt — creating an
error loop (8 repeats per cycle).

Catch the 500 in the layout (like the existing 404 path) and render
a minimal 'temporarily unavailable' shell without throwing, so
onRequestError never fires. Also make load() return null on
transient errors instead of throwing, as a safety net.

Paperclip-Issue: BIT-33541
2026-12-04 11:12:10 +00:00
paula-alves 6182c03cd5 fix(sports): downgrade transient P2037 too-many-connections to info in squad sync (BIT-33538)
ci / rust (push) Failing after 6s
ci / typescript (push) Successful in 10m10s
Prisma P2037 ("Too many database connections opened: remaining connection
slots are reserved for roles with the SUPERUSER attribute") is pool
exhaustion under concurrent worker load — the next scheduled tick reclaims
a freed slot. syncEventSquads already downgrades P1001 (unreachable) and
P1017 (connection closed) to info; P2037 was missing, so it escaped to the
archive caller's log.warn and paged the error loop.

Add isPrismaTooManyConnections to lib/pg.ts and handle it in both catch
sites of syncEventSquads (the outer wrapper and the inner savePlayers
loop), following the same stop-and-retry-next-run pattern.

Paperclip-Issue: BIT-33538
2026-12-04 10:49:42 +00:00
jos-alves ea29bd9b6e fix(reporter): filter Prisma P2037 pool-exhaustion as transient (BIT-33537) (#325)
ci / rust (push) Failing after 6s
ci / typescript (push) Successful in 9m50s
2026-12-04 10:43:49 +00:00
bug-squasher 1e3cee8612 Merge pull request 'Degrade gracefully when galleries API returns 5xx (BIT-33535)' (#324) from fix/BIT-33535-galleries-500-graceful-degradation into main
ci / rust (push) Successful in 7m5s
ci / typescript (push) Successful in 13m29s
2026-12-04 10:14:41 +00:00
spark 7b1596d8fa Merge pull request 'fix(archive): recover from P2002 race on cloud create in walk (BIT-33532)' (#323) from fix/BIT-33532-cloudfile-p2002-race into main
ci / rust (push) Successful in 5m44s
ci / typescript (push) Successful in 12m43s
2026-12-04 10:02:58 +00:00
paula-alves 932b9db233 Degrade gracefully when galleries API returns 5xx (BIT-33535)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 5m30s
ci / typescript (pull_request) Successful in 11m54s
The site home page SSR fetches galleries, latest, and popular in
Promise.all. When the API has a transient Postgres outage, the
galleries endpoint returns 500 and the site rethrows it, tripping
the Error Loop reporter. Wrap non-critical fetches (galleries,
latest, popular) with a safe() helper that returns empty data on
server errors while keeping 404 -> NotFound and 500 from getSite()
as real errors.

Paperclip-Issue: BIT-33535
2026-12-04 09:59:56 +00:00
25 changed files with 548 additions and 33 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;
+48 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { isPostgresAdminShutdown, 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(
@@ -138,6 +163,28 @@ describe("isPrismaTransactionClosed", () => {
});
});
describe("isPgClientNotQueryable", () => {
it("matches the raw pg client.js message (BIT-33527)", () => {
const err = new Error("Client has encountered a connection error and is not queryable");
expect(isPgClientNotQueryable(err)).toBe(true);
});
it("matches the message when wrapped in a Prisma raw-query failure", () => {
const err = new Error("Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `N/A`. Message: `Client has encountered a connection error and is not queryable`");
expect(isPgClientNotQueryable(err)).toBe(true);
});
it("does not match a server-closed (P1017) error", () => {
expect(isPgClientNotQueryable(new PrismaLike("P1017", "Server has closed the connection."))).toBe(false);
});
it("does not match an unrelated query error", () => {
expect(isPgClientNotQueryable(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false);
expect(isPgClientNotQueryable(null)).toBe(false);
expect(isPgClientNotQueryable("string")).toBe(false);
});
});
describe("retryOnConnectionClosed", () => {
it("retries once when the first attempt throws P1017 and returns the second result", async () => {
let calls = 0;
+27
View File
@@ -39,6 +39,21 @@ 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: …", 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|sorry, too many clients already|\b53300\b/i.test(err.message);
}
/**
* Prisma could not acquire a pooled connection to start a transaction within `maxWait`
* (code P2028, "Transaction API error: Unable to start a transaction in the given time.").
@@ -63,6 +78,18 @@ export function isPrismaTransactionClosed(err: unknown): boolean {
return /Transaction already closed/i.test(err.message);
}
/**
* A pooled `pg` Client had a connection error (socket closed, server restart, network blip) and was marked
* not-queryable by node-postgres before Prisma's adapter-pg ran the next query on it. The message comes from
* `pg/lib/client.js` and has no Prisma error code, so the `isPrismaConnectionClosed` (P1017) check does not
* catch it. The pool discards the dead client and hands out a fresh one on the next attempt, so this is
* transient and must not page the error loop (BIT-33527).
*/
export function isPgClientNotQueryable(err: unknown): boolean {
if (!(err instanceof Error)) return false;
return /Client has encountered a connection error and is not queryable/i.test(err.message);
}
/**
* Runs `fn`, retrying it once when Postgres closed the connection before the query (`P1017`). The pool hands out a
* fresh client on the next attempt, so a single retry clears the blip without surfacing it to the caller's
+7 -4
View File
@@ -12,19 +12,22 @@ import { createHash } from "node:crypto";
/**
* Transient PostgreSQL connection errors during a restart, graceful shutdown, network blip, or pool
* exhaustion. Prisma surfaces these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE
* (57P01/57P03/53300) or its own P1001/P1017. The realtime LISTEN/NOTIFY path uses `pg` directly and
* (57P01/57P03/53300) or its own P1001/P1017, and pool exhaustion (SQLSTATE 53300) as P2037 with the
* message "Too many database connections opened: sorry, too many clients already" — no SQLSTATE in the
* text, so the code check is what catches it. The realtime LISTEN/NOTIFY path uses `pg` directly and
* surfaces raw Node TCP errors (ECONNREFUSED) when Postgres is not listening at all. The pool reconnects
* on the next attempt, so these are not code bugs — reporting them only trips the Error Loop with one-off
* incidents from every code path that touches the database during the brief outage. Individual call sites
* that need to stop a batch or retry still check `isPostgresAdminShutdown` / `isPrismaServerUnreachable`
* (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the error propagate to a
* generic log.error (BIT-32490 and 11 sibling clusters, BIT-33548 for 53300, BIT-33524 for ECONNREFUSED).
* generic log.error (BIT-32490 and 11 sibling clusters, BIT-33548 for 53300, BIT-33537 for P2037,
* BIT-33524 for ECONNREFUSED).
*/
function isTransientDatabaseError(err: unknown): boolean {
if (!(err instanceof Error)) return false;
const code = (err as { code?: unknown }).code;
if (code === "P1001" || code === "P1017" || code === "ECONNREFUSED") return true;
return /57P01|57P03|53300|remaining connection slots are reserved|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection|ECONNREFUSED/i.test(err.message);
if (code === "P1001" || code === "P1017" || code === "P2037" || code === "ECONNREFUSED") return true;
return /57P01|57P03|53300|remaining connection slots are reserved|too many clients already|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection|Client has encountered a connection error and is not queryable|ECONNREFUSED/i.test(err.message);
}
export type ReportLevel = "critical" | "error" | "warning" | "info";
+23
View File
@@ -42,6 +42,12 @@ const p1017 = () =>
const p1017findUnique = () =>
Object.assign(new Error("Invalid `prisma.person.findUnique()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
const p2037 = () =>
Object.assign(
new Error("Invalid `prisma.event.findUnique()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"),
{ code: "P2037" },
);
const ligaTeam = (id: string, externalId: string) => ({
id,
provider: "LIGA",
@@ -271,6 +277,23 @@ describe("syncEventSquads downgrades a P1017 from person.findUnique in linkSquad
});
});
describe("syncEventSquads downgrades a P2037 too-many-connections error (BIT-33538)", () => {
it("logs at info and returns zeros when the initial event lookup hits P2037", async () => {
// The error loop reported P2037 ("Too many database connections opened: remaining connection slots are
// reserved for roles with the SUPERUSER attribute") from syncEventSquadsNow → db.event.findUnique. Without
// this guard the rejection escapes to the archive caller's warn and pages the error loop for a transient blip.
const db = {
event: { findUnique: async () => { throw p2037(); } },
};
const service = new SportsService(makeDeps(db));
const out = await service.syncEventSquads("evt-1");
expect(out).toEqual({ created: 0, updated: 0, headshots: 0 });
const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log;
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")).toBe(false);
});
});
describe("linkStoredSquads downgrades a 57P01 admin-terminated connection (BIT-32471)", () => {
it("logs at info and returns 0 when the raw query is terminated mid-flight (57P01)", async () => {
const db = {
+21 -2
View File
@@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js";
import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js";
import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.js";
@@ -1976,6 +1976,13 @@ export class SportsService {
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, database connection closed");
return { created: 0, updated: 0, headshots: 0 };
}
// The Postgres server is at max_connections and only SUPERUSER slots remain (P2037): every remaining query
// would fail the same way, so stop this sync and let the next scheduled run retry once a slot frees —
// rejecting to the archive caller's warn pages the error loop for a transient blip (BIT-33538).
if (isPrismaTooManyConnections(err)) {
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, too many database connections");
return { created: 0, updated: 0, headshots: 0 };
}
throw err;
}),
);
@@ -2019,6 +2026,12 @@ export class SportsService {
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, database unreachable");
return result;
}
// The Postgres server is at max_connections (P2037): stop the sync and let the next scheduled run retry
// once a slot frees — a warn per team pages the error loop for a transient blip (BIT-33538).
if (isPrismaTooManyConnections(err)) {
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, too many database connections");
return result;
}
// Same not-yet-published 400 as importLigaSquads/backfillLigaRegister: expected, kept out of the error hub.
if (err instanceof ProviderHttpError && err.status === 400)
log.info({ err, team: team.id }, "sports: liga squad not published yet for this team");
@@ -2711,6 +2724,8 @@ export class SportsWorker {
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction rolled back (connection blip or deadlock)");
} else if (isPrismaTransactionTimeout(err)) {
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction start timed out (pool contention)");
} else if (isPgClientNotQueryable(err)) {
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, pooled pg client was not queryable (connection blip)");
} else {
this.opts.log.warn({ err }, "sports: tick failed");
}
@@ -2733,7 +2748,11 @@ export class SportsWorker {
}
if (!this.stopped && saved >= 0 && this.opts.afterRegister) await this.opts.afterRegister();
} catch (err) {
this.opts.log.warn({ err }, "sports: register not filled");
if (isPgClientNotQueryable(err)) {
this.opts.log.info({ err: (err as Error).message }, "sports: register not filled, pooled pg client was not queryable (connection blip)");
} else {
this.opts.log.warn({ err }, "sports: register not filled");
}
} finally {
this.filling = false;
}
+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();
+4 -2
View File
@@ -91,7 +91,7 @@ describe("errors to errors.bitreport.pt", () => {
expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" });
});
it("does not report transient PostgreSQL shutdown/restart/unreachable errors (57P01/57P03/53300/P1001/P1017/ECONNREFUSED)", async () => {
it("does not report transient PostgreSQL shutdown/restart/unreachable errors (57P01/57P03/53300/P1001/P1017/P2037/ECONNREFUSED)", async () => {
const hub = fakeHub();
const reporter = reporterWith(hub.fetchImpl);
const sink = new Writable({ write: (_c, _e, cb) => cb() });
@@ -106,8 +106,10 @@ describe("errors to errors.bitreport.pt", () => {
log.error({ err: mk("Can't reach database server at localhost:5432", "P1001") }, "db unreachable");
log.error({ err: mk("Server has closed the connection.", "P1017") }, "connection closed");
log.error({ err: mk("Raw query failed. Code: `53300`. Message: `remaining connection slots are reserved for roles with the SUPERUSER attribute`", "P2010") }, "health: query failed");
log.error({ err: mk("Invalid `prisma.cloudSource.findUnique()` invocation:\n\nToo many database connections opened: sorry, too many clients already", "P2037") }, "archive: viewer source lookup failed");
log.error({ err: mk("connect ECONNREFUSED 127.0.0.1:5432", "ECONNREFUSED") }, "realtime error");
reporter.reportError(mk("Database error. Code: 57P03. Message: the database system is shutting down"), "worker");
log.error({ err: mk("Client has encountered a connection error and is not queryable") }, "sports: register not filled");
reporter.reportError(mk("Client has encountered a connection error and is not queryable"), "worker");
reporter.reportError(mk("connect ECONNREFUSED 127.0.0.1:5432", "ECONNREFUSED"), "api");
log.error({ err: new Error("render crashed") }, "real error");
await reporter.flush();
@@ -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 } };
}
/**
+26
View File
@@ -0,0 +1,26 @@
import type { LatestPhoto, PopularGallery, PublicGallerySummary } from "@photoreport/contracts";
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
function safe<T>(p: Promise<T>, fallback: T): Promise<T> {
return p.catch((err) => {
if (err instanceof NotFound) throw err;
return fallback;
});
}
export async function load(q: string, sport: string) {
const filtered = !!(q || sport);
try {
return await Promise.all([
getSite(),
safe(getGalleries({ q, sport }), { galleries: [] as PublicGallerySummary[], sports: [] as string[] }),
filtered ? Promise.resolve([] as LatestPhoto[]) : safe(getLatest(), [] as LatestPhoto[]),
filtered ? Promise.resolve([] as PopularGallery[]) : safe(getPopular(), [] as PopularGallery[]),
]);
} catch (err) {
if (err instanceof NotFound) return null;
// Transient API/DB errors (e.g. Postgres pool exhaustion) degrade to null so the page shows
// a neutral message instead of crashing and feeding the error loop reporter.
return null;
}
}
+15 -1
View File
@@ -40,7 +40,21 @@ export default async function RootLayout({ children }: { children: ReactNode })
try {
site = await getSite();
} catch (err) {
if (!(err instanceof NotFound)) throw err;
if (!(err instanceof NotFound)) {
// Transient API/DB errors (e.g. Postgres pool exhaustion) must not crash the layout —
// instrumentation.ts reports every thrown error to errors.bitreport.pt, creating an error
// loop. Render a minimal shell so the page returns 200 without a thrown error.
return (
<html lang="pt">
<body>
<ErrorReporter />
<main className="wrap empty">
<p>Temporariamente indisponível. Tenta novamente dentro de uns minutos.</p>
</main>
</body>
</html>
);
}
// The events domain (events.photoreport.pt) has no storefront: its event pages (QR page, kiosk) and the
// archive's sign-in pages stand alone.
if (path.startsWith("/e/") || path.startsWith("/arquivo/")) {
+68
View File
@@ -0,0 +1,68 @@
import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";
vi.mock("next/headers", () => ({
headers: () => Promise.resolve(new Headers({ host: "test.local" })),
cookies: () => Promise.resolve({ get: () => undefined }),
}));
const { load } = await import("./home-data");
const siteBody = {
id: "s1",
domain: "test.local",
skin: "photoreport",
name: "Test",
settings: {},
};
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("home load — graceful degradation", () => {
const originalFetch = global.fetch;
afterEach(() => {
global.fetch = originalFetch;
});
it("returns empty galleries when the galleries API returns 500", async () => {
mockFetch({
"/v1/public/site": { status: 200, body: siteBody },
"/v1/public/galleries": { status: 500, body: {} },
"/v1/public/latest": { status: 200, body: { photos: [] } },
"/v1/public/popular": { status: 200, body: { galleries: [] } },
});
const result = await load("", "");
expect(result).not.toBeNull();
if (!result) return;
const [, galleries] = result;
expect(galleries.galleries).toEqual([]);
expect(galleries.sports).toEqual([]);
});
it("returns null when the site API returns 404 (unconfigured shop)", async () => {
mockFetch({
"/v1/public/site": { status: 404, body: {} },
});
const result = await load("", "");
expect(result).toBeNull();
});
it("returns null when the site API returns 500 (transient error, graceful degradation)", async () => {
mockFetch({
"/v1/public/site": { status: 500, body: {} },
});
const result = await load("", "");
expect(result).toBeNull();
});
});
+1 -10
View File
@@ -1,22 +1,13 @@
import Link from "next/link";
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
import { eventTitle, longDate } from "../lib/format";
import { load } from "./home-data";
export const dynamic = "force-dynamic";
const SPORT_NAMES: Record<string, string> = { andebol: "Andebol", futebol: "Futebol", futsal: "Futsal", basquetebol: "Basquetebol", voleibol: "Voleibol", hoquei: "Hóquei", "hóquei em patins": "Hóquei em patins", rugby: "Râguebi", atletismo: "Atletismo" };
const sportName = (s: string) => SPORT_NAMES[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
async function load(q: string, sport: string) {
try {
const filtered = !!(q || sport);
return await Promise.all([getSite(), getGalleries({ q, sport }), filtered ? Promise.resolve([]) : getLatest(), filtered ? Promise.resolve([]) : getPopular()]);
} catch (err) {
if (err instanceof NotFound) return null;
throw err;
}
}
/** Home: search, sport shortcuts, the photos that just arrived, then the galleries. */
export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string; desporto?: string }> }) {
const params = await searchParams;
+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