Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c84d2de1b | ||
|
|
664f55ee83 | ||
|
|
f5af0f6239 | ||
|
|
baa22f7ea0 | ||
|
|
6cd8ba0b95 | ||
|
|
941688d2c9 | ||
|
|
e780b575fb | ||
|
|
243cabb221 | ||
|
|
dc181533ab | ||
|
|
3c3a6c084f | ||
|
|
aebf27f155 | ||
|
|
85e2f41113 | ||
|
|
8d8573e53a | ||
|
|
4092e194a9 | ||
|
|
03459fda8d | ||
|
|
6182c03cd5 | ||
|
|
ea29bd9b6e | ||
|
|
1e3cee8612 | ||
|
|
7b1596d8fa | ||
|
|
932b9db233 | ||
|
|
5287afb508 | ||
|
|
23c2f29a05 | ||
|
|
891c7f23ba | ||
|
|
d2616ce539 | ||
|
|
465937212c | ||
|
|
2ec4f263b6 | ||
|
|
cac99af991 | ||
|
|
312c1f1a68 | ||
|
|
5da37adf33 | ||
|
|
6b03ae5d11 | ||
|
|
d165996046 |
No files matched your search
+8
-3
@@ -142,9 +142,14 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
|||||||
|
|
||||||
registerClientErrors(app, reporter);
|
registerClientErrors(app, reporter);
|
||||||
|
|
||||||
app.get("/health", async () => {
|
app.get("/health", async (_req, reply) => {
|
||||||
await db.$queryRaw`SELECT 1`;
|
try {
|
||||||
return { status: "ok", version: config.APP_VERSION };
|
await db.$queryRaw`SELECT 1`;
|
||||||
|
return { status: "ok", version: config.APP_VERSION };
|
||||||
|
} catch {
|
||||||
|
reply.code(503);
|
||||||
|
return { status: "degraded", version: config.APP_VERSION };
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const authenticate = requireAuth(sessions);
|
const authenticate = requireAuth(sessions);
|
||||||
|
|||||||
@@ -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);
|
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 () => {
|
it("still warns on a real per-folder error", async () => {
|
||||||
const log = makeLog();
|
const log = makeLog();
|
||||||
const db = makeDb(async () => {
|
const db = makeDb(async () => {
|
||||||
@@ -205,4 +223,178 @@ 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 === "info" && /connection terminated/.test(c.msg))).toBe(true);
|
||||||
expect(log.calls.some((c) => c.level === "warn" && /not moved/.test(c.msg))).toBe(false);
|
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)", () => {
|
||||||
|
it("falls back to update on the compound key and still queues", async () => {
|
||||||
|
const createCalls: unknown[] = [];
|
||||||
|
const updateCalls: unknown[] = [];
|
||||||
|
const db = {
|
||||||
|
cloudFolder: {
|
||||||
|
findUnique: async () => null,
|
||||||
|
create: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }),
|
||||||
|
update: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }),
|
||||||
|
findMany: async () => [],
|
||||||
|
},
|
||||||
|
cloudFile: {
|
||||||
|
findMany: async () => [],
|
||||||
|
create: async (args: unknown) => {
|
||||||
|
createCalls.push(args);
|
||||||
|
throw Object.assign(new Error("Unique constraint failed on the constraint: cloud_files_source_id_file_id_key"), { code: "P2002" });
|
||||||
|
},
|
||||||
|
update: async (args: unknown) => {
|
||||||
|
updateCalls.push(args);
|
||||||
|
return { id: "cf-1" };
|
||||||
|
},
|
||||||
|
deleteMany: async () => ({ count: 0 }),
|
||||||
|
},
|
||||||
|
cloudVideo: {
|
||||||
|
findMany: async () => [],
|
||||||
|
deleteMany: async () => ({ count: 0 }),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const client = {
|
||||||
|
list: async () => ({
|
||||||
|
self: { path: "/root", name: "root", fileId: "fld-1", etag: "fe1", size: 0, isDir: true, contentType: null, modifiedAt: null },
|
||||||
|
children: [{ path: "/root/a.jpg", name: "a.jpg", fileId: "img-1", etag: "ie1", size: 100, isDir: false, contentType: "image/jpeg", modifiedAt: null }],
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const service = new ArchiveService({ db, log: { info() {}, debug() {}, error() {}, warn() {} } } as never);
|
||||||
|
const stats = { folders: 0, queued: 0 };
|
||||||
|
await (service as unknown as { walk: (source: unknown, client: unknown, folderPath: string, parent: unknown, stats: { folders: number; queued: number }, full: boolean, seen?: unknown) => Promise<void> }).walk(
|
||||||
|
{ id: "src-1", rootPath: "/root", secretEnc: "x" },
|
||||||
|
client,
|
||||||
|
"/root",
|
||||||
|
null,
|
||||||
|
stats,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(createCalls).toHaveLength(1);
|
||||||
|
expect(updateCalls).toHaveLength(1);
|
||||||
|
const update = updateCalls[0] as { where: { sourceId_fileId: { sourceId: string; fileId: string } }; data: { folderId: string; etag: string } };
|
||||||
|
expect(update.where.sourceId_fileId).toEqual({ sourceId: "src-1", fileId: "img-1" });
|
||||||
|
expect(update.data.folderId).toBe("fld-1");
|
||||||
|
expect(update.data.etag).toBe("ie1");
|
||||||
|
expect(stats.queued).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rethrows non-P2002 errors from cloudFile.create", async () => {
|
||||||
|
const db = {
|
||||||
|
cloudFolder: {
|
||||||
|
findUnique: async () => null,
|
||||||
|
create: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }),
|
||||||
|
update: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }),
|
||||||
|
findMany: async () => [],
|
||||||
|
},
|
||||||
|
cloudFile: {
|
||||||
|
findMany: async () => [],
|
||||||
|
create: async () => {
|
||||||
|
throw Object.assign(new Error("boom"), { code: "P2025" });
|
||||||
|
},
|
||||||
|
update: async () => ({ id: "cf-1" }),
|
||||||
|
deleteMany: async () => ({ count: 0 }),
|
||||||
|
},
|
||||||
|
cloudVideo: {
|
||||||
|
findMany: async () => [],
|
||||||
|
deleteMany: async () => ({ count: 0 }),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const client = {
|
||||||
|
list: async () => ({
|
||||||
|
self: { path: "/root", name: "root", fileId: "fld-1", etag: "fe1", size: 0, isDir: true, contentType: null, modifiedAt: null },
|
||||||
|
children: [{ path: "/root/a.jpg", name: "a.jpg", fileId: "img-1", etag: "ie1", size: 100, isDir: false, contentType: "image/jpeg", modifiedAt: null }],
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const service = new ArchiveService({ db, log: { info() {}, debug() {}, error() {}, warn() {} } } as never);
|
||||||
|
await expect(
|
||||||
|
(service as unknown as { walk: (source: unknown, client: unknown, folderPath: string, parent: unknown, stats: { folders: number; queued: number }, full: boolean, seen?: unknown) => Promise<void> }).walk(
|
||||||
|
{ id: "src-1", rootPath: "/root", secretEnc: "x" },
|
||||||
|
client,
|
||||||
|
"/root",
|
||||||
|
null,
|
||||||
|
{ folders: 0, queued: 0 },
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
).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 type { IngestLogger, IngestService } from "../ingest/service.js";
|
||||||
import { ingestWindow } from "../library/events.js";
|
import { ingestWindow } from "../library/events.js";
|
||||||
import { waitUntil } from "../lib/idle.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 type { LocalStorage } from "../storage/storage.js";
|
||||||
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
|
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
|
||||||
import {
|
import {
|
||||||
@@ -371,11 +371,19 @@ export class ArchiveService {
|
|||||||
if (known.parentId !== (parent?.id ?? null)) await db.cloudFolder.update({ where: { id: known.id }, data: { parentId: parent?.id ?? null } });
|
if (known.parentId !== (parent?.id ?? null)) await db.cloudFolder.update({ where: { id: known.id }, data: { parentId: parent?.id ?? null } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let folder = known
|
let folder: CloudFolder;
|
||||||
? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } })
|
if (known) {
|
||||||
: await db.cloudFolder.create({
|
folder = await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } });
|
||||||
data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) },
|
} else {
|
||||||
});
|
const data = { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) };
|
||||||
|
try {
|
||||||
|
folder = await db.cloudFolder.create({ data });
|
||||||
|
} catch (err) {
|
||||||
|
// A concurrent walk pass may have inserted this folder between our findUnique and create (BIT-33532).
|
||||||
|
if ((err as { code?: string }).code !== "P2002") throw err;
|
||||||
|
folder = await db.cloudFolder.update({ where: { sourceId_fileId: { sourceId: source.id, fileId: self.fileId } }, data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const dirs = children.filter((c) => c.isDir);
|
const dirs = children.filter((c) => c.isDir);
|
||||||
const images = children.filter((c) => !c.isDir && IMAGE.test(c.name));
|
const images = children.filter((c) => !c.isDir && IMAGE.test(c.name));
|
||||||
@@ -387,7 +395,16 @@ export class ArchiveService {
|
|||||||
for (const img of images) {
|
for (const img of images) {
|
||||||
const f = byId.get(img.fileId);
|
const f = byId.get(img.fileId);
|
||||||
if (!f) {
|
if (!f) {
|
||||||
await db.cloudFile.create({ data: { sourceId: source.id, folderId: folder.id, fileId: img.fileId, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size) } });
|
try {
|
||||||
|
await db.cloudFile.create({ data: { sourceId: source.id, folderId: folder.id, fileId: img.fileId, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size) } });
|
||||||
|
} catch (err) {
|
||||||
|
// A concurrent walk pass may have inserted this file between our findMany and create (BIT-33532).
|
||||||
|
if ((err as { code?: string }).code !== "P2002") throw err;
|
||||||
|
await db.cloudFile.update({
|
||||||
|
where: { sourceId_fileId: { sourceId: source.id, fileId: img.fileId } },
|
||||||
|
data: { folderId: folder.id, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size) },
|
||||||
|
});
|
||||||
|
}
|
||||||
stats.queued++;
|
stats.queued++;
|
||||||
} else if (f.etag !== img.etag) {
|
} else if (f.etag !== img.etag) {
|
||||||
await db.cloudFile.update({ where: { id: f.id }, data: { folderId: folder.id, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size), status: "PENDING", attempts: 0, error: null } });
|
await db.cloudFile.update({ where: { id: f.id }, data: { folderId: folder.id, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size), status: "PENDING", attempts: 0, error: null } });
|
||||||
@@ -405,7 +422,16 @@ export class ArchiveService {
|
|||||||
const v = videoById.get(vid.fileId);
|
const v = videoById.get(vid.fileId);
|
||||||
const size = vid.size === null ? null : BigInt(vid.size);
|
const size = vid.size === null ? null : BigInt(vid.size);
|
||||||
if (!v) {
|
if (!v) {
|
||||||
await db.cloudVideo.create({ data: { sourceId: source.id, folderId: folder.id, fileId: vid.fileId, path: vid.path, etag: vid.etag, size } });
|
try {
|
||||||
|
await db.cloudVideo.create({ data: { sourceId: source.id, folderId: folder.id, fileId: vid.fileId, path: vid.path, etag: vid.etag, size } });
|
||||||
|
} catch (err) {
|
||||||
|
// A concurrent walk pass may have inserted this video between our findMany and create (BIT-33532).
|
||||||
|
if ((err as { code?: string }).code !== "P2002") throw err;
|
||||||
|
await db.cloudVideo.update({
|
||||||
|
where: { sourceId_fileId: { sourceId: source.id, fileId: vid.fileId } },
|
||||||
|
data: { folderId: folder.id, path: vid.path, etag: vid.etag, size },
|
||||||
|
});
|
||||||
|
}
|
||||||
stats.queued++;
|
stats.queued++;
|
||||||
} else if (v.etag !== vid.etag) {
|
} else if (v.etag !== vid.etag) {
|
||||||
await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path, etag: vid.etag, size, status: "PENDING", attempts: 0, error: null } });
|
await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path, etag: vid.etag, size, status: "PENDING", attempts: 0, error: null } });
|
||||||
@@ -632,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");
|
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: future-game check stopped, database connection terminated");
|
||||||
break;
|
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");
|
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery on a game still to come not moved");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -690,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");
|
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: gallery check stopped, database connection terminated");
|
||||||
break;
|
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");
|
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) });
|
report?.errors.push({ path: folder.path, error: err instanceof Error ? err.message : String(err) });
|
||||||
}
|
}
|
||||||
@@ -1425,7 +1465,11 @@ export class ArchiveService {
|
|||||||
const games = new Map<string, { id: string; home: string; away: string }>();
|
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);
|
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])));
|
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) => {
|
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 } });
|
await tx.archiveTeamSide.deleteMany({ where: { sourceId } });
|
||||||
const chunk = 2000;
|
const chunk = 2000;
|
||||||
for (let i = 0; i < rows.length; i += chunk) {
|
for (let i = 0; i < rows.length; i += chunk) {
|
||||||
@@ -1438,7 +1482,7 @@ export class ArchiveService {
|
|||||||
data: { directoryBuiltAt: new Date(), directoryDirtyAt: null },
|
data: { directoryBuiltAt: new Date(), directoryDirtyAt: null },
|
||||||
});
|
});
|
||||||
}, { timeout: 60_000, maxWait: 60_000 });
|
}, { timeout: 60_000, maxWait: 60_000 });
|
||||||
return rows.length;
|
return stored;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One archive whose teams were never stored, or have changed. */
|
/** One archive whose teams were never stored, or have changed. */
|
||||||
|
|||||||
@@ -82,6 +82,41 @@ const median = (xs: number[]) => {
|
|||||||
return s[Math.floor(s.length / 2)]!;
|
return s[Math.floor(s.length / 2)]!;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** A gallery window. Warm-up (more than one window before kick-off) is −1 and is never sent. */
|
||||||
|
export const BEST_WINDOW_MS = 5 * 60_000;
|
||||||
|
|
||||||
|
/** Window index from kick-off. The five minutes just before the start still belong to the first window. */
|
||||||
|
export function bestWindow(at: number, start: number, windowMs = BEST_WINDOW_MS): number {
|
||||||
|
if (at < start - windowMs) return -1;
|
||||||
|
const index = Math.floor((at - start) / windowMs);
|
||||||
|
if (index < 0) return 0;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Windows that still have a frame being analysed. A live match keeps receiving photos, so a closed
|
||||||
|
* window must be allowed to send while a later one is still open.
|
||||||
|
*/
|
||||||
|
export function windowsStillArriving(start: number, inflightAt: readonly number[], windowMs = BEST_WINDOW_MS): Set<number> {
|
||||||
|
const blocked = new Set<number>();
|
||||||
|
for (const at of inflightAt) {
|
||||||
|
const window = bestWindow(at, start, windowMs);
|
||||||
|
if (window < 0) continue;
|
||||||
|
blocked.add(window);
|
||||||
|
}
|
||||||
|
return blocked;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when another frame of this same moment is still being analysed, so the burst is not complete. */
|
||||||
|
export function burstStillArriving(from: number, to: number, inflightAt: readonly number[], gapMs: number): boolean {
|
||||||
|
for (const at of inflightAt) {
|
||||||
|
if (at < from - gapMs) continue;
|
||||||
|
if (at > to + gapMs) continue;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How many frames a gallery may reach. The asked size is the target: about 15% more when the match is rich,
|
* How many frames a gallery may reach. The asked size is the target: about 15% more when the match is rich,
|
||||||
* at least 2 and never more than 25 past it, so a short gallery stays close and a long one can breathe.
|
* at least 2 and never more than 25 past it, so a short gallery stays close and a long one can breathe.
|
||||||
@@ -96,7 +131,7 @@ export function galleryCeiling(count: number): number {
|
|||||||
* (chosen or not), so earlier choices count against the gallery size.
|
* (chosen or not), so earlier choices count against the gallery size.
|
||||||
*/
|
*/
|
||||||
export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] {
|
export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] {
|
||||||
const windowMs = opts.windowMs ?? 5 * 60_000;
|
const windowMs = opts.windowMs ?? BEST_WINDOW_MS;
|
||||||
const minGapMs = opts.minGapMs ?? 5_000;
|
const minGapMs = opts.minGapMs ?? 5_000;
|
||||||
const sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS;
|
const sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS;
|
||||||
const sequenceCap = opts.sequenceCap ?? SEQUENCE_PICK_CAP;
|
const sequenceCap = opts.sequenceCap ?? SEQUENCE_PICK_CAP;
|
||||||
@@ -119,8 +154,8 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b
|
|||||||
const byWindow = new Map<number, typeof scored>();
|
const byWindow = new Map<number, typeof scored>();
|
||||||
for (const x of scored) {
|
for (const x of scored) {
|
||||||
if (done.has(x.c.id)) continue;
|
if (done.has(x.c.id)) continue;
|
||||||
// Warm-up and line-ups (more than 5 minutes before kick-off) are not game moments.
|
// Warm-up and line-ups (more than one window before kick-off) are not game moments.
|
||||||
const w = x.c.at < opts.start - 5 * 60_000 ? -1 : Math.max(0, Math.floor((x.c.at - opts.start) / windowMs));
|
const w = bestWindow(x.c.at, opts.start, windowMs);
|
||||||
byWindow.set(w, [...(byWindow.get(w) ?? []), x]);
|
byWindow.set(w, [...(byWindow.get(w) ?? []), x]);
|
||||||
}
|
}
|
||||||
const out: WindowDecision[] = [];
|
const out: WindowDecision[] = [];
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { BEST_WINDOW_MS, bestWindow, burstStillArriving, windowsStillArriving } from "./curate.js";
|
||||||
|
|
||||||
|
const start = Date.parse("2026-11-29T17:00:00Z");
|
||||||
|
|
||||||
|
describe("best windows while a match is still being analysed", () => {
|
||||||
|
it("keeps the five minutes before kick-off in the first window and the warm-up out", () => {
|
||||||
|
expect(bestWindow(start - BEST_WINDOW_MS - 1, start)).toBe(-1);
|
||||||
|
expect(bestWindow(start - 60_000, start)).toBe(0);
|
||||||
|
expect(bestWindow(start + BEST_WINDOW_MS, start)).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("blocks only the window that still has a frame in analysis", () => {
|
||||||
|
const later = start + 10 * BEST_WINDOW_MS + 30_000;
|
||||||
|
const blocked = windowsStillArriving(start, [later]);
|
||||||
|
expect(blocked.has(0)).toBe(false);
|
||||||
|
expect(blocked.has(10)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("holds a burst when another frame of the same moment is still in analysis", () => {
|
||||||
|
const from = start + 1_000;
|
||||||
|
const to = start + 1_400;
|
||||||
|
expect(burstStillArriving(from, to, [to + 500], 1_000)).toBe(true);
|
||||||
|
expect(burstStillArriving(from, to, [to + 5_000], 1_000)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { homeRestDecision, type FaceHint } from "./home-rest.js";
|
||||||
|
|
||||||
|
const start = Date.parse("2026-12-02T20:15:00Z");
|
||||||
|
const leadMin = 10;
|
||||||
|
const homeNames = new Set(["joao silva"]);
|
||||||
|
const homeClubs = new Set(["u. leiria"]);
|
||||||
|
const awayNames = new Set(["costa"]);
|
||||||
|
const awayClubs = new Set(["sporting cp b"]);
|
||||||
|
|
||||||
|
function decide(extra: {
|
||||||
|
at: number;
|
||||||
|
playerNames?: string[];
|
||||||
|
faces?: FaceHint[];
|
||||||
|
homeTeamId?: string | null;
|
||||||
|
}) {
|
||||||
|
return homeRestDecision({
|
||||||
|
at: extra.at,
|
||||||
|
start,
|
||||||
|
leadMin,
|
||||||
|
playerNames: extra.playerNames ?? [],
|
||||||
|
faces: extra.faces ?? [],
|
||||||
|
homeTeamId: extra.homeTeamId ?? "home",
|
||||||
|
homeNames,
|
||||||
|
homeClubs,
|
||||||
|
awayTeamId: "away",
|
||||||
|
awayNames,
|
||||||
|
awayClubs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("leftover picks before and during a match", () => {
|
||||||
|
it("sends every leftover pick until ten minutes before kick-off", () => {
|
||||||
|
expect(decide({ at: start - 10 * 60_000 })).toBe("send");
|
||||||
|
expect(decide({ at: start - 10 * 60_000 - 1 })).toBe("send");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends a home player and a frame we cannot name after the cutoff", () => {
|
||||||
|
const after = start - 10 * 60_000 + 1;
|
||||||
|
expect(decide({ at: after, playerNames: ["João Silva"] })).toBe("send");
|
||||||
|
expect(
|
||||||
|
decide({
|
||||||
|
at: after,
|
||||||
|
faces: [{ teamId: "home", name: "Outro", club: null, open: false }],
|
||||||
|
}),
|
||||||
|
).toBe("send");
|
||||||
|
expect(
|
||||||
|
decide({
|
||||||
|
at: after,
|
||||||
|
faces: [{ teamId: null, name: null, club: null, open: true }],
|
||||||
|
}),
|
||||||
|
).toBe("send");
|
||||||
|
expect(decide({ at: after })).toBe("send");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not send a frame that is clearly only the away team", () => {
|
||||||
|
const after = start + 30_000;
|
||||||
|
expect(
|
||||||
|
decide({
|
||||||
|
at: after,
|
||||||
|
faces: [{ teamId: "away", name: "Costa", club: "Sporting CP B", open: false }],
|
||||||
|
}),
|
||||||
|
).toBe("skip");
|
||||||
|
expect(decide({ at: after, playerNames: ["Costa"] })).toBe("skip");
|
||||||
|
expect(
|
||||||
|
decide({
|
||||||
|
at: after,
|
||||||
|
faces: [
|
||||||
|
{ teamId: "away", name: "Costa", club: "Sporting CP B", open: false },
|
||||||
|
{ teamId: null, name: null, club: null, open: true },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).toBe("send");
|
||||||
|
expect(
|
||||||
|
decide({
|
||||||
|
at: after,
|
||||||
|
faces: [{ teamId: null, name: "Árbitro", club: "Arbitragem", open: false }],
|
||||||
|
}),
|
||||||
|
).toBe("send");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
/** Same bar the face worker uses before it trusts a suggestion (faces/service.ts). */
|
||||||
|
export const STRONG_FACE = 0.85;
|
||||||
|
|
||||||
|
export interface FaceHint {
|
||||||
|
teamId: string | null;
|
||||||
|
name: string | null;
|
||||||
|
club: string | null;
|
||||||
|
/** A face is in the frame and nobody confident has been named yet. */
|
||||||
|
open: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NamedPerson {
|
||||||
|
name: string;
|
||||||
|
club: string | null;
|
||||||
|
teamId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One face group, reduced to whether we can already tell the team. Ignored groups are not people. */
|
||||||
|
export function hintFromGroup(
|
||||||
|
group: {
|
||||||
|
personId: string | null;
|
||||||
|
suggestedPersonId: string | null;
|
||||||
|
suggestionScore: number | null;
|
||||||
|
ignored: boolean;
|
||||||
|
} | null,
|
||||||
|
person: NamedPerson | null,
|
||||||
|
suggested: NamedPerson | null,
|
||||||
|
): FaceHint | null {
|
||||||
|
if (!group || group.ignored) return null;
|
||||||
|
if (group.personId) {
|
||||||
|
if (!person) return { teamId: null, name: null, club: null, open: true };
|
||||||
|
return { teamId: person.teamId, name: person.name, club: person.club, open: false };
|
||||||
|
}
|
||||||
|
const score = group.suggestionScore ?? 0;
|
||||||
|
if (group.suggestedPersonId && score >= STRONG_FACE) {
|
||||||
|
if (!suggested) return { teamId: null, name: null, club: null, open: true };
|
||||||
|
return { teamId: suggested.teamId, name: suggested.name, club: suggested.club, open: false };
|
||||||
|
}
|
||||||
|
return { teamId: null, name: null, club: null, open: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function foldName(value: string | null | undefined): string {
|
||||||
|
if (!value) return "";
|
||||||
|
return value
|
||||||
|
.normalize("NFD")
|
||||||
|
.replace(/[\u0300-\u036f]/g, "")
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function namedHome(
|
||||||
|
name: string | null,
|
||||||
|
club: string | null,
|
||||||
|
homeNames: ReadonlySet<string>,
|
||||||
|
homeClubs: ReadonlySet<string>,
|
||||||
|
): boolean {
|
||||||
|
const foldedName = foldName(name);
|
||||||
|
if (foldedName && homeNames.has(foldedName)) return true;
|
||||||
|
const foldedClub = foldName(club);
|
||||||
|
if (foldedClub && homeClubs.has(foldedClub)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when this frame shows someone from the home squad. */
|
||||||
|
export function isHomePlayer(input: {
|
||||||
|
playerNames: readonly string[];
|
||||||
|
faces: readonly FaceHint[];
|
||||||
|
homeTeamId: string | null;
|
||||||
|
homeNames: ReadonlySet<string>;
|
||||||
|
homeClubs: ReadonlySet<string>;
|
||||||
|
}): boolean {
|
||||||
|
for (const name of input.playerNames) {
|
||||||
|
if (namedHome(name, null, input.homeNames, input.homeClubs)) return true;
|
||||||
|
}
|
||||||
|
for (const face of input.faces) {
|
||||||
|
if (face.open) continue;
|
||||||
|
if (input.homeTeamId && face.teamId === input.homeTeamId) return true;
|
||||||
|
if (namedHome(face.name, face.club, input.homeNames, input.homeClubs)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchesSide(
|
||||||
|
name: string | null,
|
||||||
|
club: string | null,
|
||||||
|
teamId: string | null,
|
||||||
|
sideTeamId: string | null,
|
||||||
|
sideNames: ReadonlySet<string>,
|
||||||
|
sideClubs: ReadonlySet<string>,
|
||||||
|
): boolean {
|
||||||
|
if (sideTeamId && teamId === sideTeamId) return true;
|
||||||
|
const foldedName = foldName(name);
|
||||||
|
if (foldedName && sideNames.has(foldedName)) return true;
|
||||||
|
const foldedClub = foldName(club);
|
||||||
|
if (foldedClub && sideClubs.has(foldedClub)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when every identified person in the frame is the away side, and nobody is still unnamed.
|
||||||
|
* A missing face, a weak guess, or a home player is not this case.
|
||||||
|
*/
|
||||||
|
export function isClearlyOnlyAway(input: {
|
||||||
|
playerNames: readonly string[];
|
||||||
|
faces: readonly FaceHint[];
|
||||||
|
awayTeamId: string | null;
|
||||||
|
awayNames: ReadonlySet<string>;
|
||||||
|
awayClubs: ReadonlySet<string>;
|
||||||
|
homeTeamId: string | null;
|
||||||
|
homeNames: ReadonlySet<string>;
|
||||||
|
homeClubs: ReadonlySet<string>;
|
||||||
|
}): boolean {
|
||||||
|
const namedPlayers: string[] = [];
|
||||||
|
for (const name of input.playerNames) {
|
||||||
|
if (foldName(name)) namedPlayers.push(name);
|
||||||
|
}
|
||||||
|
if (namedPlayers.length === 0 && input.faces.length === 0) return false;
|
||||||
|
|
||||||
|
for (const face of input.faces) {
|
||||||
|
if (face.open) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of namedPlayers) {
|
||||||
|
const home = matchesSide(name, null, null, input.homeTeamId, input.homeNames, input.homeClubs);
|
||||||
|
if (home) return false;
|
||||||
|
const away = matchesSide(name, null, null, input.awayTeamId, input.awayNames, input.awayClubs);
|
||||||
|
if (!away) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const face of input.faces) {
|
||||||
|
const home = matchesSide(face.name, face.club, face.teamId, input.homeTeamId, input.homeNames, input.homeClubs);
|
||||||
|
if (home) return false;
|
||||||
|
const away = matchesSide(face.name, face.club, face.teamId, input.awayTeamId, input.awayNames, input.awayClubs);
|
||||||
|
if (!away) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Leftover picks for the rest destination.
|
||||||
|
* Up to `leadMin` before kick-off, every leftover pick goes.
|
||||||
|
* After that, a pick still goes unless the frame is clearly only the away team.
|
||||||
|
* An unidentified player is sent: the reference set is incomplete, and the client deletes the odd frame.
|
||||||
|
*/
|
||||||
|
export function homeRestDecision(input: {
|
||||||
|
at: number;
|
||||||
|
start: number;
|
||||||
|
leadMin: number;
|
||||||
|
playerNames: readonly string[];
|
||||||
|
faces: readonly FaceHint[];
|
||||||
|
homeTeamId: string | null;
|
||||||
|
homeNames: ReadonlySet<string>;
|
||||||
|
homeClubs: ReadonlySet<string>;
|
||||||
|
awayTeamId: string | null;
|
||||||
|
awayNames: ReadonlySet<string>;
|
||||||
|
awayClubs: ReadonlySet<string>;
|
||||||
|
}): "send" | "skip" | "wait" {
|
||||||
|
const cutoff = input.start - input.leadMin * 60_000;
|
||||||
|
if (input.at <= cutoff) return "send";
|
||||||
|
if (isHomePlayer(input)) return "send";
|
||||||
|
if (isClearlyOnlyAway(input)) return "skip";
|
||||||
|
return "send";
|
||||||
|
}
|
||||||
@@ -26,7 +26,8 @@ import {
|
|||||||
sequenceIndex,
|
sequenceIndex,
|
||||||
sequenceSendRoom,
|
sequenceSendRoom,
|
||||||
} from "./bursts.js";
|
} from "./bursts.js";
|
||||||
import { curate, matchMinutes } from "./curate.js";
|
import { bestWindow, burstStillArriving, curate, matchMinutes, windowsStillArriving } from "./curate.js";
|
||||||
|
import { foldName, hintFromGroup, homeRestDecision, type FaceHint, type NamedPerson } from "./home-rest.js";
|
||||||
import { type LearntStyle, learntStyle } from "./learning.js";
|
import { type LearntStyle, learntStyle } from "./learning.js";
|
||||||
import { detailForCrop, lookValues } from "./look.js";
|
import { detailForCrop, lookValues } from "./look.js";
|
||||||
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
|
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
|
||||||
@@ -46,6 +47,20 @@ function takenHere(ids: readonly string[], when: ReadonlyMap<string, Date | null
|
|||||||
return ids.filter((id) => takenDuring(when.get(id), event));
|
return ids.filter((id) => takenDuring(when.get(id), event));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Capture time of photos this event is still analysing. A live match uses this so closed windows are not held back. */
|
||||||
|
async function inflightCaptureTimes(db: Db, eventId: string): Promise<number[]> {
|
||||||
|
const rows = await db.photo.findMany({
|
||||||
|
where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } },
|
||||||
|
select: { capturedAt: true, createdAt: true },
|
||||||
|
});
|
||||||
|
const times: number[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const at = row.capturedAt ?? row.createdAt;
|
||||||
|
times.push(at.getTime());
|
||||||
|
}
|
||||||
|
return times;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AutopilotRecord {
|
export interface AutopilotRecord {
|
||||||
score: number;
|
score: number;
|
||||||
reason: string | null;
|
reason: string | null;
|
||||||
@@ -78,6 +93,12 @@ export interface AutopilotRecord {
|
|||||||
hold?: "ball";
|
hold?: "ball";
|
||||||
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
|
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
|
||||||
gallery?: Record<string, boolean>;
|
gallery?: Record<string, boolean>;
|
||||||
|
/** Leftover pick already queued for the rest destination. */
|
||||||
|
restSent?: boolean;
|
||||||
|
/** Leftover pick that is clearly only the away team, so it stays out of the rest destination. */
|
||||||
|
restSkip?: boolean;
|
||||||
|
/** `restSkip` was decided by the away-team rule. Older skips without this are looked at again. */
|
||||||
|
restAway?: boolean;
|
||||||
/**
|
/**
|
||||||
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
|
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
|
||||||
* near-duplicates left unflagged.
|
* near-duplicates left unflagged.
|
||||||
@@ -104,6 +125,9 @@ export class AutopilotService {
|
|||||||
},
|
},
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
/** Leftover picks are retried on a slow cadence: face names arrive after the window has closed. */
|
||||||
|
private restFlushAt = 0;
|
||||||
|
|
||||||
/** The upright preview, so a sequence can compare eyes. Null when it was never rendered. */
|
/** The upright preview, so a sequence can compare eyes. Null when it was never rendered. */
|
||||||
private previewFile(photo: { organizationId: string; sha256: string }): string | null {
|
private previewFile(photo: { organizationId: string; sha256: string }): string | null {
|
||||||
const file = this.deps.storage.resolve(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
|
const file = this.deps.storage.resolve(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
|
||||||
@@ -263,8 +287,8 @@ export class AutopilotService {
|
|||||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true, away: true, fixtureId: true, ingestFrom: true, ingestUntil: true } });
|
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true, away: true, fixtureId: true, ingestFrom: true, ingestUntil: true } });
|
||||||
if (!event) continue;
|
if (!event) continue;
|
||||||
const settings = AutopilotSettings.parse(event.autopilot ?? {});
|
const settings = AutopilotSettings.parse(event.autopilot ?? {});
|
||||||
const busy = await db.photo.count({ where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } } });
|
// A live match always has photos still being analysed. That must not hold the windows that already closed.
|
||||||
if (busy) continue;
|
const inflightAt = await inflightCaptureTimes(db, eventId);
|
||||||
const photos = await db.photo.findMany({
|
const photos = await db.photo.findMany({
|
||||||
where: { eventId, autopilotStatus: "DONE" },
|
where: { eventId, autopilotStatus: "DONE" },
|
||||||
select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true, sha256: true, facesStatus: true, iso: true },
|
select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true, sha256: true, facesStatus: true, iso: true },
|
||||||
@@ -295,8 +319,11 @@ export class AutopilotService {
|
|||||||
for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) {
|
for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) {
|
||||||
const burst = orderedBursts[burstIndex]!;
|
const burst = orderedBursts[burstIndex]!;
|
||||||
if (burst.every((f) => f.rec?.decided)) continue;
|
if (burst.every((f) => f.rec?.decided)) continue;
|
||||||
// Still arriving: wait until the burst has settled.
|
// Still arriving: wait until the burst has settled, and until a frame of the same moment finishes analysis.
|
||||||
if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue;
|
if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue;
|
||||||
|
const burstFrom = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
|
||||||
|
const burstTo = Math.max(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
|
||||||
|
if (burstStillArriving(burstFrom, burstTo, inflightAt, settings.burstGapSec * 1000)) continue;
|
||||||
const reportage = reportageEvent;
|
const reportage = reportageEvent;
|
||||||
const sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length;
|
const sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length;
|
||||||
const need = picksNeeded(settings);
|
const need = picksNeeded(settings);
|
||||||
@@ -315,7 +342,7 @@ export class AutopilotService {
|
|||||||
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
|
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
|
||||||
take = Math.min(asked, Math.max(0, cap));
|
take = Math.min(asked, Math.max(0, cap));
|
||||||
}
|
}
|
||||||
const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
|
const start = burstFrom;
|
||||||
const sameCamera = frames
|
const sameCamera = frames
|
||||||
.filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id))
|
.filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id))
|
||||||
.map((f) => ({
|
.map((f) => ({
|
||||||
@@ -475,6 +502,10 @@ export class AutopilotService {
|
|||||||
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
||||||
if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now);
|
if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now);
|
||||||
}
|
}
|
||||||
|
if (now.getTime() - this.restFlushAt >= 20_000) {
|
||||||
|
this.restFlushAt = now.getTime();
|
||||||
|
await this.flushHomeRest();
|
||||||
|
}
|
||||||
return picked;
|
return picked;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -505,6 +536,13 @@ export class AutopilotService {
|
|||||||
// With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target.
|
// With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target.
|
||||||
// Separate gallery sizes curate to the largest, and each smaller one keeps its own spread.
|
// Separate gallery sizes curate to the largest, and each smaller one keeps its own spread.
|
||||||
const candidates = candidatesOf(ranked, settings.burstGapSec * 1000, true, "best");
|
const candidates = candidatesOf(ranked, settings.burstGapSec * 1000, true, "best");
|
||||||
|
// A window that still has a frame in analysis stays open. The ones already complete can leave now.
|
||||||
|
const blockedWindows = windowsStillArriving(event.startsAt.getTime(), await inflightCaptureTimes(db, eventId));
|
||||||
|
const ready = candidates.filter((candidate) => {
|
||||||
|
const window = bestWindow(candidate.at, event.startsAt.getTime());
|
||||||
|
if (blockedWindows.has(window)) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
const curateOpts = {
|
const curateOpts = {
|
||||||
start: event.startsAt.getTime(),
|
start: event.startsAt.getTime(),
|
||||||
durationMs: matchMinutes(event.sport) * 60_000,
|
durationMs: matchMinutes(event.sport) * 60_000,
|
||||||
@@ -512,7 +550,7 @@ export class AutopilotService {
|
|||||||
minGapMs: MELHORES_GAP_MS,
|
minGapMs: MELHORES_GAP_MS,
|
||||||
sequenceCap: settings.picksPerBurst,
|
sequenceCap: settings.picksPerBurst,
|
||||||
};
|
};
|
||||||
const decisions = curate(candidates, decided, {
|
const decisions = curate(ready, decided, {
|
||||||
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
|
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
|
||||||
...curateOpts,
|
...curateOpts,
|
||||||
});
|
});
|
||||||
@@ -533,7 +571,7 @@ export class AutopilotService {
|
|||||||
const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId];
|
const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId];
|
||||||
return flag === undefined ? [] : [{ id: p.id, chosen: flag, at: p.capturedAt?.getTime() ?? 0 }];
|
return flag === undefined ? [] : [{ id: p.id, chosen: flag, at: p.capturedAt?.getTime() ?? 0 }];
|
||||||
});
|
});
|
||||||
const parts = curate(candidates, earlier, { count: g.count, ...curateOpts });
|
const parts = curate(ready, earlier, { count: g.count, ...curateOpts });
|
||||||
chosenBy.set(g.targetId, new Set(parts.flatMap((d) => d.chosen)));
|
chosenBy.set(g.targetId, new Set(parts.flatMap((d) => d.chosen)));
|
||||||
seenBy.set(g.targetId, new Set(parts.flatMap((d) => d.ids)));
|
seenBy.set(g.targetId, new Set(parts.flatMap((d) => d.ids)));
|
||||||
}
|
}
|
||||||
@@ -625,8 +663,284 @@ export class AutopilotService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (typeof settings.restHomeFromMin === "number" && settings.restTargetId && galleries.length) {
|
||||||
|
await this.sendGalleryRest(eventId, settings);
|
||||||
|
}
|
||||||
return chosenCount;
|
return chosenCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Events whose leftover picks have not been sent, including skips made before the away-team rule. */
|
||||||
|
private async flushHomeRest(): Promise<void> {
|
||||||
|
const { db, log } = this.deps;
|
||||||
|
const rows = await db.$queryRaw<{ event_id: string }[]>`
|
||||||
|
SELECT DISTINCT p.event_id
|
||||||
|
FROM photos p
|
||||||
|
JOIN events e ON e.id = p.event_id
|
||||||
|
WHERE p.flag = 'PICK'
|
||||||
|
AND p.autopilot_status = 'DONE'
|
||||||
|
AND p.created_at > now() - interval '2 days'
|
||||||
|
AND (p.autopilot->>'curated') = 'true'
|
||||||
|
AND (p.autopilot->>'restSent') IS DISTINCT FROM 'true'
|
||||||
|
AND (
|
||||||
|
(p.autopilot->>'restSkip') IS DISTINCT FROM 'true'
|
||||||
|
OR (p.autopilot->>'restAway') IS DISTINCT FROM 'true'
|
||||||
|
)
|
||||||
|
AND jsonb_typeof(e.autopilot->'restHomeFromMin') = 'number'
|
||||||
|
AND e.autopilot->>'restTargetId' IS NOT NULL
|
||||||
|
AND jsonb_typeof(e.autopilot->'galleries') = 'array'
|
||||||
|
AND jsonb_array_length(e.autopilot->'galleries') > 0
|
||||||
|
`;
|
||||||
|
for (const row of rows) {
|
||||||
|
const event = await db.event.findUnique({ where: { id: row.event_id }, select: { autopilot: true } });
|
||||||
|
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
||||||
|
await this.sendGalleryRest(row.event_id, settings).catch((err: unknown) => {
|
||||||
|
log.warn({ err, eventId: row.event_id }, "autopilot: leftover delivery not queued");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks that did not make a gallery. Until `restHomeFromMin` before kick-off they all go to the rest
|
||||||
|
* destination. From then on they still go, unless every identified person in the frame is the away team.
|
||||||
|
*/
|
||||||
|
private async sendGalleryRest(eventId: string, settings: AutopilotSettings): Promise<number> {
|
||||||
|
const leadMin = settings.restHomeFromMin;
|
||||||
|
const restTargetId = settings.restTargetId;
|
||||||
|
const galleries = settings.galleries ?? [];
|
||||||
|
if (typeof leadMin !== "number" || !restTargetId || !galleries.length) return 0;
|
||||||
|
if (!this.deps.deliveries) return 0;
|
||||||
|
const { db, log } = this.deps;
|
||||||
|
const event = await db.event.findUnique({
|
||||||
|
where: { id: eventId },
|
||||||
|
select: {
|
||||||
|
organizationId: true,
|
||||||
|
startsAt: true,
|
||||||
|
createdById: true,
|
||||||
|
ingestFrom: true,
|
||||||
|
ingestUntil: true,
|
||||||
|
home: true,
|
||||||
|
homeShort: true,
|
||||||
|
away: true,
|
||||||
|
awayShort: true,
|
||||||
|
homeTeamId: true,
|
||||||
|
awayTeamId: true,
|
||||||
|
fixture: { select: { season: true } },
|
||||||
|
homeTeam: { select: { name: true, abbreviation: true } },
|
||||||
|
awayTeam: { select: { name: true, abbreviation: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!event?.createdById) return 0;
|
||||||
|
const photos = await db.photo.findMany({
|
||||||
|
where: { eventId, flag: "PICK", autopilotStatus: "DONE" },
|
||||||
|
select: { id: true, capturedAt: true, createdAt: true, players: true, autopilot: true },
|
||||||
|
});
|
||||||
|
const cutoff = event.startsAt.getTime() - leadMin * 60_000;
|
||||||
|
const pending: typeof photos = [];
|
||||||
|
for (const photo of photos) {
|
||||||
|
const rec = photo.autopilot as AutopilotRecord | null;
|
||||||
|
if (!rec?.curated) continue;
|
||||||
|
if (rec.restSent) continue;
|
||||||
|
if (rec.restSkip && rec.restAway) continue;
|
||||||
|
if (rec.hold === "ball" || rec.chosen) continue;
|
||||||
|
if (!takenDuring(photo.capturedAt, event)) continue;
|
||||||
|
let inGallery = false;
|
||||||
|
for (const gallery of galleries) {
|
||||||
|
if (rec.gallery?.[gallery.targetId] === true) inGallery = true;
|
||||||
|
}
|
||||||
|
if (inGallery) continue;
|
||||||
|
pending.push(photo);
|
||||||
|
}
|
||||||
|
if (!pending.length) return 0;
|
||||||
|
|
||||||
|
const season = event.fixture?.season ?? null;
|
||||||
|
const homeNames = await squadNames(db, event.homeTeamId, season);
|
||||||
|
const awayNames = await squadNames(db, event.awayTeamId, season);
|
||||||
|
const homeClubs = labelSet([event.home, event.homeShort, event.homeTeam?.name, event.homeTeam?.abbreviation]);
|
||||||
|
const awayClubs = labelSet([event.away, event.awayShort, event.awayTeam?.name, event.awayTeam?.abbreviation]);
|
||||||
|
|
||||||
|
const faceIds: string[] = [];
|
||||||
|
for (const photo of pending) {
|
||||||
|
const at = photo.capturedAt?.getTime() ?? photo.createdAt.getTime();
|
||||||
|
if (at > cutoff) faceIds.push(photo.id);
|
||||||
|
}
|
||||||
|
const hints = new Map<string, FaceHint[]>();
|
||||||
|
if (faceIds.length) {
|
||||||
|
const faces = await db.face.findMany({
|
||||||
|
where: { photoId: { in: faceIds } },
|
||||||
|
select: {
|
||||||
|
photoId: true,
|
||||||
|
group: {
|
||||||
|
select: {
|
||||||
|
personId: true,
|
||||||
|
suggestedPersonId: true,
|
||||||
|
suggestionScore: true,
|
||||||
|
ignoredAt: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const personIds: string[] = [];
|
||||||
|
for (const face of faces) {
|
||||||
|
if (face.group?.personId) personIds.push(face.group.personId);
|
||||||
|
if (face.group?.suggestedPersonId) personIds.push(face.group.suggestedPersonId);
|
||||||
|
}
|
||||||
|
let people: { id: string; name: string; club: string | null; sportsPlayerId: string | null }[] = [];
|
||||||
|
if (personIds.length > 0) {
|
||||||
|
people = await db.person.findMany({
|
||||||
|
where: { id: { in: [...new Set(personIds)] } },
|
||||||
|
select: { id: true, name: true, club: true, sportsPlayerId: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const sportsIds: string[] = [];
|
||||||
|
for (const person of people) {
|
||||||
|
if (person.sportsPlayerId) sportsIds.push(person.sportsPlayerId);
|
||||||
|
}
|
||||||
|
let sports: { id: string; teamId: string }[] = [];
|
||||||
|
if (sportsIds.length > 0) {
|
||||||
|
sports = await db.sportsPlayer.findMany({
|
||||||
|
where: { id: { in: sportsIds } },
|
||||||
|
select: { id: true, teamId: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const teamOf = new Map(sports.map((player) => [player.id, player.teamId]));
|
||||||
|
const named = new Map<string, NamedPerson>();
|
||||||
|
for (const person of people) {
|
||||||
|
let teamId: string | null = null;
|
||||||
|
if (person.sportsPlayerId) {
|
||||||
|
const found = teamOf.get(person.sportsPlayerId);
|
||||||
|
if (found) teamId = found;
|
||||||
|
}
|
||||||
|
named.set(person.id, { name: person.name, club: person.club, teamId });
|
||||||
|
}
|
||||||
|
for (const face of faces) {
|
||||||
|
let group: {
|
||||||
|
personId: string | null;
|
||||||
|
suggestedPersonId: string | null;
|
||||||
|
suggestionScore: number | null;
|
||||||
|
ignored: boolean;
|
||||||
|
} | null = null;
|
||||||
|
if (face.group) {
|
||||||
|
group = {
|
||||||
|
personId: face.group.personId,
|
||||||
|
suggestedPersonId: face.group.suggestedPersonId,
|
||||||
|
suggestionScore: face.group.suggestionScore,
|
||||||
|
ignored: face.group.ignoredAt !== null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let person: NamedPerson | null = null;
|
||||||
|
if (face.group?.personId) {
|
||||||
|
person = named.get(face.group.personId) ?? null;
|
||||||
|
}
|
||||||
|
let suggested: NamedPerson | null = null;
|
||||||
|
if (face.group?.suggestedPersonId) {
|
||||||
|
suggested = named.get(face.group.suggestedPersonId) ?? null;
|
||||||
|
}
|
||||||
|
const hint = hintFromGroup(group, person, suggested);
|
||||||
|
if (!hint) continue;
|
||||||
|
const list = hints.get(face.photoId) ?? [];
|
||||||
|
list.push(hint);
|
||||||
|
hints.set(face.photoId, list);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const send: typeof photos = [];
|
||||||
|
for (const photo of pending) {
|
||||||
|
const at = photo.capturedAt?.getTime() ?? photo.createdAt.getTime();
|
||||||
|
const decision = homeRestDecision({
|
||||||
|
at,
|
||||||
|
start: event.startsAt.getTime(),
|
||||||
|
leadMin,
|
||||||
|
playerNames: photo.players,
|
||||||
|
faces: hints.get(photo.id) ?? [],
|
||||||
|
homeTeamId: event.homeTeamId,
|
||||||
|
homeNames,
|
||||||
|
homeClubs,
|
||||||
|
awayTeamId: event.awayTeamId,
|
||||||
|
awayNames,
|
||||||
|
awayClubs,
|
||||||
|
});
|
||||||
|
if (decision === "wait") continue;
|
||||||
|
if (decision === "skip") {
|
||||||
|
await this.markRest(photo, "restSkip");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
send.push(photo);
|
||||||
|
}
|
||||||
|
if (!send.length) return 0;
|
||||||
|
|
||||||
|
let queued = 0;
|
||||||
|
const chunk = 40;
|
||||||
|
for (let index = 0; index < send.length; index += chunk) {
|
||||||
|
const slice = send.slice(index, index + chunk);
|
||||||
|
const result = await this.deps.deliveries.enqueue({
|
||||||
|
organizationId: event.organizationId,
|
||||||
|
targetId: restTargetId,
|
||||||
|
photoIds: slice.map((photo) => photo.id),
|
||||||
|
again: false,
|
||||||
|
requestedById: event.createdById,
|
||||||
|
});
|
||||||
|
const done = new Set(result.queued.map((item) => item.photoId));
|
||||||
|
for (const skipped of result.skipped) {
|
||||||
|
if (skipped.reason === "already_delivered") done.add(skipped.photoId);
|
||||||
|
}
|
||||||
|
for (const photo of slice) {
|
||||||
|
if (!done.has(photo.id)) continue;
|
||||||
|
await this.markRest(photo, "restSent");
|
||||||
|
queued += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (queued) log.info({ eventId, queued, restTargetId }, "autopilot: leftover picks queued");
|
||||||
|
return queued;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async markRest(photo: { id: string; autopilot: unknown }, key: "restSent" | "restSkip"): Promise<void> {
|
||||||
|
const rec = photo.autopilot;
|
||||||
|
if (!rec || typeof rec !== "object" || Array.isArray(rec)) return;
|
||||||
|
let extra: { restSkip: true; restAway: true } | { restSent: true };
|
||||||
|
if (key === "restSkip") {
|
||||||
|
extra = { restSkip: true, restAway: true };
|
||||||
|
} else {
|
||||||
|
extra = { restSent: true };
|
||||||
|
}
|
||||||
|
await this.deps.db.photo.update({
|
||||||
|
where: { id: photo.id },
|
||||||
|
data: { autopilot: { ...rec, ...extra } as object },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function labelSet(labels: readonly (string | null | undefined)[]): Set<string> {
|
||||||
|
const names = new Set<string>();
|
||||||
|
for (const label of labels) {
|
||||||
|
const folded = foldName(label);
|
||||||
|
if (folded) names.add(folded);
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function squadNames(db: Db, teamId: string | null, season: string | null): Promise<Set<string>> {
|
||||||
|
const names = new Set<string>();
|
||||||
|
if (!teamId) return names;
|
||||||
|
let squad: { name: string; fullName: string | null }[] = [];
|
||||||
|
if (season) {
|
||||||
|
squad = await db.sportsPlayer.findMany({
|
||||||
|
where: { teamId, goneAt: null, season },
|
||||||
|
select: { name: true, fullName: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (squad.length === 0) {
|
||||||
|
squad = await db.sportsPlayer.findMany({
|
||||||
|
where: { teamId, goneAt: null },
|
||||||
|
select: { name: true, fullName: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const player of squad) {
|
||||||
|
const name = foldName(player.name);
|
||||||
|
const fullName = foldName(player.fullName);
|
||||||
|
if (name) names.add(name);
|
||||||
|
if (fullName) names.add(fullName);
|
||||||
|
}
|
||||||
|
return names;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
|
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
|
||||||
|
|||||||
@@ -151,7 +151,7 @@ function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra:
|
|||||||
matchNumber: "1",
|
matchNumber: "1",
|
||||||
startsAt,
|
startsAt,
|
||||||
},
|
},
|
||||||
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
|
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1, fileName: "IMG_0001.JPG" },
|
||||||
"Fotógrafo",
|
"Fotógrafo",
|
||||||
);
|
);
|
||||||
const fileSample = { ...built, ...extra };
|
const fileSample = { ...built, ...extra };
|
||||||
|
|||||||
@@ -288,7 +288,7 @@ export class DeliveryService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
return created;
|
return created;
|
||||||
});
|
}, { timeout: 30_000 });
|
||||||
queued.push(...items);
|
queued.push(...items);
|
||||||
}
|
}
|
||||||
for (const item of queued) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
|
for (const item of queued) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { DeliveryService } from "./service.js";
|
||||||
|
import type { Db } from "../db.js";
|
||||||
|
|
||||||
|
/** A minimal hand-rolled Db whose `$transaction` spy captures the options argument. */
|
||||||
|
function mockDb(captured: { options: unknown }): Pick<Db, "$transaction"> & Record<string, unknown> {
|
||||||
|
const tx = {
|
||||||
|
$executeRaw: (strings: TemplateStringsArray) => Promise.resolve(strings.length),
|
||||||
|
deliveryItem: {
|
||||||
|
aggregate: async () => ({ _max: { sequence: null } }),
|
||||||
|
create: async ({ data }: { data: Record<string, unknown> }) => ({
|
||||||
|
id: "item-1",
|
||||||
|
targetId: data.targetId,
|
||||||
|
photoId: data.photoId,
|
||||||
|
eventId: data.eventId,
|
||||||
|
sequence: data.sequence,
|
||||||
|
status: "QUEUED",
|
||||||
|
attempts: 0,
|
||||||
|
lastError: null,
|
||||||
|
remotePath: null,
|
||||||
|
byteSize: null,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
organizationId: data.organizationId,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
$transaction: async (fn: (tx: typeof tx) => Promise<unknown>, options?: unknown) => {
|
||||||
|
captured.options = options;
|
||||||
|
return fn(tx);
|
||||||
|
},
|
||||||
|
deliveryTarget: { findFirst: async () => ({ id: "t1", colorLabel: null, copyTargetId: null }) },
|
||||||
|
photo: { findMany: async () => [{ id: "p1", organizationId: "org", status: "READY", eventId: "ev1" }] },
|
||||||
|
deliveryItem: { findMany: async () => [] },
|
||||||
|
} as unknown as Pick<Db, "$transaction"> & Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("DeliveryService.enqueue transaction timeout (BIT-33904)", () => {
|
||||||
|
it("passes a 30 s execution timeout to $transaction so advisory-lock contention doesn't hit P2028", async () => {
|
||||||
|
const captured: { options: unknown } = { options: undefined };
|
||||||
|
const db = mockDb(captured) as unknown as Db;
|
||||||
|
const delivery = new DeliveryService({
|
||||||
|
db,
|
||||||
|
storage: {} as never,
|
||||||
|
secrets: undefined,
|
||||||
|
broadcaster: { library: () => {}, broadcast: () => {} } as never,
|
||||||
|
log: { info: () => {}, warn: () => {} } as never,
|
||||||
|
});
|
||||||
|
|
||||||
|
await delivery.enqueue({
|
||||||
|
organizationId: "org",
|
||||||
|
targetId: "t1",
|
||||||
|
photoIds: ["p1"],
|
||||||
|
again: false,
|
||||||
|
requestedById: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(captured.options).toEqual({ timeout: 30_000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { RenderWorker, type DevelopService } from "./service.js";
|
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";
|
import type { IngestLogger } from "../ingest/service.js";
|
||||||
|
|
||||||
describe("isPostgresAdminShutdown", () => {
|
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", () => {
|
describe("RenderWorker poll error handling", () => {
|
||||||
type Level = "info" | "warn";
|
type Level = "info" | "warn";
|
||||||
const makeLog = (): IngestLogger & { calls: { level: Level; msg: string }[] } => {
|
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);
|
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 () => {
|
it("still warns on a real poll failure", async () => {
|
||||||
const log = makeLog();
|
const log = makeLog();
|
||||||
const worker = new RenderWorker(makeService(new Error("relation photos does not exist")) as DevelopService, {
|
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 { Prisma, type PhotoEdit } from "../generated/prisma/client.js";
|
||||||
import type { IngestLogger } from "../ingest/service.js";
|
import type { IngestLogger } from "../ingest/service.js";
|
||||||
import { waitUntil } from "../lib/idle.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 { photoUrls } from "../library/serialize.js";
|
||||||
import type { Broadcaster } from "../realtime.js";
|
import type { Broadcaster } from "../realtime.js";
|
||||||
import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.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
|
// 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).
|
// 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");
|
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");
|
else this.opts.log.warn({ err }, "develop: poll failed");
|
||||||
} finally {
|
} finally {
|
||||||
this.ticking = false;
|
this.ticking = false;
|
||||||
|
|||||||
@@ -144,10 +144,13 @@ export class Pressure {
|
|||||||
* instance's worth of API connections during a deploy (`pm2 startOrReload` on the clustered `photoreport-api`
|
* instance's worth of API connections during a deploy (`pm2 startOrReload` on the clustered `photoreport-api`
|
||||||
* app brings a new instance online and confirms it before stopping an old one, so for a few seconds there are
|
* app brings a new instance online and confirms it before stopping an old one, so for a few seconds there are
|
||||||
* `apiInstances + 1` live, not just `apiInstances` — BIT-31550 was this exact overlap tipping the API's steady
|
* `apiInstances + 1` live, not just `apiInstances` — BIT-31550 was this exact overlap tipping the API's steady
|
||||||
* -state budget into Postgres' `superuser_reserved_connections`); Postgres' `superuser_reserved_connections`
|
* -state budget into Postgres' `superuser_reserved_connections`); one extra worker during a deploy
|
||||||
* itself (reserved below `max_connections`, never available to the app no matter how much headroom is left —
|
* (`pm2 startOrReload` on the fork-mode `photoreport-worker` starts the new process before the old one finishes
|
||||||
* this is what "reserved for roles with the SUPERUSER attribute" means); and extra headroom for ad hoc
|
* its 25 s drain, so both Prisma pools and both broadcasters are open at once — BIT-33530 was this overlap
|
||||||
* connections (migrations, scripts, psql, admin tools) that aren't sized here.
|
* exhausting all slots with "sorry, too many clients already", error 53300); Postgres'
|
||||||
|
* `superuser_reserved_connections` itself (reserved below `max_connections`, never available to the app no
|
||||||
|
* matter how much headroom is left — this is what "reserved for roles with the SUPERUSER attribute" means); and
|
||||||
|
* extra headroom for ad hoc connections (migrations, scripts, psql, admin tools) that aren't sized here.
|
||||||
*/
|
*/
|
||||||
export function dbConnectionBudget(
|
export function dbConnectionBudget(
|
||||||
wanted: number,
|
wanted: number,
|
||||||
@@ -157,6 +160,7 @@ export function dbConnectionBudget(
|
|||||||
apiPoolSize = 10,
|
apiPoolSize = 10,
|
||||||
realtimePerInstance = 3,
|
realtimePerInstance = 3,
|
||||||
apiReloadOverlap = 1,
|
apiReloadOverlap = 1,
|
||||||
|
workerReloadOverlap = 1,
|
||||||
superuserReserved = 3,
|
superuserReserved = 3,
|
||||||
headroom = 10,
|
headroom = 10,
|
||||||
}: {
|
}: {
|
||||||
@@ -165,10 +169,15 @@ export function dbConnectionBudget(
|
|||||||
apiPoolSize?: number;
|
apiPoolSize?: number;
|
||||||
realtimePerInstance?: number;
|
realtimePerInstance?: number;
|
||||||
apiReloadOverlap?: number;
|
apiReloadOverlap?: number;
|
||||||
|
workerReloadOverlap?: number;
|
||||||
superuserReserved?: number;
|
superuserReserved?: number;
|
||||||
headroom?: number;
|
headroom?: number;
|
||||||
} = {},
|
} = {},
|
||||||
): number {
|
): number {
|
||||||
const available = max - superuserReserved - (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance) - 1 - headroom;
|
const apiConnections = (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance);
|
||||||
|
// Room for (1 + workerReloadOverlap) workers, each with `available` Prisma connections + 1 broadcaster.
|
||||||
|
// Solving (1 + workerReloadOverlap) * (available + 1) <= max - superuserReserved - apiConnections - headroom
|
||||||
|
// gives available <= floor((max - superuserReserved - apiConnections - headroom) / (1 + workerReloadOverlap)) - 1.
|
||||||
|
const available = Math.floor((max - superuserReserved - apiConnections - headroom) / (1 + workerReloadOverlap)) - 1;
|
||||||
return Math.max(1, Math.min(wanted, available));
|
return Math.max(1, Math.min(wanted, available));
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
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 {
|
class PrismaLike extends Error {
|
||||||
constructor(readonly code: string, message: string) {
|
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", () => {
|
describe("isPrismaTransactionTimeout", () => {
|
||||||
it("matches a PrismaClientKnownRequestError with code P2028 (BIT-32083)", () => {
|
it("matches a PrismaClientKnownRequestError with code P2028 (BIT-32083)", () => {
|
||||||
const err = new PrismaLike(
|
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", () => {
|
describe("retryOnConnectionClosed", () => {
|
||||||
it("retries once when the first attempt throws P1017 and returns the second result", async () => {
|
it("retries once when the first attempt throws P1017 and returns the second result", async () => {
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
|
|||||||
@@ -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`
|
* 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.").
|
* (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);
|
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
|
* 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
|
* fresh client on the next attempt, so a single retry clears the blip without surfacing it to the caller's
|
||||||
|
|||||||
@@ -10,19 +10,24 @@ import { createHash } from "node:crypto";
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transient PostgreSQL connection errors during a restart, graceful shutdown, or network blip. Prisma surfaces
|
* Transient PostgreSQL connection errors during a restart, graceful shutdown, network blip, or pool
|
||||||
* these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE (57P01/57P03) or its own P1001/P1017.
|
* exhaustion. Prisma surfaces these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE
|
||||||
* The pool reconnects on the next attempt, so these are not code bugs — reporting them only trips the Error
|
* (57P01/57P03/53300) or its own P1001/P1017, and pool exhaustion (SQLSTATE 53300) as P2037 with the
|
||||||
* Loop with one-off incidents from every code path that touches the database during the brief outage.
|
* message "Too many database connections opened: sorry, too many clients already" — no SQLSTATE in the
|
||||||
* Individual call sites that need to stop a batch or retry still check `isPostgresAdminShutdown` /
|
* text, so the code check is what catches it. The realtime LISTEN/NOTIFY path uses `pg` directly and
|
||||||
* `isPrismaServerUnreachable` (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the
|
* surfaces raw Node TCP errors (ECONNREFUSED) when Postgres is not listening at all. The pool reconnects
|
||||||
* error propagate to a generic log.error (BIT-32490 and 11 sibling clusters).
|
* 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-33537 for P2037,
|
||||||
|
* BIT-33524 for ECONNREFUSED).
|
||||||
*/
|
*/
|
||||||
function isTransientDatabaseError(err: unknown): boolean {
|
function isTransientDatabaseError(err: unknown): boolean {
|
||||||
if (!(err instanceof Error)) return false;
|
if (!(err instanceof Error)) return false;
|
||||||
const code = (err as { code?: unknown }).code;
|
const code = (err as { code?: unknown }).code;
|
||||||
if (code === "P1001" || code === "P1017") return true;
|
if (code === "P1001" || code === "P1017" || code === "P2037" || code === "ECONNREFUSED") return true;
|
||||||
return /57P01|57P03|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection/i.test(err.message);
|
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";
|
export type ReportLevel = "critical" | "error" | "warning" | "info";
|
||||||
|
|
||||||
|
|||||||
@@ -16,14 +16,24 @@ import { claimInbox } from "./adopt.js";
|
|||||||
|
|
||||||
const HOUR = 3600_000;
|
const HOUR = 3600_000;
|
||||||
|
|
||||||
/** An older app does not send `galleries`. Keep the sizes already stored instead of clearing them. */
|
/**
|
||||||
|
* An older app does not send `galleries` or `restHomeFromMin`. Keep what is already stored instead of clearing it.
|
||||||
|
*/
|
||||||
function keptGalleries(next: AutopilotSettings | null, current: Prisma.JsonValue): AutopilotSettings | typeof Prisma.DbNull {
|
function keptGalleries(next: AutopilotSettings | null, current: Prisma.JsonValue): AutopilotSettings | typeof Prisma.DbNull {
|
||||||
if (!next) return Prisma.DbNull;
|
if (!next) return Prisma.DbNull;
|
||||||
if (next.galleries !== undefined) return next;
|
|
||||||
if (!current || typeof current !== "object" || Array.isArray(current)) return next;
|
if (!current || typeof current !== "object" || Array.isArray(current)) return next;
|
||||||
const kept = (current as { galleries?: AutopilotSettings["galleries"] }).galleries;
|
const prev = current as {
|
||||||
if (!Array.isArray(kept) || kept.length === 0) return next;
|
galleries?: AutopilotSettings["galleries"];
|
||||||
return { ...next, galleries: kept };
|
restHomeFromMin?: number | null;
|
||||||
|
};
|
||||||
|
let out = next;
|
||||||
|
if (next.galleries === undefined && Array.isArray(prev.galleries) && prev.galleries.length > 0) {
|
||||||
|
out = { ...out, galleries: prev.galleries };
|
||||||
|
}
|
||||||
|
if (next.restHomeFromMin === undefined && typeof prev.restHomeFromMin === "number") {
|
||||||
|
out = { ...out, restHomeFromMin: prev.restHomeFromMin };
|
||||||
|
}
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
const OrgParams = z.object({ orgId: z.uuid() });
|
const OrgParams = z.object({ orgId: z.uuid() });
|
||||||
const EventParams = z.object({ eventId: z.uuid() });
|
const EventParams = z.object({ eventId: z.uuid() });
|
||||||
|
|||||||
@@ -42,6 +42,12 @@ const p1017 = () =>
|
|||||||
const p1017findUnique = () =>
|
const p1017findUnique = () =>
|
||||||
Object.assign(new Error("Invalid `prisma.person.findUnique()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
|
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) => ({
|
const ligaTeam = (id: string, externalId: string) => ({
|
||||||
id,
|
id,
|
||||||
provider: "LIGA",
|
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)", () => {
|
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 () => {
|
it("logs at info and returns 0 when the raw query is terminated mid-flight (57P01)", async () => {
|
||||||
const db = {
|
const db = {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js";
|
|||||||
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
|
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
|
||||||
import { badRequest, notFound } from "../lib/errors.js";
|
import { badRequest, notFound } from "../lib/errors.js";
|
||||||
import { waitUntil } from "../lib/idle.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 { LocalStorage, UrlSigner } from "../storage/storage.js";
|
||||||
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
|
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
|
||||||
import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.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");
|
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, database connection closed");
|
||||||
return { created: 0, updated: 0, headshots: 0 };
|
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;
|
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");
|
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, database unreachable");
|
||||||
return result;
|
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.
|
// Same not-yet-published 400 as importLigaSquads/backfillLigaRegister: expected, kept out of the error hub.
|
||||||
if (err instanceof ProviderHttpError && err.status === 400)
|
if (err instanceof ProviderHttpError && err.status === 400)
|
||||||
log.info({ err, team: team.id }, "sports: liga squad not published yet for this team");
|
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)");
|
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction rolled back (connection blip or deadlock)");
|
||||||
} else if (isPrismaTransactionTimeout(err)) {
|
} else if (isPrismaTransactionTimeout(err)) {
|
||||||
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction start timed out (pool contention)");
|
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 {
|
} else {
|
||||||
this.opts.log.warn({ err }, "sports: tick failed");
|
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();
|
if (!this.stopped && saved >= 0 && this.opts.afterRegister) await this.opts.afterRegister();
|
||||||
} catch (err) {
|
} 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 {
|
} finally {
|
||||||
this.filling = false;
|
this.filling = false;
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-2
@@ -17,6 +17,7 @@ import { DevelopService, RenderWorker } from "./develop/service.js";
|
|||||||
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
|
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
|
||||||
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
||||||
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
|
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
|
||||||
|
import { isPrismaTooManyConnections } from "./lib/pg.js";
|
||||||
import { jogaClientFromConfig } from "./sports/joga.js";
|
import { jogaClientFromConfig } from "./sports/joga.js";
|
||||||
import { SportsService, SportsWorker } from "./sports/service.js";
|
import { SportsService, SportsWorker } from "./sports/service.js";
|
||||||
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
|
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
|
||||||
@@ -176,8 +177,15 @@ const sports = config.SPORTS_SYNC === "on"
|
|||||||
})
|
})
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
ensureCloudM19Target(db).catch((err) => log.warn({ err }, "delivery: Cloud M19 profile not created"));
|
// Pool exhaustion (P2037) during a deploy overlap is transient: the next worker restart retries these
|
||||||
ensureCloudW17Target(db).catch((err) => log.warn({ err }, "delivery: Cloud W17 profile not created"));
|
// 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();
|
scanner.start();
|
||||||
if (secrets) archive.start();
|
if (secrets) archive.start();
|
||||||
autopilot.start();
|
autopilot.start();
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { buildApp } from "../src/app.js";
|
||||||
|
import { loadConfig } from "../src/config.js";
|
||||||
|
import { createDb } from "../src/db.js";
|
||||||
import { bearer, createTestApp, login, PASSWORD, resetDb, seedUser, type TestContext } from "./helpers.js";
|
import { bearer, createTestApp, login, PASSWORD, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||||
|
|
||||||
let ctx: TestContext;
|
let ctx: TestContext;
|
||||||
@@ -16,6 +19,24 @@ describe("health", () => {
|
|||||||
const res = await ctx.app.inject({ method: "GET", url: "/health" });
|
const res = await ctx.app.inject({ method: "GET", url: "/health" });
|
||||||
expect(res.json()).toEqual({ status: "ok", version: "dev" });
|
expect(res.json()).toEqual({ status: "ok", version: "dev" });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("returns 503 degraded when the database is unreachable", async () => {
|
||||||
|
const config = loadConfig({
|
||||||
|
NODE_ENV: "test",
|
||||||
|
DATABASE_URL: "postgresql://[email protected]:1/photoreport_test",
|
||||||
|
JWT_SECRET: "test-secret-test-secret-test-secret-123",
|
||||||
|
});
|
||||||
|
const db = createDb(config.DATABASE_URL);
|
||||||
|
const app = await buildApp({ config, db });
|
||||||
|
try {
|
||||||
|
const res = await app.inject({ method: "GET", url: "/health" });
|
||||||
|
expect(res.statusCode).toBe(503);
|
||||||
|
expect(res.json()).toEqual({ status: "degraded", version: "dev" });
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
await db.$disconnect();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("login", () => {
|
describe("login", () => {
|
||||||
|
|||||||
@@ -40,22 +40,40 @@ describe("capacity", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("dbConnectionBudget", () => {
|
describe("dbConnectionBudget", () => {
|
||||||
it("stays under what the API's cluster, a deploy's reload overlap, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
|
it("stays under what the API's cluster, a deploy's reload overlaps, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
|
||||||
// 100 - 3 superuser reserved - ((2 api instances + 1 reload overlap) * (10 pool + 3 realtime)) - 1 broadcaster - 10 headroom = 47.
|
// 100 - 3 superuser reserved - ((2 api + 1 reload) * (10 pool + 3 realtime)) - 10 headroom = 48.
|
||||||
expect(dbConnectionBudget(500)).toBe(47);
|
// Divide by (1 + 1 worker overlap) = 24, minus 1 broadcaster = 23.
|
||||||
|
expect(dbConnectionBudget(500)).toBe(23);
|
||||||
expect(dbConnectionBudget(10)).toBe(10);
|
expect(dbConnectionBudget(10)).toBe(10);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("follows a differently sized API cluster or Postgres limit", () => {
|
it("follows a differently sized API cluster or Postgres limit", () => {
|
||||||
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(96);
|
// 200 - 3 - ((4 + 1) * (15 + 3)) - 10 = 200 - 3 - 90 - 10 = 97; floor(97 / 2) - 1 = 47.
|
||||||
|
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(47);
|
||||||
|
// 40 - 3 - ((2 + 1) * (10 + 3)) - 10 = 40 - 3 - 39 - 10 = -12; floor(-12 / 2) - 1 = -7; clamped to 1.
|
||||||
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
|
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("can be told a deploy never overlaps instances (e.g. a non-cluster or single-instance API)", () => {
|
it("can be told a deploy never overlaps API instances (e.g. a non-cluster or single-instance API)", () => {
|
||||||
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(60);
|
// 100 - 3 - (2 * 13) - 10 = 61; floor(61 / 2) - 1 = 29.
|
||||||
|
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(29);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("can be told the worker never overlaps during a deploy", () => {
|
||||||
|
// 100 - 3 - (3 * 13) - 10 = 48; floor(48 / 1) - 1 = 47 (the old steady-state budget, BIT-31550 era).
|
||||||
|
expect(dbConnectionBudget(500, { workerReloadOverlap: 0 })).toBe(47);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("never goes below 1, even if the API and headroom already exceed max_connections", () => {
|
it("never goes below 1, even if the API and headroom already exceed max_connections", () => {
|
||||||
expect(dbConnectionBudget(50, { max: 20, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
|
expect(dbConnectionBudget(50, { max: 20, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the total at or below max_connections during a worker deploy overlap", () => {
|
||||||
|
const max = 100;
|
||||||
|
const budget = dbConnectionBudget(500, { max });
|
||||||
|
// Two workers (old draining + new), each with `budget` Prisma + 1 broadcaster, plus API at deploy overlap.
|
||||||
|
const apiConnections = 3 * (10 + 3);
|
||||||
|
const total = apiConnections + 2 * (budget + 1) + 3 + 10;
|
||||||
|
expect(total).toBeLessThanOrEqual(max);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -91,7 +91,7 @@ describe("errors to errors.bitreport.pt", () => {
|
|||||||
expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" });
|
expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not report transient PostgreSQL shutdown/restart errors (57P01/57P03/P1001/P1017)", async () => {
|
it("does not report transient PostgreSQL shutdown/restart/unreachable errors (57P01/57P03/53300/P1001/P1017/P2037/ECONNREFUSED)", async () => {
|
||||||
const hub = fakeHub();
|
const hub = fakeHub();
|
||||||
const reporter = reporterWith(hub.fetchImpl);
|
const reporter = reporterWith(hub.fetchImpl);
|
||||||
const sink = new Writable({ write: (_c, _e, cb) => cb() });
|
const sink = new Writable({ write: (_c, _e, cb) => cb() });
|
||||||
@@ -105,7 +105,12 @@ describe("errors to errors.bitreport.pt", () => {
|
|||||||
log.error({ err: mk("Database error. Code: 57P01. Message: terminating connection due to administrator command") }, "archive: query failed");
|
log.error({ err: mk("Database error. Code: 57P01. Message: terminating connection due to administrator command") }, "archive: query failed");
|
||||||
log.error({ err: mk("Can't reach database server at localhost:5432", "P1001") }, "db unreachable");
|
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("Server has closed the connection.", "P1017") }, "connection closed");
|
||||||
reporter.reportError(mk("Database error. Code: 57P03. Message: the database system is shutting down"), "worker");
|
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");
|
||||||
|
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");
|
log.error({ err: new Error("render crashed") }, "real error");
|
||||||
await reporter.flush();
|
await reporter.flush();
|
||||||
const events = hub.sent.flatMap((s) => s.events);
|
const events = hub.sent.flatMap((s) => s.events);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
|
|||||||
/** Pure tests. The default config migrates a database, which these do not need. */
|
/** Pure tests. The default config migrates a database, which these do not need. */
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
test: {
|
test: {
|
||||||
include: ["src/**/*.test.ts", "test/compose.test.ts"],
|
include: ["src/**/*.test.ts", "test/capacity.test.ts", "test/compose.test.ts"],
|
||||||
fileParallelism: false,
|
fileParallelism: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
|||||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const info = await load(id);
|
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) {
|
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). */
|
/** 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 }) {
|
export async function ArchiveFrame({ id, start }: { id: string; start?: View }) {
|
||||||
const info = await load(id);
|
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.
|
// 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";
|
const atRoot = (await headers()).get("x-arquivo-root") === "1";
|
||||||
return <ArchiveView info={{ ...info, base: atRoot ? "" : `/arquivo/${info.id}` }} start={start} />;
|
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> {
|
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const info = await load(id);
|
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) {
|
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;
|
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();
|
if (!/^[0-9a-f-]{36}$/i.test(id)) notFound();
|
||||||
const res = await fetch(`${API}/v1/archive/${id}`, { cache: "no-store" });
|
const res = await fetch(`${API}/v1/archive/${id}`, { cache: "no-store" });
|
||||||
if (res.status === 404 || res.status === 400) notFound();
|
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;
|
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> {
|
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const info = await load(id);
|
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) {
|
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> {
|
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||||
const info = await load((await params).id);
|
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 } };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,7 +40,21 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
|||||||
try {
|
try {
|
||||||
site = await getSite();
|
site = await getSite();
|
||||||
} catch (err) {
|
} 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
|
// The events domain (events.photoreport.pt) has no storefront: its event pages (QR page, kiosk) and the
|
||||||
// archive's sign-in pages stand alone.
|
// archive's sign-in pages stand alone.
|
||||||
if (path.startsWith("/e/") || path.startsWith("/arquivo/")) {
|
if (path.startsWith("/e/") || path.startsWith("/arquivo/")) {
|
||||||
|
|||||||
@@ -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,22 +1,13 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
|
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
|
||||||
import { eventTitle, longDate } from "../lib/format";
|
import { eventTitle, longDate } from "../lib/format";
|
||||||
|
import { load } from "./home-data";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
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 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);
|
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. */
|
/** Home: search, sport shortcuts, the photos that just arrived, then the galleries. */
|
||||||
export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string; desporto?: string }> }) {
|
export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string; desporto?: string }> }) {
|
||||||
const params = await searchParams;
|
const params = await searchParams;
|
||||||
|
|||||||
+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
|
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.
|
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):
|
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
|
- `pnpm install --frozen-lockfile` / `cargo build --release -p <crate>` as needed
|
||||||
- build only the affected package (`pnpm --filter <pkg> build`)
|
- build only the affected package (`pnpm --filter <pkg> build`)
|
||||||
- API only: `prisma migrate deploy`
|
- 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
|
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)"
|
PREVIOUS="$(git rev-parse HEAD)"
|
||||||
log "deploying $SERVICE: $PREVIOUS -> $SHA"
|
log "deploying $SERVICE: $PREVIOUS -> $SHA"
|
||||||
backup_env
|
backup_env
|
||||||
|
|||||||
@@ -104,6 +104,12 @@ export const AutopilotSettings = z.object({
|
|||||||
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.
|
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.
|
||||||
*/
|
*/
|
||||||
restTargetId: z.string().uuid().nullable().default(null),
|
restTargetId: z.string().uuid().nullable().default(null),
|
||||||
|
/**
|
||||||
|
* With galleries and `restTargetId`: leftover picks go to the rest destination until this many minutes
|
||||||
|
* before kick-off. After that they still go, unless the frame is clearly only the away team. Omitted:
|
||||||
|
* galleries do not send leftovers (an older app leaves this out; the stored value is kept).
|
||||||
|
*/
|
||||||
|
restHomeFromMin: z.number().int().min(0).max(180).nullable().optional(),
|
||||||
});
|
});
|
||||||
export type AutopilotSettings = z.infer<typeof AutopilotSettings>;
|
export type AutopilotSettings = z.infer<typeof AutopilotSettings>;
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user