Compare commits
51
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 | ||
|
|
c8949c690d | ||
|
|
690b35389d | ||
|
|
cb2b887a48 | ||
|
|
413983a057 | ||
|
|
30b30ef122 | ||
|
|
2fad6e96c3 | ||
|
|
ae6e467103 | ||
|
|
360dc5efb8 | ||
|
|
92cecc7214 | ||
|
|
0a845f8bc6 | ||
|
|
a9b7007d5d | ||
|
|
56c115933c | ||
|
|
63b021cec8 | ||
|
|
28f08bc5bc | ||
|
|
7f44cba460 | ||
|
|
fcaa795b1d | ||
|
|
6077a1062a | ||
|
|
e6b5f2e390 | ||
|
|
2a612a6f9a | ||
|
|
af63ea5673 |
No files matched your search
@@ -1,8 +1,9 @@
|
||||
name: desktop-release
|
||||
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
|
||||
# Linux builds on the standard runner. macOS (.dmg) builds on a Mac registered as a runner with the label "macos"
|
||||
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) needs a
|
||||
# runner labelled "windows": register one, then uncomment its entry.
|
||||
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) builds
|
||||
# on a runner labelled "windows" (Git bash, plus the WebView2 step). No Windows runner is registered yet, so a
|
||||
# tag waits on that job until one is online. Notarisation runs only when the Apple secrets below are set.
|
||||
#
|
||||
# Self-updates (apps/desktop/src-tauri/src/updater.rs): with the secret TAURI_SIGNING_PRIVATE_KEY (and
|
||||
# TAURI_SIGNING_PRIVATE_KEY_PASSWORD) and the variable TAURI_UPDATER_PUBKEY set (`tauri signer generate`), each job
|
||||
@@ -14,6 +15,10 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
defaults:
|
||||
run:
|
||||
# Windows runners default to PowerShell. Git bash is what the rest of this job is written for.
|
||||
shell: bash
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -25,9 +30,10 @@ jobs:
|
||||
bundles: dmg,app
|
||||
platform: darwin-universal
|
||||
args: --target universal-apple-darwin
|
||||
# - runner: windows
|
||||
# bundles: msi
|
||||
# platform: windows-x86_64
|
||||
- runner: windows
|
||||
bundles: msi
|
||||
platform: windows-x86_64
|
||||
args: ""
|
||||
runs-on: ${{ matrix.runner }}
|
||||
env:
|
||||
VITE_API_URL: https://api.next.photoreport.pt
|
||||
@@ -35,13 +41,23 @@ jobs:
|
||||
PHOTOREPORT_UPDATER_PUBKEY: ${{ vars.TAURI_UPDATER_PUBKEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
# Empty until a Developer ID and an app-specific password (or an App Store Connect API key) are stored.
|
||||
# Tauri notarises only when a full set is present; the install step drops blank values so a missing
|
||||
# secret does not turn into a failed notarisation.
|
||||
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_PATH: ${{ secrets.APPLE_API_KEY_PATH }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: System libraries (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev libgphoto2-dev pkg-config
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -68,6 +84,10 @@ jobs:
|
||||
sleep 15
|
||||
done
|
||||
test "$ok" = 1
|
||||
- name: WebView2 runtime (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File infra/desktop/windows-webview2.ps1
|
||||
- name: Both Mac processors (universal app)
|
||||
if: runner.os == 'macOS'
|
||||
run: rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
@@ -82,11 +102,32 @@ jobs:
|
||||
- name: Installers
|
||||
shell: bash
|
||||
run: |
|
||||
# Blank Apple secrets must not look "set", or Tauri tries to notarise with an empty account.
|
||||
for name in APPLE_SIGNING_IDENTITY APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_PATH; do
|
||||
if [[ -z "${!name:-}" ]]; then
|
||||
unset "$name"
|
||||
fi
|
||||
done
|
||||
extra=()
|
||||
# Signed updater artifacts only when the release key is there (a build without it still works).
|
||||
# The bundler checks each signature against plugins.updater.pubkey, so the public key goes into the config too.
|
||||
if [[ -n "$TAURI_SIGNING_PRIVATE_KEY" ]]; then
|
||||
extra=(--config "$(node -e 'console.log(JSON.stringify({bundle:{createUpdaterArtifacts:true},plugins:{updater:{pubkey:process.env.PHOTOREPORT_UPDATER_PUBKEY}}}))')")
|
||||
# Updater artifacts when the release key is there. A Developer ID also turns on the hardened
|
||||
# runtime with the entitlements the bundled ONNX library needs, which is what notarisation requires.
|
||||
config="$(node -e '
|
||||
const bundle = {};
|
||||
const plugins = {};
|
||||
if (process.env.TAURI_SIGNING_PRIVATE_KEY) {
|
||||
bundle.createUpdaterArtifacts = true;
|
||||
plugins.updater = { pubkey: process.env.PHOTOREPORT_UPDATER_PUBKEY };
|
||||
}
|
||||
if (process.platform === "darwin" && process.env.APPLE_SIGNING_IDENTITY) {
|
||||
bundle.macOS = { hardenedRuntime: true, entitlements: "entitlements.plist" };
|
||||
}
|
||||
const cfg = {};
|
||||
if (Object.keys(bundle).length) cfg.bundle = bundle;
|
||||
if (Object.keys(plugins).length) cfg.plugins = plugins;
|
||||
if (Object.keys(cfg).length) process.stdout.write(JSON.stringify(cfg));
|
||||
')"
|
||||
if [[ -n "$config" ]]; then
|
||||
extra=(--config "$config")
|
||||
fi
|
||||
pnpm --filter @photoreport/desktop exec tauri build --bundles ${{ matrix.bundles }} ${{ matrix.args }} "${extra[@]}"
|
||||
- name: Update manifest
|
||||
|
||||
+8
-3
@@ -142,9 +142,14 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
||||
|
||||
registerClientErrors(app, reporter);
|
||||
|
||||
app.get("/health", async () => {
|
||||
await db.$queryRaw`SELECT 1`;
|
||||
return { status: "ok", version: config.APP_VERSION };
|
||||
app.get("/health", async (_req, reply) => {
|
||||
try {
|
||||
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);
|
||||
|
||||
@@ -125,6 +125,24 @@ describe("rematch stops and downgrades a P1001 unreachable database (BIT-32462)"
|
||||
expect(log.calls.some((c) => c.level === "warn" && /gallery not checked/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("logs at info and stops the batch when Postgres is at max_connections (P2037, BIT-33550)", async () => {
|
||||
const log = makeLog();
|
||||
const calls: string[] = [];
|
||||
const db = makeDb(async () => {
|
||||
calls.push("findUnique");
|
||||
throw Object.assign(
|
||||
new Error("Invalid `prisma.sportsFixture.findMany()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"),
|
||||
{ code: "P2037" },
|
||||
);
|
||||
});
|
||||
const service = new ArchiveService({ db, log } as never);
|
||||
const moved = await (service as unknown as { rematch: (sourceId: string) => Promise<number> }).rematch("src-1");
|
||||
expect(calls).toEqual(["findUnique"]);
|
||||
expect(moved).toBe(0);
|
||||
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn" && /gallery not checked/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("still warns on a real per-folder error", async () => {
|
||||
const log = makeLog();
|
||||
const db = makeDb(async () => {
|
||||
@@ -205,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 === "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 { ingestWindow } from "../library/events.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { isPostgresAdminShutdown, isPrismaServerUnreachable } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPrismaServerUnreachable, isPrismaTooManyConnections } from "../lib/pg.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
|
||||
import {
|
||||
@@ -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 } });
|
||||
return;
|
||||
}
|
||||
let folder = known
|
||||
? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } })
|
||||
: await db.cloudFolder.create({
|
||||
data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) },
|
||||
});
|
||||
let folder: CloudFolder;
|
||||
if (known) {
|
||||
folder = await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } });
|
||||
} 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 images = children.filter((c) => !c.isDir && IMAGE.test(c.name));
|
||||
@@ -387,7 +395,16 @@ export class ArchiveService {
|
||||
for (const img of images) {
|
||||
const f = byId.get(img.fileId);
|
||||
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++;
|
||||
} 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 } });
|
||||
@@ -405,7 +422,16 @@ export class ArchiveService {
|
||||
const v = videoById.get(vid.fileId);
|
||||
const size = vid.size === null ? null : BigInt(vid.size);
|
||||
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++;
|
||||
} 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 } });
|
||||
@@ -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");
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
break;
|
||||
}
|
||||
// The Postgres server is at max_connections and only SUPERUSER slots remain (P2037): every remaining folder
|
||||
// would fail the same way, so stop this source's batch and let the next verifyAll retry once a slot frees —
|
||||
// logging a warn per folder pages the error loop for a transient blip (BIT-33550).
|
||||
if (isPrismaTooManyConnections(err)) {
|
||||
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: gallery check stopped, too many database connections");
|
||||
break;
|
||||
}
|
||||
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery not checked");
|
||||
report?.errors.push({ path: folder.path, error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
@@ -1425,7 +1465,11 @@ export class ArchiveService {
|
||||
const games = new Map<string, { id: string; home: string; away: string }>();
|
||||
for (const folder of folders) if (folder.event) games.set(folder.event.id, folder.event);
|
||||
const rows = teamSideRows(games.values(), teamMatcher(teams), new Map(aliases.map((alias) => [alias.aliasKey, alias.name])));
|
||||
let stored = rows.length;
|
||||
await db.$transaction(async (tx) => {
|
||||
// Two workers can pick the same due source (BIT-33539): the second skips instead of colliding on the PK.
|
||||
const [locked] = await tx.$queryRaw<{ ok: boolean }[]>`SELECT pg_try_advisory_xact_lock(hashtext(${sourceId})::bigint) AS ok`;
|
||||
if (!locked?.ok) { stored = 0; return; }
|
||||
await tx.archiveTeamSide.deleteMany({ where: { sourceId } });
|
||||
const chunk = 2000;
|
||||
for (let i = 0; i < rows.length; i += chunk) {
|
||||
@@ -1438,7 +1482,7 @@ export class ArchiveService {
|
||||
data: { directoryBuiltAt: new Date(), directoryDirtyAt: null },
|
||||
});
|
||||
}, { timeout: 60_000, maxWait: 60_000 });
|
||||
return rows.length;
|
||||
return stored;
|
||||
}
|
||||
|
||||
/** One archive whose teams were never stored, or have changed. */
|
||||
|
||||
@@ -82,6 +82,41 @@ const median = (xs: number[]) => {
|
||||
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,
|
||||
* 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.
|
||||
*/
|
||||
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 sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS;
|
||||
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>();
|
||||
for (const x of scored) {
|
||||
if (done.has(x.c.id)) continue;
|
||||
// Warm-up and line-ups (more than 5 minutes 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));
|
||||
// Warm-up and line-ups (more than one window before kick-off) are not game moments.
|
||||
const w = bestWindow(x.c.at, opts.start, windowMs);
|
||||
byWindow.set(w, [...(byWindow.get(w) ?? []), x]);
|
||||
}
|
||||
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,10 +26,11 @@ import {
|
||||
sequenceIndex,
|
||||
sequenceSendRoom,
|
||||
} 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 { detailForCrop, lookValues } from "./look.js";
|
||||
import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type GalleryExport } from "./targets.js";
|
||||
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
|
||||
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** A burst is decided once no new frame of it has arrived for this long. */
|
||||
@@ -46,6 +47,20 @@ function takenHere(ids: readonly string[], when: ReadonlyMap<string, Date | null
|
||||
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 {
|
||||
score: number;
|
||||
reason: string | null;
|
||||
@@ -78,6 +93,12 @@ export interface AutopilotRecord {
|
||||
hold?: "ball";
|
||||
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
|
||||
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
|
||||
* 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. */
|
||||
private previewFile(photo: { organizationId: string; sha256: string }): string | null {
|
||||
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 } });
|
||||
if (!event) continue;
|
||||
const settings = AutopilotSettings.parse(event.autopilot ?? {});
|
||||
const busy = await db.photo.count({ where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } } });
|
||||
if (busy) continue;
|
||||
// A live match always has photos still being analysed. That must not hold the windows that already closed.
|
||||
const inflightAt = await inflightCaptureTimes(db, eventId);
|
||||
const photos = await db.photo.findMany({
|
||||
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 },
|
||||
@@ -282,10 +306,24 @@ export class AutopilotService {
|
||||
const score = rec?.score == null ? null : rec.score * (look.get(p.id) ?? 1);
|
||||
return { ...p, rec, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score };
|
||||
});
|
||||
for (const burst of groupBursts(frames, settings.burstGapSec * 1000)) {
|
||||
const orderedBursts = groupBursts(frames, settings.burstGapSec * 1000);
|
||||
const sentByTarget = new Map<string, number>();
|
||||
if (settings.deliverExports.length > 0) {
|
||||
const sentRows = await db.deliveryItem.groupBy({
|
||||
by: ["targetId"],
|
||||
where: { eventId, status: { in: ["QUEUED", "RUNNING", "WAITING", "DONE"] } },
|
||||
_count: true,
|
||||
});
|
||||
for (const row of sentRows) sentByTarget.set(row.targetId, row._count);
|
||||
}
|
||||
for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) {
|
||||
const burst = orderedBursts[burstIndex]!;
|
||||
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;
|
||||
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 sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length;
|
||||
const need = picksNeeded(settings);
|
||||
@@ -301,9 +339,10 @@ export class AutopilotService {
|
||||
// between frames) is still that sequence. A frame that looks different may add another, up to four.
|
||||
let take = asked;
|
||||
if (!reportage) {
|
||||
take = Math.min(asked, Math.max(0, settings.picksPerBurst));
|
||||
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
|
||||
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
|
||||
.filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id))
|
||||
.map((f) => ({
|
||||
@@ -323,13 +362,16 @@ export class AutopilotService {
|
||||
});
|
||||
if (already.length > 0) {
|
||||
const next = bestOf(pool, 1)[0];
|
||||
const room = next
|
||||
? sequenceSendRoom(settings.picksPerBurst, already.map((frame) => frame.look), {
|
||||
subject: next.rec?.subject ?? null,
|
||||
people: next.rec?.people ?? null,
|
||||
reason: next.rec?.reason ?? null,
|
||||
})
|
||||
: 0;
|
||||
let sequenceCap = settings.picksPerBurst;
|
||||
if (settings.deliverExports.length > 0) sequenceCap = settings.deliverExports.length;
|
||||
let room = 0;
|
||||
if (next) {
|
||||
room = sequenceSendRoom(sequenceCap, already.map((frame) => frame.look), {
|
||||
subject: next.rec?.subject ?? null,
|
||||
people: next.rec?.people ?? null,
|
||||
reason: next.rec?.reason ?? null,
|
||||
});
|
||||
}
|
||||
take = Math.min(take, room);
|
||||
}
|
||||
const chosen = bestOf(pool, take)
|
||||
@@ -408,11 +450,37 @@ export class AutopilotService {
|
||||
await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } });
|
||||
}
|
||||
// "Only the best" delivers per window of the match instead (below), not every burst's picks.
|
||||
// N exports → rank i of this burst to export i (same file never to two).
|
||||
const targets = exportTargets(settings);
|
||||
if (settings.selection === "bursts" && targets.length && best.length && this.deps.deliveries && event.createdById) {
|
||||
// One different frame per destination still under its total. A copy (Direto → Arquivo) shares the frame.
|
||||
const slots: BurstExportSlot[] = exportSlots(settings).map((slot) => ({
|
||||
...slot,
|
||||
sent: sentByTarget.get(slot.targetId) ?? 0,
|
||||
}));
|
||||
if (settings.selection === "bursts" && settings.deliverExports.length > 0 && slots.length && best.length && this.deps.deliveries && event.createdById) {
|
||||
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
|
||||
const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length);
|
||||
const plan = assignBurstExports(slots, burstIndex, sendable.length);
|
||||
for (const assignment of plan) {
|
||||
const frame = sendable[assignment.rank];
|
||||
if (!frame) continue;
|
||||
const targets = [assignment.targetId, ...assignment.alsoTargetIds];
|
||||
for (const targetId of targets) {
|
||||
await this.deps.deliveries
|
||||
.enqueue({
|
||||
organizationId: event.organizationId,
|
||||
targetId,
|
||||
photoIds: [frame.id],
|
||||
again: false,
|
||||
originals: assignment.originals,
|
||||
requestedById: event.createdById,
|
||||
})
|
||||
.catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued"));
|
||||
}
|
||||
sentByTarget.set(assignment.targetId, (sentByTarget.get(assignment.targetId) ?? 0) + 1);
|
||||
}
|
||||
} else if (settings.selection === "bursts" && slots.length && best.length && this.deps.deliveries && event.createdById) {
|
||||
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
|
||||
const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length);
|
||||
const targets = exportTargets(settings);
|
||||
for (let i = 0; i < targets.length && i < sendable.length; i++) {
|
||||
const id = sendable[i]!.id;
|
||||
await this.deps.deliveries
|
||||
@@ -434,6 +502,10 @@ export class AutopilotService {
|
||||
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -464,6 +536,13 @@ export class AutopilotService {
|
||||
// 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.
|
||||
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 = {
|
||||
start: event.startsAt.getTime(),
|
||||
durationMs: matchMinutes(event.sport) * 60_000,
|
||||
@@ -471,7 +550,7 @@ export class AutopilotService {
|
||||
minGapMs: MELHORES_GAP_MS,
|
||||
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,
|
||||
...curateOpts,
|
||||
});
|
||||
@@ -492,7 +571,7 @@ export class AutopilotService {
|
||||
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 }];
|
||||
});
|
||||
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)));
|
||||
seenBy.set(g.targetId, new Set(parts.flatMap((d) => d.ids)));
|
||||
}
|
||||
@@ -584,8 +663,284 @@ export class AutopilotService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof settings.restHomeFromMin === "number" && settings.restTargetId && galleries.length) {
|
||||
await this.sendGalleryRest(eventId, settings);
|
||||
}
|
||||
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. */
|
||||
|
||||
@@ -22,8 +22,96 @@ export function exportTargets(settings: Pick<AutopilotSettings, "deliverTargetId
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface BurstExportSlot {
|
||||
targetId: string;
|
||||
alsoTargetIds: string[];
|
||||
/** Null: this destination stays in every burst. */
|
||||
count: number | null;
|
||||
originals: boolean;
|
||||
/** Photos already queued or delivered to `targetId` in this event. */
|
||||
sent: number;
|
||||
}
|
||||
|
||||
export interface BurstAssignment {
|
||||
targetId: string;
|
||||
alsoTargetIds: string[];
|
||||
originals: boolean;
|
||||
/** Index into the burst's ranked frames. 0 is the best available. */
|
||||
rank: number;
|
||||
}
|
||||
|
||||
/** The configured exports, or one slot per legacy destination when that list is empty. */
|
||||
export function exportSlots(
|
||||
settings: Pick<AutopilotSettings, "deliverExports" | "deliverTargetIds" | "deliverTargetId" | "restTargetId">,
|
||||
): Omit<BurstExportSlot, "sent">[] {
|
||||
const configured = settings.deliverExports ?? [];
|
||||
if (configured.length) {
|
||||
const seen = new Set<string>();
|
||||
const slots: Omit<BurstExportSlot, "sent">[] = [];
|
||||
for (const row of configured) {
|
||||
if (!row.targetId || seen.has(row.targetId)) continue;
|
||||
seen.add(row.targetId);
|
||||
const also: string[] = [];
|
||||
for (const id of row.alsoTargetIds) {
|
||||
if (!id || id === row.targetId || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
also.push(id);
|
||||
}
|
||||
slots.push({
|
||||
targetId: row.targetId,
|
||||
alsoTargetIds: also,
|
||||
count: row.count,
|
||||
originals: row.originals,
|
||||
});
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
return exportTargets(settings).map((targetId) => ({
|
||||
targetId,
|
||||
alsoTargetIds: [],
|
||||
count: null,
|
||||
originals: false,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* One different frame per destination that is still under its total. A short burst starts at the next
|
||||
* destination, so the frames that do exist rotate and every total can still be met. A destination that
|
||||
* already has its `count` is skipped. `alsoTargetIds` ride with that frame and do not take another one.
|
||||
*/
|
||||
export function assignBurstExports(slots: readonly BurstExportSlot[], burstIndex: number, frameCount: number): BurstAssignment[] {
|
||||
if (frameCount <= 0 || slots.length === 0) return [];
|
||||
const open: { slot: BurstExportSlot; order: number }[] = [];
|
||||
for (let order = 0; order < slots.length; order++) {
|
||||
const slot = slots[order]!;
|
||||
if (slot.count !== null && slot.sent >= slot.count) continue;
|
||||
open.push({ slot, order });
|
||||
}
|
||||
if (open.length === 0) return [];
|
||||
const start = burstIndex % slots.length;
|
||||
open.sort((left, right) => {
|
||||
const leftTurn = (left.order - start + slots.length) % slots.length;
|
||||
const rightTurn = (right.order - start + slots.length) % slots.length;
|
||||
return leftTurn - rightTurn;
|
||||
});
|
||||
const take = Math.min(open.length, frameCount);
|
||||
const assigned: BurstAssignment[] = [];
|
||||
for (let rank = 0; rank < take; rank++) {
|
||||
const slot = open[rank]!.slot;
|
||||
assigned.push({
|
||||
targetId: slot.targetId,
|
||||
alsoTargetIds: slot.alsoTargetIds,
|
||||
originals: slot.originals,
|
||||
rank,
|
||||
});
|
||||
}
|
||||
return assigned;
|
||||
}
|
||||
|
||||
/** How many frames of a burst to keep: one per configured export, else `picksPerBurst`. */
|
||||
export function picksNeeded(settings: AutopilotSettings): number {
|
||||
const configured = settings.deliverExports?.length ?? 0;
|
||||
if (configured > 0) return Math.min(10, configured);
|
||||
const n = exportTargets(settings).length;
|
||||
if (n > 0) return Math.min(5, Math.max(1, n));
|
||||
return settings.picksPerBurst;
|
||||
|
||||
@@ -4,13 +4,19 @@ import type { Db } from "../db.js";
|
||||
/** The destination photographers pick to send an under-19 national game to the FPA cloud. */
|
||||
export const CLOUD_M19_TARGET = "Cloud M19";
|
||||
|
||||
/** The same kind of destination for the women's under-17 side. */
|
||||
export const CLOUD_W17_TARGET = "Cloud W17";
|
||||
|
||||
/**
|
||||
* One Nextcloud destination per organisation that already delivers club games to cloud.photoreport.pt.
|
||||
* Same account and file name as that destination; the folder is Seleções Nacionais/M19.
|
||||
* Same account and file name as that destination; the folder is under Seleções Nacionais.
|
||||
* It does not send on arrival: the photographer chooses it for this game.
|
||||
* Returns how many destinations were created.
|
||||
*/
|
||||
export async function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
async function ensureNationalCloudTarget(
|
||||
db: Db,
|
||||
target: { name: string; folder: string; fileName: string },
|
||||
): Promise<number> {
|
||||
const sources = await db.deliveryTarget.findMany({
|
||||
where: {
|
||||
kind: "NEXTCLOUD",
|
||||
@@ -31,21 +37,21 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
if (seen.has(source.organizationId)) continue;
|
||||
seen.add(source.organizationId);
|
||||
const exists = await db.deliveryTarget.findUnique({
|
||||
where: { organizationId_name: { organizationId: source.organizationId, name: CLOUD_M19_TARGET } },
|
||||
where: { organizationId_name: { organizationId: source.organizationId, name: target.name } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (exists) continue;
|
||||
await db.deliveryTarget.create({
|
||||
data: {
|
||||
organizationId: source.organizationId,
|
||||
name: CLOUD_M19_TARGET,
|
||||
name: target.name,
|
||||
kind: source.kind,
|
||||
baseUrl: source.baseUrl,
|
||||
username: source.username,
|
||||
secretEnc: source.secretEnc,
|
||||
hostFingerprint: source.hostFingerprint,
|
||||
folderTemplate: DESTINATION_EXAMPLES.fpaM19.folder,
|
||||
fileNameTemplate: source.fileNameTemplate || DESTINATION_EXAMPLES.fpaM19.fileName,
|
||||
folderTemplate: target.folder,
|
||||
fileNameTemplate: source.fileNameTemplate || target.fileName,
|
||||
longEdge: source.longEdge,
|
||||
jpegQuality: source.jpegQuality,
|
||||
sharpen: source.sharpen,
|
||||
@@ -64,3 +70,19 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
export function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
return ensureNationalCloudTarget(db, {
|
||||
name: CLOUD_M19_TARGET,
|
||||
folder: DESTINATION_EXAMPLES.fpaM19.folder,
|
||||
fileName: DESTINATION_EXAMPLES.fpaM19.fileName,
|
||||
});
|
||||
}
|
||||
|
||||
export function ensureCloudW17Target(db: Db): Promise<number> {
|
||||
return ensureNationalCloudTarget(db, {
|
||||
name: CLOUD_W17_TARGET,
|
||||
folder: DESTINATION_EXAMPLES.fpaW17.folder,
|
||||
fileName: DESTINATION_EXAMPLES.fpaW17.fileName,
|
||||
});
|
||||
}
|
||||
@@ -151,7 +151,7 @@ function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra:
|
||||
matchNumber: "1",
|
||||
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",
|
||||
);
|
||||
const fileSample = { ...built, ...extra };
|
||||
@@ -392,8 +392,13 @@ export async function registerDeliveryRoutes(
|
||||
where: { id: itemId, organizationId: orgId, status: "FAILED" },
|
||||
data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null },
|
||||
});
|
||||
if (!result.count) throw notFound("failed_item_not_found");
|
||||
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
|
||||
if (result.count) return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
|
||||
// Race: the item was no longer FAILED between the render and the retry (autopilot/queue worker
|
||||
// requeued, retried, or retracted it). The retry is idempotent — return the current state instead
|
||||
// of a 404, so the desktop does not unhandledrejection into the error loop (BIT-33418).
|
||||
const current = await db.deliveryItem.findUnique({ where: { id: itemId } });
|
||||
if (!current) throw notFound("item_not_found");
|
||||
return toItemSummary(current);
|
||||
});
|
||||
|
||||
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
|
||||
|
||||
@@ -288,7 +288,7 @@ export class DeliveryService {
|
||||
);
|
||||
}
|
||||
return created;
|
||||
});
|
||||
}, { timeout: 30_000 });
|
||||
queued.push(...items);
|
||||
}
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -175,6 +175,7 @@ export class ZerozeroTransport implements Transport {
|
||||
const account = await this.client.login();
|
||||
const author = meta?.author?.trim() || account.name || "PhotoReport";
|
||||
const imageId = await this.client.upload(gameId, fileName, data, author);
|
||||
await this.client.publish(gameId, imageId);
|
||||
return `${gameId}/${imageId}`;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { TransportError } from "./transports.js";
|
||||
import { ZerozeroClient } from "./zerozero.js";
|
||||
|
||||
/**
|
||||
* A desk that is already willing to sign the client in, and answers photo-sync however the test says.
|
||||
* Login is the real OAuth dance; only the publish routes vary.
|
||||
*/
|
||||
function desk(publish: (pathname: string) => Response): typeof fetch {
|
||||
return async (input, init) => {
|
||||
const url = new URL(String(input));
|
||||
const method = init?.method ?? "GET";
|
||||
const cookie = new Headers(init?.headers).get("cookie") ?? "";
|
||||
const has = (name: string) => cookie.split(/;\s*/).some((part) => part.startsWith(`${name}=`));
|
||||
if (url.hostname === "www.zerozero.pt" && url.pathname === "/oauth.php") {
|
||||
if (has("zzuser")) {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "https://fotos.zerozero.pt/api/auth/callback?code=c&state=s" },
|
||||
});
|
||||
}
|
||||
return new Response("login", { status: 200, headers: { "set-cookie": "PHPSESSID=s; Domain=.zerozero.pt" } });
|
||||
}
|
||||
if (url.hostname === "www.zerozero.pt" && url.pathname === "/ax_login.php" && method === "POST") {
|
||||
return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; Domain=.zerozero.pt" } });
|
||||
}
|
||||
if (url.pathname === "/api/auth/login") {
|
||||
return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&state=s" });
|
||||
}
|
||||
if (url.pathname === "/api/auth/callback") {
|
||||
return new Response(null, { status: 302, headers: { location: "https://fotos.zerozero.pt/", "set-cookie": "desk=ok; Path=/" } });
|
||||
}
|
||||
if (url.pathname === "/api/auth/me") {
|
||||
if (!has("desk")) return Response.json({ error: "unauthorized" }, { status: 401 });
|
||||
return Response.json({ role: "photographer", photographer_name: "Kapta+" });
|
||||
}
|
||||
if (url.pathname === "/") return new Response("desk", { status: 200 });
|
||||
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) return publish(url.pathname);
|
||||
return new Response("no", { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
describe("zerozero remove", () => {
|
||||
it("never asks the desk to delete a \"synced-\" placeholder (a real image is taken back: test/delivery.test.ts)", async () => {
|
||||
const calls: string[] = [];
|
||||
@@ -14,3 +53,109 @@ describe("zerozero remove", () => {
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("zerozero publish", () => {
|
||||
it("publishes the one photo that was just uploaded", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk((pathname) => {
|
||||
calls.push(pathname);
|
||||
return Response.json({ synced: 1, failed: 0, failures: [] });
|
||||
}),
|
||||
);
|
||||
await client.publish("12627743", "img-9");
|
||||
expect(calls).toEqual(["/api/photo-sync/img-9"]);
|
||||
});
|
||||
|
||||
it("publishes the game when the account cannot publish one photo", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk((pathname) => {
|
||||
calls.push(pathname);
|
||||
if (pathname.startsWith("/api/photo-sync/match/")) return Response.json({ synced: 1, failed: 0, failures: [] });
|
||||
return Response.json({ error: "forbidden" }, { status: 403 });
|
||||
}),
|
||||
);
|
||||
await client.publish("12627743", "img-9");
|
||||
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
|
||||
});
|
||||
|
||||
it("signs in again when publish answers insufficient permissions", async () => {
|
||||
const calls: string[] = [];
|
||||
let refused = false;
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk((pathname) => {
|
||||
calls.push(pathname);
|
||||
if (!refused && pathname === "/api/photo-sync/img-9") {
|
||||
refused = true;
|
||||
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
|
||||
}
|
||||
return Response.json({ synced: 1, failed: 0, failures: [] });
|
||||
}),
|
||||
);
|
||||
await client.publish("12627743", "img-9");
|
||||
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9"]);
|
||||
});
|
||||
|
||||
it("publishes the whole game when the desk has no single-photo publish", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk((pathname) => {
|
||||
calls.push(pathname);
|
||||
if (pathname === "/api/photo-sync/match/12627743") return Response.json({ synced: 1, failed: 0, failures: [] });
|
||||
return new Response("missing", { status: 404 });
|
||||
}),
|
||||
);
|
||||
await client.publish("12627743", "img-9");
|
||||
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
|
||||
});
|
||||
|
||||
it("publishes the game when the desk already had the file and there is no image id", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk((pathname) => {
|
||||
calls.push(pathname);
|
||||
return Response.json({ synced: 0, failed: 0, failures: [] });
|
||||
}),
|
||||
);
|
||||
await client.publish("12627743", "synced-PS_jogo_1.jpg");
|
||||
expect(calls).toEqual(["/api/photo-sync/match/12627743"]);
|
||||
});
|
||||
|
||||
it("retries when the desk reports that this photo did not publish", async () => {
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk(() => Response.json({ synced: 0, failed: 1, failures: [{ id: "img-9", error: "desk busy" }] })),
|
||||
);
|
||||
const err = await client.publish("12627743", "img-9").then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
expect(err).toBeInstanceOf(TransportError);
|
||||
expect((err as TransportError).message).toBe("zerozero publish: desk busy");
|
||||
expect((err as TransportError).transient).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the upload when the account is not allowed to publish", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = new ZerozeroClient(
|
||||
{ username: "kapta", password: "zz-pass" },
|
||||
desk((pathname) => {
|
||||
calls.push(pathname);
|
||||
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
|
||||
}),
|
||||
);
|
||||
await client.publish("12627743", "img-9");
|
||||
expect(calls).toEqual([
|
||||
"/api/photo-sync/img-9",
|
||||
"/api/photo-sync/img-9",
|
||||
"/api/photo-sync/match/12627743",
|
||||
"/api/photo-sync/match/12627743",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -11,12 +11,16 @@ import { TransportError } from "./transports.js";
|
||||
* Lisbon time).
|
||||
* - Upload: tus 1.0 at `/api/upload?match_id=<id>`, metadata `match_id`, `artist` (the author shown with the photo)
|
||||
* and the file name. The image's id is the upload's id; `DELETE /api/images/<id>` takes it back.
|
||||
* - Publish: the upload only lands on the desk. The public game shows it after `POST /api/photo-sync/<image id>`
|
||||
* (the desk's "send now"). When that route is missing, `POST /api/photo-sync/match/<id>` publishes the game.
|
||||
*/
|
||||
|
||||
export const ZEROZERO_URL = "https://fotos.zerozero.pt";
|
||||
const LOGIN_SITE = "https://www.zerozero.pt";
|
||||
const CHUNK = 5 * 1024 * 1024;
|
||||
const TIMEOUT_MS = 60_000;
|
||||
/** Publishing pushes the file onwards to the public game, which is slower than one tus chunk. */
|
||||
const PUBLISH_TIMEOUT_MS = 180_000;
|
||||
|
||||
export interface ZerozeroGame {
|
||||
id: string;
|
||||
@@ -104,7 +108,7 @@ export class ZerozeroClient {
|
||||
) {}
|
||||
|
||||
/** One request with the jar's cookies; redirects followed by hand so every hop's cookies are kept. */
|
||||
private async request(url: string, init: RequestInit = {}, hops = 10): Promise<{ res: Response; url: string }> {
|
||||
private async request(url: string, init: RequestInit = {}, hops = 10, timeoutMs = TIMEOUT_MS): Promise<{ res: Response; url: string }> {
|
||||
let current = url;
|
||||
let options = init;
|
||||
for (let i = 0; i <= hops; i++) {
|
||||
@@ -114,7 +118,7 @@ export class ZerozeroClient {
|
||||
if (!headers.has("user-agent")) headers.set("user-agent", "PhotoReport/2 (delivery)");
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
|
||||
} catch (err) {
|
||||
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
|
||||
}
|
||||
@@ -263,6 +267,78 @@ export class ZerozeroClient {
|
||||
return new URL(url).pathname.split("/").filter(Boolean).pop()!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts an uploaded photo on the public game. The desk keeps it first (`sync_status` pending); without this call
|
||||
* it never leaves the photographer's page. One photo when the desk allows it, otherwise the whole game.
|
||||
* `synced-<file name>` is not an image id (the desk already had the file), so the game is published.
|
||||
*/
|
||||
async publish(gameId: string, imageId: string): Promise<void> {
|
||||
const placeholder = imageId.startsWith("synced-");
|
||||
if (!placeholder) {
|
||||
const one = await this.postApi(`/photo-sync/${encodeURIComponent(imageId)}`, PUBLISH_TIMEOUT_MS);
|
||||
// 404/405: this desk has no single-photo publish. 403: this account may still publish the game.
|
||||
if (one.status !== 404 && one.status !== 405 && one.status !== 403) {
|
||||
this.assertPublished(one, imageId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const match = await this.postApi(`/photo-sync/match/${encodeURIComponent(gameId)}`, PUBLISH_TIMEOUT_MS);
|
||||
// A photographer account may upload but not publish ("Insufficient permissions"). The file is already on
|
||||
// the desk; failing the delivery here only blocks the queue. The desk publishes those itself.
|
||||
if (match.status === 403) return;
|
||||
const ours = placeholder ? null : imageId;
|
||||
this.assertPublished(match, ours);
|
||||
}
|
||||
|
||||
private async postApi(path: string, timeoutMs: number, retry = true): Promise<{ status: number; body: unknown }> {
|
||||
await this.login();
|
||||
// The desk's own client posts JSON. An empty object is what "send now" sends when it has no extra fields.
|
||||
const { res } = await this.request(
|
||||
`${this.base}/api${path}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", accept: "application/json" },
|
||||
body: "{}",
|
||||
},
|
||||
10,
|
||||
timeoutMs,
|
||||
);
|
||||
// 401: logged out. 403 "Insufficient permissions": the cookie is still sent, but the session is no longer
|
||||
// the photographer. One fresh sign-in. The same refusal after that is the account, not a stale login.
|
||||
if (res.status === 401 && retry) {
|
||||
this.account = null;
|
||||
this.jar.clear();
|
||||
return this.postApi(path, timeoutMs, false);
|
||||
}
|
||||
if (res.status === 403 && retry) {
|
||||
this.account = null;
|
||||
this.jar.clear();
|
||||
return this.postApi(path, timeoutMs, false);
|
||||
}
|
||||
const text = await res.text();
|
||||
let body: unknown = null;
|
||||
if (text) {
|
||||
try {
|
||||
body = JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
}
|
||||
return { status: res.status, body };
|
||||
}
|
||||
|
||||
private assertPublished(result: { status: number; body: unknown }, imageId: string | null): void {
|
||||
if (result.status >= 200 && result.status < 300) {
|
||||
assertSyncBody(result.body, imageId);
|
||||
return;
|
||||
}
|
||||
const detail = errorText(result.body);
|
||||
const transient = result.status >= 500 || result.status === 429 || result.status === 404;
|
||||
let message = `zerozero publish: ${result.status}`;
|
||||
if (detail) message = `${message} ${detail}`;
|
||||
throw new TransportError(message, transient);
|
||||
}
|
||||
|
||||
/** Takes an uploaded image back. Already gone (or no longer this account's to remove) is not an error. */
|
||||
async remove(imageId: string): Promise<void> {
|
||||
// "synced-<file name>" (from `upload`, when the desk already had the file) is not a real image id: there was
|
||||
@@ -275,6 +351,31 @@ export class ZerozeroClient {
|
||||
}
|
||||
}
|
||||
|
||||
function errorText(body: unknown): string | null {
|
||||
if (!body || typeof body !== "object") return null;
|
||||
const error = (body as { error?: unknown }).error;
|
||||
if (typeof error !== "string" || !error) return null;
|
||||
return error.replace(/\s+/g, " ").slice(0, 180);
|
||||
}
|
||||
|
||||
function assertSyncBody(body: unknown, imageId: string | null): void {
|
||||
if (!body || typeof body !== "object") return;
|
||||
const record = body as { sync_status?: unknown; syncStatus?: unknown; failures?: unknown; error?: unknown };
|
||||
const status = record.sync_status ?? record.syncStatus;
|
||||
if (status === "failed") {
|
||||
const message = typeof record.error === "string" && record.error ? record.error : "the desk could not publish the photo";
|
||||
throw new TransportError(`zerozero publish: ${message}`, true);
|
||||
}
|
||||
if (!imageId || !Array.isArray(record.failures)) return;
|
||||
for (const failure of record.failures) {
|
||||
if (!failure || typeof failure !== "object") continue;
|
||||
const row = failure as { id?: unknown; error?: unknown };
|
||||
if (row.id !== imageId) continue;
|
||||
const message = typeof row.error === "string" && row.error ? row.error : "the desk could not publish the photo";
|
||||
throw new TransportError(`zerozero publish: ${message}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
function toGame(r: Record<string, unknown> | null | undefined): ZerozeroGame | null {
|
||||
if (!r) return null;
|
||||
const s = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : null);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RenderWorker, type DevelopService } from "./service.js";
|
||||
import { isPostgresAdminShutdown } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPrismaTooManyConnections } from "../lib/pg.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
|
||||
describe("isPostgresAdminShutdown", () => {
|
||||
@@ -18,6 +18,25 @@ describe("isPostgresAdminShutdown", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrismaTooManyConnections", () => {
|
||||
it("matches the P2010 raw-query variant wrapping SQLSTATE 53300 (BIT-33549)", () => {
|
||||
const err = new Error(
|
||||
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `53300`. Message: `sorry, too many clients already`",
|
||||
);
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches the P2037 variant", () => {
|
||||
const err = new Error("Too many database connections opened: sorry, too many clients already");
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match an unrelated query error", () => {
|
||||
expect(isPrismaTooManyConnections(new Error("relation \"photos\" does not exist"))).toBe(false);
|
||||
expect(isPrismaTooManyConnections(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RenderWorker poll error handling", () => {
|
||||
type Level = "info" | "warn";
|
||||
const makeLog = (): IngestLogger & { calls: { level: Level; msg: string }[] } => {
|
||||
@@ -51,6 +70,23 @@ describe("RenderWorker poll error handling", () => {
|
||||
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("logs a 53300 pool-exhaustion error at info, not warn (BIT-33549)", async () => {
|
||||
const log = makeLog();
|
||||
const worker = new RenderWorker(
|
||||
makeService(
|
||||
new Error(
|
||||
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `53300`. Message: `sorry, too many clients already`",
|
||||
),
|
||||
) as DevelopService,
|
||||
{ concurrency: 1, intervalMs: 60_000, log },
|
||||
);
|
||||
worker.start();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
await worker.stop();
|
||||
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
|
||||
});
|
||||
|
||||
it("still warns on a real poll failure", async () => {
|
||||
const log = makeLog();
|
||||
const worker = new RenderWorker(makeService(new Error("relation photos does not exist")) as DevelopService, {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Db } from "../db.js";
|
||||
import { Prisma, type PhotoEdit } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { isPostgresAdminShutdown } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPrismaTooManyConnections } from "../lib/pg.js";
|
||||
import { photoUrls } from "../library/serialize.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
|
||||
@@ -223,6 +223,9 @@ export class RenderWorker {
|
||||
// A DB restart or `pg_terminate_backend` (57P01) takes the pooled client mid-`$queryRaw`; the next tick
|
||||
// re-claims a fresh one, so log at info and let the loop continue instead of paging the error loop (BIT-32449).
|
||||
if (isPostgresAdminShutdown(err)) this.opts.log.info({ err: (err as Error).message }, "develop: poll skipped, db connection was reset");
|
||||
// Pool exhaustion (P2037 or P2010 wrapping SQLSTATE 53300 "too many clients already"): every remaining
|
||||
// query would fail the same way, so skip this tick and let the next one retry once a slot frees (BIT-33549).
|
||||
else if (isPrismaTooManyConnections(err)) this.opts.log.info({ err: (err as Error).message }, "develop: poll skipped, too many database connections");
|
||||
else this.opts.log.warn({ err }, "develop: poll failed");
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
|
||||
@@ -17,6 +17,7 @@ describe("selectionKey", () => {
|
||||
expect(selectionKey(["Seleção Nacional sub-19 Masculina"])).toBe("m19");
|
||||
expect(selectionKey(["Portugal", "Espanha", "sub-19"])).toBe("m19");
|
||||
expect(selectionKey(["Seleção Nacional sub-19 feminina"])).toBe("w19");
|
||||
expect(selectionKey(["/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA"])).toBe("w17");
|
||||
});
|
||||
|
||||
it("names no team for a club game, a gala, or a gathering", () => {
|
||||
|
||||
@@ -144,10 +144,13 @@ export class Pressure {
|
||||
* 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
|
||||
* `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`
|
||||
* 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.
|
||||
* -state budget into Postgres' `superuser_reserved_connections`); one extra worker during a deploy
|
||||
* (`pm2 startOrReload` on the fork-mode `photoreport-worker` starts the new process before the old one finishes
|
||||
* its 25 s drain, so both Prisma pools and both broadcasters are open at once — BIT-33530 was this overlap
|
||||
* 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(
|
||||
wanted: number,
|
||||
@@ -157,6 +160,7 @@ export function dbConnectionBudget(
|
||||
apiPoolSize = 10,
|
||||
realtimePerInstance = 3,
|
||||
apiReloadOverlap = 1,
|
||||
workerReloadOverlap = 1,
|
||||
superuserReserved = 3,
|
||||
headroom = 10,
|
||||
}: {
|
||||
@@ -165,10 +169,15 @@ export function dbConnectionBudget(
|
||||
apiPoolSize?: number;
|
||||
realtimePerInstance?: number;
|
||||
apiReloadOverlap?: number;
|
||||
workerReloadOverlap?: number;
|
||||
superuserReserved?: number;
|
||||
headroom?: 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));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "./pg.js";
|
||||
import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "./pg.js";
|
||||
|
||||
class PrismaLike extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
@@ -90,6 +90,31 @@ describe("isPrismaServerUnreachable", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrismaTooManyConnections", () => {
|
||||
it("matches a PrismaClientKnownRequestError with code P2037 (BIT-33558)", () => {
|
||||
const err = new PrismaLike(
|
||||
"P2037",
|
||||
"Invalid `prisma.deliveryTarget.findMany()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute",
|
||||
);
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches the 'remaining connection slots are reserved' message without the code", () => {
|
||||
expect(isPrismaTooManyConnections(new Error("Too many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"))).toBe(true);
|
||||
});
|
||||
|
||||
it("matches a P2010 raw-query failure wrapping SQLSTATE 53300 (BIT-33549)", () => {
|
||||
const err = new PrismaLike("P2010", "Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `53300`. Message: `sorry, too many clients already`");
|
||||
expect(isPrismaTooManyConnections(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match an unrelated query error", () => {
|
||||
expect(isPrismaTooManyConnections(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false);
|
||||
expect(isPrismaTooManyConnections(null)).toBe(false);
|
||||
expect(isPrismaTooManyConnections("string")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrismaTransactionTimeout", () => {
|
||||
it("matches a PrismaClientKnownRequestError with code P2028 (BIT-32083)", () => {
|
||||
const err = new PrismaLike(
|
||||
@@ -138,6 +163,28 @@ describe("isPrismaTransactionClosed", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPgClientNotQueryable", () => {
|
||||
it("matches the raw pg client.js message (BIT-33527)", () => {
|
||||
const err = new Error("Client has encountered a connection error and is not queryable");
|
||||
expect(isPgClientNotQueryable(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches the message when wrapped in a Prisma raw-query failure", () => {
|
||||
const err = new Error("Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `N/A`. Message: `Client has encountered a connection error and is not queryable`");
|
||||
expect(isPgClientNotQueryable(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match a server-closed (P1017) error", () => {
|
||||
expect(isPgClientNotQueryable(new PrismaLike("P1017", "Server has closed the connection."))).toBe(false);
|
||||
});
|
||||
|
||||
it("does not match an unrelated query error", () => {
|
||||
expect(isPgClientNotQueryable(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false);
|
||||
expect(isPgClientNotQueryable(null)).toBe(false);
|
||||
expect(isPgClientNotQueryable("string")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("retryOnConnectionClosed", () => {
|
||||
it("retries once when the first attempt throws P1017 and returns the second result", async () => {
|
||||
let calls = 0;
|
||||
|
||||
@@ -39,6 +39,21 @@ export function isPrismaServerUnreachable(err: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Postgres server has no free connection slots for non-superuser roles — every slot is in use and the
|
||||
* remaining ones are reserved for SUPERUSER. Prisma surfaces this as `PrismaClientKnownRequestError` with
|
||||
* code `P2037` and message "Too many database connections opened: …", or as `P2010` wrapping the raw
|
||||
* SQLSTATE `53300` ("sorry, too many clients already") when a `$queryRaw` hits the limit. This is pool
|
||||
* exhaustion under concurrent worker load; the next scheduled tick reclaims a freed slot, so it is
|
||||
* transient and must not page the error loop — the caller should stop the current batch and let the next
|
||||
* run retry (BIT-33538, BIT-33549 for the P2010/53300 raw-query variant).
|
||||
*/
|
||||
export function isPrismaTooManyConnections(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
const code = (err as { code?: unknown }).code;
|
||||
return code === "P2037" || /Too many database connections opened|sorry, too many clients already|\b53300\b/i.test(err.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prisma could not acquire a pooled connection to start a transaction within `maxWait`
|
||||
* (code P2028, "Transaction API error: Unable to start a transaction in the given time.").
|
||||
@@ -63,6 +78,18 @@ export function isPrismaTransactionClosed(err: unknown): boolean {
|
||||
return /Transaction already closed/i.test(err.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* A pooled `pg` Client had a connection error (socket closed, server restart, network blip) and was marked
|
||||
* not-queryable by node-postgres before Prisma's adapter-pg ran the next query on it. The message comes from
|
||||
* `pg/lib/client.js` and has no Prisma error code, so the `isPrismaConnectionClosed` (P1017) check does not
|
||||
* catch it. The pool discards the dead client and hands out a fresh one on the next attempt, so this is
|
||||
* transient and must not page the error loop (BIT-33527).
|
||||
*/
|
||||
export function isPgClientNotQueryable(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
return /Client has encountered a connection error and is not queryable/i.test(err.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `fn`, retrying it once when Postgres closed the connection before the query (`P1017`). The pool hands out a
|
||||
* fresh client on the next attempt, so a single retry clears the blip without surfacing it to the caller's
|
||||
|
||||
@@ -10,19 +10,24 @@ import { createHash } from "node:crypto";
|
||||
*/
|
||||
|
||||
/**
|
||||
* Transient PostgreSQL connection errors during a restart, graceful shutdown, or network blip. Prisma surfaces
|
||||
* these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE (57P01/57P03) or its own P1001/P1017.
|
||||
* The pool reconnects on the next attempt, so these are not code bugs — reporting them only trips the Error
|
||||
* Loop with one-off incidents from every code path that touches the database during the brief outage.
|
||||
* Individual call sites that need to stop a batch or retry still check `isPostgresAdminShutdown` /
|
||||
* `isPrismaServerUnreachable` (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the
|
||||
* error propagate to a generic log.error (BIT-32490 and 11 sibling clusters).
|
||||
* Transient PostgreSQL connection errors during a restart, graceful shutdown, network blip, or pool
|
||||
* exhaustion. Prisma surfaces these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE
|
||||
* (57P01/57P03/53300) or its own P1001/P1017, and pool exhaustion (SQLSTATE 53300) as P2037 with the
|
||||
* message "Too many database connections opened: sorry, too many clients already" — no SQLSTATE in the
|
||||
* text, so the code check is what catches it. The realtime LISTEN/NOTIFY path uses `pg` directly and
|
||||
* surfaces raw Node TCP errors (ECONNREFUSED) when Postgres is not listening at all. The pool reconnects
|
||||
* on the next attempt, so these are not code bugs — reporting them only trips the Error Loop with one-off
|
||||
* incidents from every code path that touches the database during the brief outage. Individual call sites
|
||||
* that need to stop a batch or retry still check `isPostgresAdminShutdown` / `isPrismaServerUnreachable`
|
||||
* (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the error propagate to a
|
||||
* generic log.error (BIT-32490 and 11 sibling clusters, BIT-33548 for 53300, BIT-33537 for P2037,
|
||||
* BIT-33524 for ECONNREFUSED).
|
||||
*/
|
||||
function isTransientDatabaseError(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
const code = (err as { code?: unknown }).code;
|
||||
if (code === "P1001" || code === "P1017") 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);
|
||||
if (code === "P1001" || code === "P1017" || code === "P2037" || code === "ECONNREFUSED") return true;
|
||||
return /57P01|57P03|53300|remaining connection slots are reserved|too many clients already|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection|Client has encountered a connection error and is not queryable|ECONNREFUSED/i.test(err.message);
|
||||
}
|
||||
export type ReportLevel = "critical" | "error" | "warning" | "info";
|
||||
|
||||
|
||||
@@ -16,14 +16,24 @@ import { claimInbox } from "./adopt.js";
|
||||
|
||||
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 {
|
||||
if (!next) return Prisma.DbNull;
|
||||
if (next.galleries !== undefined) return next;
|
||||
if (!current || typeof current !== "object" || Array.isArray(current)) return next;
|
||||
const kept = (current as { galleries?: AutopilotSettings["galleries"] }).galleries;
|
||||
if (!Array.isArray(kept) || kept.length === 0) return next;
|
||||
return { ...next, galleries: kept };
|
||||
const prev = current as {
|
||||
galleries?: AutopilotSettings["galleries"];
|
||||
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 EventParams = z.object({ eventId: z.uuid() });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
|
||||
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
|
||||
import { preferIpv4 } from "./lib/prefer-ipv4.js";
|
||||
import { buildApp, reporterFor } from "./app.js";
|
||||
import { loadConfig } from "./config.js";
|
||||
@@ -21,6 +21,7 @@ process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
||||
process.on("SIGINT", () => void shutdown("SIGINT"));
|
||||
|
||||
ensureCloudM19Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud M19 profile not created"));
|
||||
ensureCloudW17Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud W17 profile not created"));
|
||||
|
||||
try {
|
||||
await app.listen({ port: config.PORT, host: "0.0.0.0" });
|
||||
|
||||
@@ -111,4 +111,40 @@ describe("EHF matches", () => {
|
||||
expect(seen.some((u) => u.includes("/men/2026-27/matches/"))).toBe(true);
|
||||
expect(seen.filter((u) => u.includes("GetMatches")).length).toBe(3);
|
||||
});
|
||||
|
||||
it("reads a national standing list with the hall, the group and the kick-off", async () => {
|
||||
const fetch: Fetch = async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
matches: [
|
||||
{
|
||||
matchID: "202712010502014",
|
||||
venue: {
|
||||
date: { utc: "2026-11-27T19:00:00Z" },
|
||||
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
|
||||
},
|
||||
homeTeam: { team: { nationAbbreviation: "POR" } },
|
||||
guestTeam: { team: { nationAbbreviation: "ITA" } },
|
||||
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
|
||||
},
|
||||
],
|
||||
}),
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
});
|
||||
const rows = await new EhfProvider(fetch, 0).euroCupMenMatches("comp", "139009");
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
matchId: "202712010502014",
|
||||
startsAt: new Date("2026-11-27T19:00:00Z"),
|
||||
homeNation: "POR",
|
||||
awayNation: "ITA",
|
||||
venue: "Pavilhão da Associação Atlética de Águas Santas",
|
||||
city: "Àguas Santas",
|
||||
round: "Qualification Tournaments",
|
||||
group: "C",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
nationalNamesMatch,
|
||||
nationalSideFromTexts,
|
||||
nationalTeamExternalId,
|
||||
youthEuroRound,
|
||||
youthNationalTeam,
|
||||
} from "./national.js";
|
||||
|
||||
describe("national call-up", () => {
|
||||
@@ -76,4 +78,12 @@ describe("nationalTeamExternalId", () => {
|
||||
expect(nationalTeamExternalId("Roménia", "w18")).toBe("ROU-W18");
|
||||
expect(nationalCountryLabel("Switzerland")).toBe("Suíça");
|
||||
});
|
||||
|
||||
it("maps the W17 qualification nations onto youth sides", () => {
|
||||
expect(youthNationalTeam("POR", "w17")).toEqual({ externalId: "W17", name: "Portugal", abbreviation: "POR" });
|
||||
expect(youthNationalTeam("ITA", "w17")).toEqual({ externalId: "ITA-W17", name: "Itália", abbreviation: "ITA" });
|
||||
expect(youthNationalTeam("SLO", "w17")?.externalId).toBe("SLO-W17");
|
||||
expect(youthNationalTeam("FAR", "w17")?.name).toBe("Ilhas Faroé");
|
||||
expect(youthEuroRound("Qualification Tournaments", "C")).toBe("Qualificação C");
|
||||
});
|
||||
});
|
||||
@@ -171,6 +171,19 @@ export const EHF_EURO_CUP_MEN = {
|
||||
sheetWindowMs: 3 * 86400_000,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Women's under-17 EHF EURO 2027 qualification (Águas Santas, 27–29 Nov 2026, and the same page
|
||||
* for the rest of that tournament). Same standing list and match sheet as the men's Euro Cup.
|
||||
*/
|
||||
export const EHF_W17_EURO = {
|
||||
competitionId: "DrPEklHxLKeDu_IajXOQvA",
|
||||
contentId: "139009",
|
||||
externalId: "W17-EURO",
|
||||
name: "W17 EHF EURO",
|
||||
gender: "F" as const,
|
||||
side: "w17",
|
||||
} as const;
|
||||
|
||||
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||
|
||||
/** Same athlete across FPA call-up spelling and EHF sheet ("Iturriza" / "Iturizza", "Miguel Oliveira" / "Miguel Moreira de Oliveira"). */
|
||||
@@ -231,6 +244,21 @@ export function nationalCountryLabel(raw: string): string | null {
|
||||
if (/^(fra|fr|franca|france)$/.test(n)) return "França";
|
||||
if (/^(ger|deu|alemanha|germany)$/.test(n)) return "Alemanha";
|
||||
if (/^(swe|suecia|sweden)$/.test(n)) return "Suécia";
|
||||
if (/^(ita|italy|italia)$/.test(n)) return "Itália";
|
||||
if (/^(slo|svn|slovenia|eslovenia)$/.test(n)) return "Eslovénia";
|
||||
if (/^(ukr|ukraine|ucrania)$/.test(n)) return "Ucrânia";
|
||||
if (/^(isl|iceland|islandia)$/.test(n)) return "Islândia";
|
||||
if (/^(far|fro|faroe|faroe islands|ilhas faroe)$/.test(n)) return "Ilhas Faroé";
|
||||
if (/^(tur|turkey|turkiye|turquia)$/.test(n)) return "Turquia";
|
||||
if (/^(isr|israel)$/.test(n)) return "Israel";
|
||||
if (/^(mkd|north macedonia|macedonia do norte)$/.test(n)) return "Macedónia do Norte";
|
||||
if (/^(ltu|lithuania|lituania)$/.test(n)) return "Lituânia";
|
||||
if (/^(kos|kosovo)$/.test(n)) return "Kosovo";
|
||||
if (/^(gre|greece|grecia)$/.test(n)) return "Grécia";
|
||||
if (/^(aut|austria)$/.test(n)) return "Áustria";
|
||||
if (/^(pol|poland|polonia)$/.test(n)) return "Polónia";
|
||||
if (/^(fin|finland|finlandia)$/.test(n)) return "Finlândia";
|
||||
if (/^(lux|luxembourg|luxemburgo)$/.test(n)) return "Luxemburgo";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -248,6 +276,15 @@ const YOUTH_CODE: Record<string, string> = {
|
||||
hungria: "HUN",
|
||||
noruega: "NOR",
|
||||
italia: "ITA",
|
||||
ucrania: "UKR",
|
||||
"ilhas faroe": "FAR",
|
||||
turquia: "TUR",
|
||||
israel: "ISR",
|
||||
"macedonia do norte": "MKD",
|
||||
lituania: "LTU",
|
||||
kosovo: "KOS",
|
||||
grecia: "GRE",
|
||||
luxemburgo: "LUX",
|
||||
polonia: "POL",
|
||||
chequia: "CZE",
|
||||
montenegro: "MNE",
|
||||
@@ -261,6 +298,33 @@ const YOUTH_CODE: Record<string, string> = {
|
||||
"paises baixos": "NED",
|
||||
};
|
||||
|
||||
/**
|
||||
* A youth national side from an EHF nation code or an English/Portuguese country name.
|
||||
* Portugal's under-17 women are "W17"; Italy is "ITA-W17".
|
||||
*/
|
||||
export function youthNationalTeam(
|
||||
nation: string | null | undefined,
|
||||
side: string,
|
||||
): { externalId: string; name: string; abbreviation: string } | null {
|
||||
if (!nation) return null;
|
||||
const name = nationalCountryLabel(nation);
|
||||
if (!name) return null;
|
||||
const externalId = nationalTeamExternalId(name, side);
|
||||
if (!externalId) return null;
|
||||
const abbreviation = YOUTH_CODE[fold(name)];
|
||||
if (!abbreviation) return null;
|
||||
return { externalId, name, abbreviation };
|
||||
}
|
||||
|
||||
/** "Qualification Tournaments" + group "C" is what the picker shows as "Qualificação C". */
|
||||
export function youthEuroRound(round: string | null, group: string | null): string | null {
|
||||
let name = round;
|
||||
if (name === "Qualification Tournaments") name = "Qualificação";
|
||||
if (name && group) return `${name} ${group}`;
|
||||
if (name) return name;
|
||||
return group;
|
||||
}
|
||||
|
||||
/** Which national sports team externalId fits this country + side key. */
|
||||
export function nationalTeamExternalId(country: string, side: string): string | null {
|
||||
const label = nationalCountryLabel(country) ?? country;
|
||||
|
||||
@@ -1538,7 +1538,7 @@ export class EhfProvider {
|
||||
async euroCupMenMatches(
|
||||
competitionId: string,
|
||||
contentId: string,
|
||||
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> {
|
||||
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[]> {
|
||||
const data = await get(
|
||||
this.fetcher,
|
||||
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
|
||||
@@ -1546,7 +1546,7 @@ export class EhfProvider {
|
||||
"json",
|
||||
);
|
||||
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
|
||||
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
|
||||
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[] = [];
|
||||
for (const row of rows) {
|
||||
const m = obj(row);
|
||||
const matchId = str(m.matchID);
|
||||
@@ -1557,6 +1557,7 @@ export class EhfProvider {
|
||||
if (Number.isNaN(at.getTime())) continue;
|
||||
const hall = str(place.hallName);
|
||||
const city = str(place.cityName);
|
||||
const comp = obj(m.comp);
|
||||
out.push({
|
||||
matchId,
|
||||
startsAt: at,
|
||||
@@ -1564,6 +1565,8 @@ export class EhfProvider {
|
||||
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
|
||||
venue: hall,
|
||||
city,
|
||||
round: str(obj(comp.round).name),
|
||||
group: str(obj(comp.group).name),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -42,6 +42,12 @@ const p1017 = () =>
|
||||
const p1017findUnique = () =>
|
||||
Object.assign(new Error("Invalid `prisma.person.findUnique()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
|
||||
|
||||
const p2037 = () =>
|
||||
Object.assign(
|
||||
new Error("Invalid `prisma.event.findUnique()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"),
|
||||
{ code: "P2037" },
|
||||
);
|
||||
|
||||
const ligaTeam = (id: string, externalId: string) => ({
|
||||
id,
|
||||
provider: "LIGA",
|
||||
@@ -271,6 +277,23 @@ describe("syncEventSquads downgrades a P1017 from person.findUnique in linkSquad
|
||||
});
|
||||
});
|
||||
|
||||
describe("syncEventSquads downgrades a P2037 too-many-connections error (BIT-33538)", () => {
|
||||
it("logs at info and returns zeros when the initial event lookup hits P2037", async () => {
|
||||
// The error loop reported P2037 ("Too many database connections opened: remaining connection slots are
|
||||
// reserved for roles with the SUPERUSER attribute") from syncEventSquadsNow → db.event.findUnique. Without
|
||||
// this guard the rejection escapes to the archive caller's warn and pages the error loop for a transient blip.
|
||||
const db = {
|
||||
event: { findUnique: async () => { throw p2037(); } },
|
||||
};
|
||||
const service = new SportsService(makeDeps(db));
|
||||
const out = await service.syncEventSquads("evt-1");
|
||||
expect(out).toEqual({ created: 0, updated: 0, headshots: 0 });
|
||||
const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log;
|
||||
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("linkStoredSquads downgrades a 57P01 admin-terminated connection (BIT-32471)", () => {
|
||||
it("logs at info and returns 0 when the raw query is terminated mid-flight (57P01)", async () => {
|
||||
const db = {
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js";
|
||||
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
|
||||
import { badRequest, notFound } from "../lib/errors.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js";
|
||||
import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js";
|
||||
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
|
||||
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
|
||||
import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.js";
|
||||
@@ -17,6 +17,7 @@ import { type ClubCandidate, type JogaClient, chooseClub, jogaCompetitionId, jog
|
||||
import { sameListedPerson } from "./people.js";
|
||||
import {
|
||||
EHF_EURO_CUP_MEN,
|
||||
EHF_W17_EURO,
|
||||
ESP_M19_2026,
|
||||
M19_POR_2026,
|
||||
NATIONAL_SIDES,
|
||||
@@ -24,6 +25,8 @@ import {
|
||||
SUI_EURO_CUP_2026,
|
||||
nationToSnamTeam,
|
||||
nationalNamesMatch,
|
||||
youthEuroRound,
|
||||
youthNationalTeam,
|
||||
type NationalCallUp,
|
||||
} from "./national.js";
|
||||
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
|
||||
@@ -615,6 +618,7 @@ export class SportsService {
|
||||
const espHave = await this.deps.db.sportsPlayer.count({ where: { teamId: espM19Id, season, goneAt: null } });
|
||||
if (espHave === 0) result.players += await this.saveNationalCallUp(espM19Id, season, ESP_M19_2026);
|
||||
await this.applyEuroCupSheets(now, season, result);
|
||||
await this.applyYouthEuros(now, season, result);
|
||||
// People + reference faces: only when an event syncs these teams (`syncEventSquads`), not on every FPA refresh.
|
||||
await this.fillNationalPhotos(snamId, season);
|
||||
await this.fillNationalPhotos(suiId, season);
|
||||
@@ -687,6 +691,20 @@ export class SportsService {
|
||||
this.deps.log.info({ side: camp.side, players: camp.players.length, source: camp.sourceUrl }, "sports: youth call-up");
|
||||
}
|
||||
for (const game of camp.games) {
|
||||
if (camp.side === EHF_W17_EURO.side) {
|
||||
const homeTeamId = await this.upsertTeam("FPA", {
|
||||
externalId: game.homeExternalId,
|
||||
name: game.homeCountry,
|
||||
abbreviation: youthAbbrev(game.homeExternalId, camp.side),
|
||||
});
|
||||
const awayTeamId = await this.upsertTeam("FPA", {
|
||||
externalId: game.awayExternalId,
|
||||
name: game.awayCountry,
|
||||
abbreviation: youthAbbrev(game.awayExternalId, camp.side),
|
||||
});
|
||||
const listed = await this.hasOfficialYouthFixture(homeTeamId, awayTeamId, game.startsAt, EHF_W17_EURO.externalId);
|
||||
if (listed) continue;
|
||||
}
|
||||
const comp = await this.youthCompetition(season, camp.side);
|
||||
result.fixtures += await this.saveFixture(comp, "FPA", {
|
||||
externalId: game.externalId,
|
||||
@@ -806,6 +824,149 @@ export class SportsService {
|
||||
}
|
||||
}
|
||||
|
||||
/** The FPA camp and the EHF page can disagree by an hour and still be the same match. */
|
||||
private sameKickoff(startsAt: Date) {
|
||||
const slackMs = 2 * 60 * 60 * 1000;
|
||||
return {
|
||||
gte: new Date(startsAt.getTime() - slackMs),
|
||||
lte: new Date(startsAt.getTime() + slackMs),
|
||||
};
|
||||
}
|
||||
|
||||
/** The official under-17 EURO already has this kick-off, so the camp must not add it again as a friendly. */
|
||||
private async hasOfficialYouthFixture(homeTeamId: string, awayTeamId: string, startsAt: Date, competitionExternalId: string): Promise<boolean> {
|
||||
const row = await this.deps.db.sportsFixture.findFirst({
|
||||
where: {
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
startsAt: this.sameKickoff(startsAt),
|
||||
competition: { externalId: competitionExternalId },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return row !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The FPA post lists the same under-17 game as a friendly ("Sub-17 feminina"). One match, one row.
|
||||
* An event already opened on the friendly keeps that row when it can become the official one.
|
||||
*/
|
||||
private async foldYouthFriendly(
|
||||
officialCompetitionId: string,
|
||||
officialExternalId: string,
|
||||
homeTeamId: string,
|
||||
awayTeamId: string,
|
||||
startsAt: Date,
|
||||
): Promise<void> {
|
||||
const friendly = await this.deps.db.sportsFixture.findFirst({
|
||||
where: {
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
startsAt: this.sameKickoff(startsAt),
|
||||
competition: { provider: "FPA", externalId: { endsWith: "-AMIG" } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!friendly) return;
|
||||
const official = await this.deps.db.sportsFixture.findUnique({
|
||||
where: { competitionId_externalId: { competitionId: officialCompetitionId, externalId: officialExternalId } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!official) {
|
||||
await this.deps.db.sportsFixture.update({
|
||||
where: { id: friendly.id },
|
||||
data: { competitionId: officialCompetitionId, externalId: officialExternalId },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (official.id === friendly.id) return;
|
||||
await this.deps.db.event.updateMany({
|
||||
where: { fixtureId: friendly.id },
|
||||
data: { fixtureId: official.id },
|
||||
});
|
||||
await this.deps.db.sportsFixture.delete({ where: { id: friendly.id } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Women's under-17 EHF EURO qualification on eurohandball.com. The whole tournament is stored so the
|
||||
* picker can open Portugal–Italy (and the rest of the weekend) before the nominated sheet is published.
|
||||
* The sheet, when it is out, writes shirt numbers and headshots onto W17 / ITA-W17 / …
|
||||
*/
|
||||
private async applyYouthEuros(now: Date, season: string, result: RefreshResult): Promise<void> {
|
||||
const { db, log } = this.deps;
|
||||
let matches: Awaited<ReturnType<EhfProvider["euroCupMenMatches"]>>;
|
||||
try {
|
||||
matches = await this.ehf.euroCupMenMatches(EHF_W17_EURO.competitionId, EHF_W17_EURO.contentId);
|
||||
} catch (err) {
|
||||
result.errors.push(`ehf w17: ${(err as Error).message}`);
|
||||
return;
|
||||
}
|
||||
const listed = matches.flatMap((m) => {
|
||||
const home = youthNationalTeam(m.homeNation, EHF_W17_EURO.side);
|
||||
const away = youthNationalTeam(m.awayNation, EHF_W17_EURO.side);
|
||||
if (!home || !away) return [];
|
||||
return [{ match: m, home, away }];
|
||||
});
|
||||
if (!listed.length) return;
|
||||
const comp = await db.sportsCompetition.upsert({
|
||||
where: { provider_externalId: { provider: "FPA", externalId: EHF_W17_EURO.externalId } },
|
||||
create: {
|
||||
provider: "FPA",
|
||||
externalId: EHF_W17_EURO.externalId,
|
||||
sport: "andebol",
|
||||
name: EHF_W17_EURO.name,
|
||||
gender: EHF_W17_EURO.gender,
|
||||
season,
|
||||
},
|
||||
update: { name: EHF_W17_EURO.name, gender: EHF_W17_EURO.gender, season },
|
||||
});
|
||||
for (const row of listed) {
|
||||
const homeTeamId = await this.upsertTeam("FPA", row.home);
|
||||
const awayTeamId = await this.upsertTeam("FPA", row.away);
|
||||
await this.foldYouthFriendly(comp.id, row.match.matchId, homeTeamId, awayTeamId, row.match.startsAt);
|
||||
result.fixtures += await this.saveFixture(comp, "FPA", {
|
||||
externalId: row.match.matchId,
|
||||
competition: EHF_W17_EURO.externalId,
|
||||
season,
|
||||
home: row.home,
|
||||
away: row.away,
|
||||
startsAt: row.match.startsAt,
|
||||
timeKnown: true,
|
||||
round: youthEuroRound(row.match.round, row.match.group),
|
||||
venue: row.match.venue,
|
||||
city: row.match.city,
|
||||
});
|
||||
}
|
||||
const due = listed.filter((row) => Math.abs(row.match.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
|
||||
for (const row of due) {
|
||||
if (this.deps.ehfDelayMs) await new Promise((r) => setTimeout(r, this.deps.ehfDelayMs));
|
||||
let sheet: Awaited<ReturnType<EhfProvider["nationalSheet"]>>;
|
||||
try {
|
||||
sheet = await this.ehf.nationalSheet(row.match.matchId);
|
||||
} catch (err) {
|
||||
result.errors.push(`ehf w17 sheet ${row.match.matchId}: ${(err as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
if (!sheet) continue;
|
||||
const sides = [
|
||||
{ nation: sheet.homeNation, players: sheet.home },
|
||||
{ nation: sheet.awayNation, players: sheet.away },
|
||||
];
|
||||
for (const side of sides) {
|
||||
const team = youthNationalTeam(side.nation, EHF_W17_EURO.side);
|
||||
if (!team) continue;
|
||||
const teamId = await this.upsertTeam("FPA", team);
|
||||
const field = side.players.filter((p) => p.position !== "Equipa técnica");
|
||||
result.players += await this.mergeNationalSheet(teamId, season, field, []);
|
||||
await this.fillNationalPhotos(teamId, season);
|
||||
}
|
||||
log.info(
|
||||
{ matchId: row.match.matchId, home: sheet.homeNation, away: sheet.awayNation, players: sheet.home.length + sheet.away.length },
|
||||
"sports: w17 sheet",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write EHF sheet players onto a national team. For Portugal, keep the CIPA from the FPA call-up when the
|
||||
* name matches; still take the shirt number and headshot from the sheet.
|
||||
@@ -1815,6 +1976,13 @@ export class SportsService {
|
||||
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, database connection closed");
|
||||
return { created: 0, updated: 0, headshots: 0 };
|
||||
}
|
||||
// The Postgres server is at max_connections and only SUPERUSER slots remain (P2037): every remaining query
|
||||
// would fail the same way, so stop this sync and let the next scheduled run retry once a slot frees —
|
||||
// rejecting to the archive caller's warn pages the error loop for a transient blip (BIT-33538).
|
||||
if (isPrismaTooManyConnections(err)) {
|
||||
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, too many database connections");
|
||||
return { created: 0, updated: 0, headshots: 0 };
|
||||
}
|
||||
throw err;
|
||||
}),
|
||||
);
|
||||
@@ -1858,6 +2026,12 @@ export class SportsService {
|
||||
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, database unreachable");
|
||||
return result;
|
||||
}
|
||||
// The Postgres server is at max_connections (P2037): stop the sync and let the next scheduled run retry
|
||||
// once a slot frees — a warn per team pages the error loop for a transient blip (BIT-33538).
|
||||
if (isPrismaTooManyConnections(err)) {
|
||||
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, too many database connections");
|
||||
return result;
|
||||
}
|
||||
// Same not-yet-published 400 as importLigaSquads/backfillLigaRegister: expected, kept out of the error hub.
|
||||
if (err instanceof ProviderHttpError && err.status === 400)
|
||||
log.info({ err, team: team.id }, "sports: liga squad not published yet for this team");
|
||||
@@ -2550,6 +2724,8 @@ export class SportsWorker {
|
||||
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction rolled back (connection blip or deadlock)");
|
||||
} else if (isPrismaTransactionTimeout(err)) {
|
||||
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction start timed out (pool contention)");
|
||||
} else if (isPgClientNotQueryable(err)) {
|
||||
this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, pooled pg client was not queryable (connection blip)");
|
||||
} else {
|
||||
this.opts.log.warn({ err }, "sports: tick failed");
|
||||
}
|
||||
@@ -2572,7 +2748,11 @@ export class SportsWorker {
|
||||
}
|
||||
if (!this.stopped && saved >= 0 && this.opts.afterRegister) await this.opts.afterRegister();
|
||||
} catch (err) {
|
||||
this.opts.log.warn({ err }, "sports: register not filled");
|
||||
if (isPgClientNotQueryable(err)) {
|
||||
this.opts.log.info({ err: (err as Error).message }, "sports: register not filled, pooled pg client was not queryable (connection blip)");
|
||||
} else {
|
||||
this.opts.log.warn({ err }, "sports: register not filled");
|
||||
}
|
||||
} finally {
|
||||
this.filling = false;
|
||||
}
|
||||
|
||||
+11
-2
@@ -16,7 +16,8 @@ import { RenderPool, RenderProcess } from "./develop/engine.js";
|
||||
import { DevelopService, RenderWorker } from "./develop/service.js";
|
||||
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
|
||||
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
||||
import { ensureCloudM19Target } 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 { SportsService, SportsWorker } from "./sports/service.js";
|
||||
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
|
||||
@@ -176,7 +177,15 @@ const sports = config.SPORTS_SYNC === "on"
|
||||
})
|
||||
: 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
|
||||
// one-shot targets. Log at info so the reporter hook (warn+) does not page the error loop (BIT-33558).
|
||||
const ensureCloudTarget = (fn: Promise<number>, name: string) =>
|
||||
fn.catch((err) => {
|
||||
if (isPrismaTooManyConnections(err)) log.info({ err: (err as Error).message }, `delivery: ${name} profile not created, too many database connections`);
|
||||
else log.warn({ err }, `delivery: ${name} profile not created`);
|
||||
});
|
||||
ensureCloudTarget(ensureCloudM19Target(db), "Cloud M19");
|
||||
ensureCloudTarget(ensureCloudW17Target(db), "Cloud W17");
|
||||
scanner.start();
|
||||
if (secrets) archive.start();
|
||||
autopilot.start();
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
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";
|
||||
|
||||
let ctx: TestContext;
|
||||
@@ -16,6 +19,24 @@ describe("health", () => {
|
||||
const res = await ctx.app.inject({ method: "GET", url: "/health" });
|
||||
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", () => {
|
||||
|
||||
@@ -40,22 +40,40 @@ describe("capacity", () => {
|
||||
});
|
||||
|
||||
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", () => {
|
||||
// 100 - 3 superuser reserved - ((2 api instances + 1 reload overlap) * (10 pool + 3 realtime)) - 1 broadcaster - 10 headroom = 47.
|
||||
expect(dbConnectionBudget(500)).toBe(47);
|
||||
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 + 1 reload) * (10 pool + 3 realtime)) - 10 headroom = 48.
|
||||
// Divide by (1 + 1 worker overlap) = 24, minus 1 broadcaster = 23.
|
||||
expect(dbConnectionBudget(500)).toBe(23);
|
||||
expect(dbConnectionBudget(10)).toBe(10);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it("can be told a deploy never overlaps instances (e.g. a non-cluster or single-instance API)", () => {
|
||||
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(60);
|
||||
it("can be told a deploy never overlaps API instances (e.g. a non-cluster or single-instance API)", () => {
|
||||
// 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", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -75,6 +75,8 @@ class FakeNextcloud {
|
||||
class FakeZerozero {
|
||||
logins = 0;
|
||||
removed: string[] = [];
|
||||
/** Paths of POST /api/photo-sync/… after each upload (the public game, not only the desk). */
|
||||
syncs: string[] = [];
|
||||
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
|
||||
password = "zz-pass";
|
||||
|
||||
@@ -129,6 +131,10 @@ class FakeZerozero {
|
||||
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
|
||||
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
|
||||
}
|
||||
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) {
|
||||
this.syncs.push(url.pathname);
|
||||
return Response.json({ synced: 1, failed: 0, failures: [] });
|
||||
}
|
||||
const gone = /^\/api\/images\/(.+)$/.exec(url.pathname);
|
||||
if (gone && method === "DELETE") {
|
||||
this.removed.push(gone[1]!);
|
||||
@@ -622,6 +628,8 @@ describe("delivery", () => {
|
||||
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark / Kapta+", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
|
||||
expect(first.data.length).toBe(first.length);
|
||||
expect((await sharp(first.data).metadata()).width).toBe(3000);
|
||||
// The desk upload is not the public game: each photo is published there before the delivery is done.
|
||||
expect(zz.syncs).toEqual(["/api/photo-sync/img-1", "/api/photo-sync/img-2"]);
|
||||
// Signed in once for the whole batch.
|
||||
expect(zz.logins).toBe(1);
|
||||
|
||||
@@ -644,6 +652,7 @@ describe("delivery", () => {
|
||||
expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]);
|
||||
// Same name ({n} kept), shown once in the game.
|
||||
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
|
||||
expect(zz.syncs.at(-1)).toBe(`/api/photo-sync/${resent.remotePath!.split("/")[1]}`);
|
||||
expect(await delivery.queueEdited()).toBe(0);
|
||||
|
||||
// A reject that bypassed the library PATCH (flag flipped in the DB) is still taken back on the next sweep.
|
||||
@@ -842,6 +851,32 @@ describe("delivery", () => {
|
||||
expect(broadcaster.sent.filter((s) => s.message.type === "delivery.updated").map((s) => (s.message as { item: { status: string } }).item.status)).toEqual(["QUEUED", "QUEUED", "FAILED", "DONE"]);
|
||||
});
|
||||
|
||||
it("retry is idempotent when the item leaves FAILED between render and click (BIT-33418)", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("race.jpg", "2026:09:23 21:10:00");
|
||||
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: [id], again: false, requestedById: (await ctx.db.user.findFirstOrThrow()).id });
|
||||
const [claimed] = await delivery.claim(5);
|
||||
nc.status = 401;
|
||||
expect(await delivery.process(claimed!)).toMatchObject({ status: "FAILED", attempts: 1 });
|
||||
nc.status = undefined;
|
||||
|
||||
// Between the desktop rendering the FAILED row and the user clicking "Repetir", the queue worker
|
||||
// requeued the item (autopilot, queueEdited, queueOrphanRetracts, …) so it is no longer FAILED.
|
||||
const itemId = (await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } })).id;
|
||||
await ctx.db.deliveryItem.update({ where: { id: itemId }, data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null } });
|
||||
|
||||
// The retry must not 404 — it returns the current state, so the desktop's promise resolves and no
|
||||
// unhandledrejection reaches the error hub.
|
||||
const retry = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${itemId}/retry`, headers: bearer(token) });
|
||||
expect(retry.statusCode).toBe(200);
|
||||
expect(retry.json()).toMatchObject({ id: itemId, status: "QUEUED", attempts: 0 });
|
||||
|
||||
// A truly missing item still 404s.
|
||||
const ghost = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/00000000-0000-4000-8000-000000000000/retry`, headers: bearer(token) });
|
||||
expect(ghost.statusCode).toBe(404);
|
||||
expect(ghost.json()).toMatchObject({ error: "item_not_found" });
|
||||
});
|
||||
|
||||
it("writes long venues whole in IIM and XMP, flagged as UTF-8", async () => {
|
||||
const src = path.join(dir, "src.jpg");
|
||||
await writeFile(src, await sharp({ create: { width: 300, height: 200, channels: 3, background: "#123456" } }).jpeg().toBuffer());
|
||||
|
||||
@@ -91,7 +91,7 @@ describe("errors to errors.bitreport.pt", () => {
|
||||
expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" });
|
||||
});
|
||||
|
||||
it("does not report transient PostgreSQL shutdown/restart 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 reporter = reporterWith(hub.fetchImpl);
|
||||
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("Can't reach database server at localhost:5432", "P1001") }, "db unreachable");
|
||||
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");
|
||||
await reporter.flush();
|
||||
const events = hub.sent.flatMap((s) => s.events);
|
||||
|
||||
@@ -733,6 +733,28 @@ describe("sports data service", () => {
|
||||
log: quiet,
|
||||
fetch: (async (url, init) => {
|
||||
const u = String(url);
|
||||
if (u.includes("GetStandingMatches") && u.includes("contentId=139009"))
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
matches: [
|
||||
{
|
||||
matchID: "202712010502014",
|
||||
venue: {
|
||||
date: { utc: kick.toISOString() },
|
||||
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
|
||||
},
|
||||
homeTeam: { team: { nationAbbreviation: "POR" } },
|
||||
guestTeam: { team: { nationAbbreviation: "ITA" } },
|
||||
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
|
||||
},
|
||||
],
|
||||
rounds: [],
|
||||
}),
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
if (u.includes("GetStandingMatches"))
|
||||
return {
|
||||
ok: true,
|
||||
@@ -751,6 +773,45 @@ describe("sports data service", () => {
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
if (u.includes("GetMatchDetails") && u.includes("202712010502014"))
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
matchDetails: {
|
||||
details: {
|
||||
homeTeam: {
|
||||
team: { nationAbbreviation: "POR" },
|
||||
players: [
|
||||
{
|
||||
id: "ehf-w17-costa",
|
||||
shirtNumber: "7",
|
||||
playingPosition: "Centre Back",
|
||||
person: { firstName: "Maria", lastName: "Costa", nationAbbreviation: "POR" },
|
||||
newPhoto: { w512: "https://res.ehf.eu/photo/w17-costa.jpg" },
|
||||
},
|
||||
],
|
||||
officials: [],
|
||||
},
|
||||
guestTeam: {
|
||||
team: { nationAbbreviation: "ITA" },
|
||||
players: [
|
||||
{
|
||||
id: "ehf-w17-rossi",
|
||||
shirtNumber: "9",
|
||||
playingPosition: "Left Wing",
|
||||
person: { firstName: "Giulia", lastName: "Rossi", nationAbbreviation: "ITA" },
|
||||
newPhoto: { w512: "https://res.ehf.eu/photo/w17-rossi.jpg" },
|
||||
},
|
||||
],
|
||||
officials: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
if (u.includes("GetMatchDetails") && u.includes("202811130101002"))
|
||||
return {
|
||||
ok: true,
|
||||
@@ -848,6 +909,85 @@ describe("sports data service", () => {
|
||||
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
|
||||
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
|
||||
expect(friendly?.city).toBe("Caminha");
|
||||
const w17 = await ctx.db.sportsFixture.findFirst({
|
||||
where: { externalId: "202712010502014" },
|
||||
include: { homeTeam: true, awayTeam: true, competition: true },
|
||||
});
|
||||
expect(w17?.competition.name).toBe("W17 EHF EURO");
|
||||
expect(w17?.competition.gender).toBe("F");
|
||||
expect(w17?.round).toBe("Qualificação C");
|
||||
expect(w17?.venue).toBe("Pavilhão da Associação Atlética de Águas Santas");
|
||||
expect(w17?.city).toBe("Àguas Santas");
|
||||
expect(w17?.homeTeam.externalId).toBe("W17");
|
||||
expect(w17?.homeTeam.name).toBe("Portugal");
|
||||
expect(w17?.awayTeam.externalId).toBe("ITA-W17");
|
||||
expect(w17?.awayTeam.name).toBe("Itália");
|
||||
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.homeTeam.id, name: "Maria Costa" } })).toMatchObject({
|
||||
number: "7",
|
||||
photoUrl: "https://res.ehf.eu/photo/w17-costa.jpg",
|
||||
});
|
||||
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.awayTeam.id, name: "Giulia Rossi" } })).toMatchObject({
|
||||
number: "9",
|
||||
externalId: "ehf-w17-rossi",
|
||||
});
|
||||
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "w17dup", role: "OWNER" });
|
||||
const friendlyComp = await ctx.db.sportsCompetition.create({
|
||||
data: { provider: "FPA", externalId: "W17-AMIG", sport: "andebol", name: "Sub-17 feminina", gender: "F", season: w17!.season },
|
||||
});
|
||||
const duplicate = await ctx.db.sportsFixture.create({
|
||||
data: {
|
||||
competitionId: friendlyComp.id,
|
||||
externalId: "w17-por-ita-20261127",
|
||||
season: w17!.season,
|
||||
homeTeamId: w17!.homeTeam.id,
|
||||
awayTeamId: w17!.awayTeam.id,
|
||||
startsAt: w17!.startsAt,
|
||||
timeKnown: true,
|
||||
round: "Particular",
|
||||
},
|
||||
});
|
||||
const opened = await ctx.db.event.create({
|
||||
data: {
|
||||
organizationId: org!.id,
|
||||
home: "Portugal",
|
||||
away: "Itália",
|
||||
startsAt: w17!.startsAt,
|
||||
ingestFrom: w17!.startsAt,
|
||||
ingestUntil: w17!.startsAt,
|
||||
iptcTemplate: {},
|
||||
fixtureId: duplicate.id,
|
||||
},
|
||||
});
|
||||
await sports.syncNationalCallUps(kick);
|
||||
const paired = await ctx.db.sportsFixture.findMany({
|
||||
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
|
||||
});
|
||||
expect(paired.map((row) => row.externalId)).toEqual(["202712010502014"]);
|
||||
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(w17!.id);
|
||||
|
||||
await ctx.db.sportsFixture.delete({ where: { id: w17!.id } });
|
||||
const campOnly = await ctx.db.sportsFixture.create({
|
||||
data: {
|
||||
competitionId: friendlyComp.id,
|
||||
externalId: "w17-por-ita-20261127",
|
||||
season: w17!.season,
|
||||
homeTeamId: w17!.homeTeam.id,
|
||||
awayTeamId: w17!.awayTeam.id,
|
||||
startsAt: w17!.startsAt,
|
||||
timeKnown: true,
|
||||
round: "Particular",
|
||||
},
|
||||
});
|
||||
await ctx.db.event.update({ where: { id: opened.id }, data: { fixtureId: campOnly.id } });
|
||||
await sports.syncNationalCallUps(kick);
|
||||
const adopted = await ctx.db.sportsFixture.findMany({
|
||||
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
|
||||
include: { competition: true },
|
||||
});
|
||||
expect(adopted).toHaveLength(1);
|
||||
expect(adopted[0]).toMatchObject({ id: campOnly.id, externalId: "202712010502014", competition: { name: "W17 EHF EURO" } });
|
||||
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(campOnly.id);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AutopilotSettings } from "@photoreport/contracts";
|
||||
import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js";
|
||||
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, picksNeeded, type BurstExportSlot } from "../src/autopilot/targets.js";
|
||||
|
||||
const a = "11111111-1111-4111-8111-111111111111";
|
||||
const b = "22222222-2222-4222-8222-222222222222";
|
||||
@@ -17,6 +17,62 @@ describe("exportTargets", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function slot(targetId: string, extra: Partial<BurstExportSlot> = {}): BurstExportSlot {
|
||||
return {
|
||||
targetId,
|
||||
alsoTargetIds: [],
|
||||
count: null,
|
||||
originals: false,
|
||||
sent: 0,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
describe("exportSlots", () => {
|
||||
it("keeps a copy on the same frame and out of the pick list", () => {
|
||||
const settings = AutopilotSettings.parse({
|
||||
enabled: true,
|
||||
deliverExports: [
|
||||
{ targetId: a, alsoTargetIds: [b], count: 50, originals: false },
|
||||
{ targetId: c, alsoTargetIds: [], count: null, originals: true },
|
||||
],
|
||||
});
|
||||
expect(exportSlots(settings)).toEqual([
|
||||
{ targetId: a, alsoTargetIds: [b], count: 50, originals: false },
|
||||
{ targetId: c, alsoTargetIds: [], count: null, originals: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assignBurstExports", () => {
|
||||
const three = [slot(a), slot(b), slot(c)];
|
||||
|
||||
it("gives one different frame to each destination when the burst has enough", () => {
|
||||
expect(assignBurstExports(three, 0, 3).map((row) => row.targetId)).toEqual([a, b, c]);
|
||||
});
|
||||
|
||||
it("rotates the only frame so a short burst does not always feed the first destination", () => {
|
||||
expect(assignBurstExports(three, 0, 1).map((row) => row.targetId)).toEqual([a]);
|
||||
expect(assignBurstExports(three, 1, 1).map((row) => row.targetId)).toEqual([b]);
|
||||
expect(assignBurstExports(three, 2, 1).map((row) => row.targetId)).toEqual([c]);
|
||||
expect(assignBurstExports(three, 3, 1).map((row) => row.targetId)).toEqual([a]);
|
||||
});
|
||||
|
||||
it("stops a destination that already has its total and keeps filling the others", () => {
|
||||
const slots = [slot(a, { count: 20, sent: 20 }), slot(b, { count: 80, sent: 20 }), slot(c)];
|
||||
expect(assignBurstExports(slots, 0, 2).map((row) => row.targetId)).toEqual([b, c]);
|
||||
});
|
||||
|
||||
it("sends the same frame's copy alongside, without taking a second frame", () => {
|
||||
const slots = [slot(a, { alsoTargetIds: [b] }), slot(c)];
|
||||
const plan = assignBurstExports(slots, 0, 2);
|
||||
expect(plan).toEqual([
|
||||
{ targetId: a, alsoTargetIds: [b], originals: false, rank: 0 },
|
||||
{ targetId: c, alsoTargetIds: [], originals: false, rank: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("picksNeeded", () => {
|
||||
it("matches the number of exports when set", () => {
|
||||
const s = AutopilotSettings.parse({ enabled: true, deliverTargetIds: [a, b, c] });
|
||||
|
||||
@@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
|
||||
/** Pure tests. The default config migrates a database, which these do not need. */
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/**/*.test.ts", "test/compose.test.ts"],
|
||||
include: ["src/**/*.test.ts", "test/capacity.test.ts", "test/compose.test.ts"],
|
||||
fileParallelism: false,
|
||||
},
|
||||
});
|
||||
@@ -578,6 +578,14 @@ export const t = {
|
||||
noPicks: "Não escolher",
|
||||
minLongEdge: "Resolução mínima do recorte",
|
||||
deliver: "Enviar as escolhidas para",
|
||||
exportAdd: "Acrescentar envio",
|
||||
exportRemove: "Tirar",
|
||||
exportAlso: "A mesma foto também para",
|
||||
exportCount: "Total neste jogo",
|
||||
exportOriginals: "Originais, sem edição",
|
||||
exportHelp:
|
||||
"Há tantos escolhidos por sequência quantos os envios: uma foto diferente para cada um. Se a sequência não chegar para todos, a que houver vai rodando, para no fim cada destino chegar ao total que pediste. Vazio nesse total: uma por sequência, até ao fim. «Também para» manda a mesma foto aos dois (Cofina Direto e Cofina Arquivo) e não conta como outra escolha. Originais sai o ficheiro da câmara, sem o recorte nem o tom.",
|
||||
exportPlayers: "Um destino com «Esperar pelas caras» sai com os jogadores no ficheiro. Se os nomes chegarem depois, o ficheiro volta a ser enviado.",
|
||||
noDelivery: "Não enviar",
|
||||
selection: "O que enviar",
|
||||
selectionBursts: "As escolhidas de cada sequência",
|
||||
@@ -713,7 +721,7 @@ export const t = {
|
||||
startsAt: "Início",
|
||||
photographers: "Fotógrafos",
|
||||
pickMatch: "Escolher o jogo",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções), W17 EHF EURO (qualificação de sub-17 feminina) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
|
||||
squadFromMatch: "Usar o plantel de um jogo",
|
||||
squadFromMatchHelp: "Treino ou sessão: fica com os jogadores desse jogo, sem ser o jogo (legenda e hora são as tuas).",
|
||||
searchMatch: "Equipa, competição ou pavilhão",
|
||||
|
||||
@@ -4,6 +4,153 @@ import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { ZerozeroGamePicker } from "./ZerozeroGame.js";
|
||||
|
||||
type ExportRow = AutopilotSettings["deliverExports"][number];
|
||||
|
||||
/** As many burst exports as the photographer lists. One frame each; a copy shares that frame. */
|
||||
function BurstExports(props: {
|
||||
settings: AutopilotSettings;
|
||||
targets: DeliveryTarget[];
|
||||
canEdit: boolean;
|
||||
onChange: (next: AutopilotSettings) => void;
|
||||
}) {
|
||||
const L = t.autopilot;
|
||||
const rows = props.settings.deliverExports;
|
||||
const used = new Set<string>();
|
||||
for (const row of rows) {
|
||||
used.add(row.targetId);
|
||||
for (const id of row.alsoTargetIds) used.add(id);
|
||||
}
|
||||
|
||||
const commit = (nextRows: ExportRow[]) => {
|
||||
const primaries: string[] = [];
|
||||
for (const row of nextRows) primaries.push(row.targetId);
|
||||
props.onChange({
|
||||
...props.settings,
|
||||
deliverExports: nextRows,
|
||||
deliverTargetIds: primaries,
|
||||
deliverTargetId: primaries[0] ?? null,
|
||||
});
|
||||
};
|
||||
|
||||
const update = (index: number, row: ExportRow) => {
|
||||
const next = rows.map((item) => ({ ...item, alsoTargetIds: [...item.alsoTargetIds] }));
|
||||
next[index] = row;
|
||||
commit(next);
|
||||
};
|
||||
|
||||
const add = () => {
|
||||
let free = "";
|
||||
for (const target of props.targets) {
|
||||
if (!used.has(target.id)) {
|
||||
free = target.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!free) return;
|
||||
commit([...rows, { targetId: free, alsoTargetIds: [], count: null, originals: false }]);
|
||||
};
|
||||
|
||||
const remove = (index: number) => {
|
||||
commit(rows.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="text-faint">{L.exportHelp}</p>
|
||||
{rows.map((row, index) => {
|
||||
const also = row.alsoTargetIds[0] ?? "";
|
||||
return (
|
||||
<div key={`${row.targetId}-${index}`} className="space-y-1 border border-line p-1.5">
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{index + 1}</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<select
|
||||
className="h-6 max-w-[160px] border border-black bg-cell px-1"
|
||||
disabled={!props.canEdit}
|
||||
value={row.targetId}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (!value) return;
|
||||
const alsoIds = row.alsoTargetIds.filter((id) => id !== value);
|
||||
update(index, { ...row, targetId: value, alsoTargetIds: alsoIds });
|
||||
}}
|
||||
>
|
||||
{props.targets.map((target) => {
|
||||
if (used.has(target.id) && target.id !== row.targetId && target.id !== also) return null;
|
||||
return (
|
||||
<option key={target.id} value={target.id}>
|
||||
{target.name}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
<button type="button" className="text-faint hover:text-ink" disabled={!props.canEdit} onClick={() => remove(index)}>
|
||||
{L.exportRemove}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="text-faint">{L.exportAlso}</span>
|
||||
<select
|
||||
className="h-6 max-w-[160px] border border-black bg-cell px-1"
|
||||
disabled={!props.canEdit}
|
||||
value={also}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (!value) update(index, { ...row, alsoTargetIds: [] });
|
||||
else update(index, { ...row, alsoTargetIds: [value] });
|
||||
}}
|
||||
>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((target) => {
|
||||
if (target.id === row.targetId) return null;
|
||||
if (used.has(target.id) && target.id !== also) return null;
|
||||
return (
|
||||
<option key={target.id} value={target.id}>
|
||||
{target.name}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="text-faint">{L.exportCount}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={2000}
|
||||
disabled={!props.canEdit}
|
||||
value={row.count ?? ""}
|
||||
placeholder="—"
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value.trim();
|
||||
let count: number | null = null;
|
||||
if (raw) count = Math.max(1, Math.min(2000, Number(raw) || 1));
|
||||
update(index, { ...row, count });
|
||||
}}
|
||||
className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink"
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={!props.canEdit}
|
||||
checked={row.originals}
|
||||
onChange={(e) => update(index, { ...row, originals: e.target.checked })}
|
||||
/>
|
||||
<span>{L.exportOriginals}</span>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<button type="button" className="pr-quiet" disabled={!props.canEdit || used.size >= props.targets.length} onClick={add}>
|
||||
{L.exportAdd}
|
||||
</button>
|
||||
<p className="text-faint">{L.exportPlayers}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest
|
||||
* are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered.
|
||||
@@ -30,9 +177,12 @@ export function AutopilotButton(props: {
|
||||
}, [props.autopilotAsk, props.event.id, props.onAsked]);
|
||||
|
||||
const save = async (next: AutopilotSettings) => {
|
||||
// Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list).
|
||||
const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x);
|
||||
const synced = { ...next, deliverTargetIds: ids.length ? ids : next.deliverTargetIds ?? [] };
|
||||
// Burst groups already name every destination. The two legacy slots must not wipe that list.
|
||||
let synced = next;
|
||||
if (next.selection !== "bursts" || next.deliverExports.length === 0) {
|
||||
const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x);
|
||||
if (ids.length > 0) synced = { ...next, deliverTargetIds: ids };
|
||||
}
|
||||
setS(synced);
|
||||
setState("saving");
|
||||
try {
|
||||
@@ -59,7 +209,7 @@ export function AutopilotButton(props: {
|
||||
{L.button}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute right-0 top-7 z-30 w-[360px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
|
||||
<div className="absolute right-0 top-7 z-30 w-[420px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="font-semibold uppercase tracking-wide text-ink">{L.button}</span>
|
||||
<input type="checkbox" disabled={!props.canEdit} checked={s.enabled} onChange={(e) => void save({ ...s, enabled: e.target.checked })} aria-label={L.enable} />
|
||||
@@ -110,17 +260,22 @@ export function AutopilotButton(props: {
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.deliver}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{s.selection === "bursts" && (
|
||||
<BurstExports settings={s} targets={props.targets} canEdit={props.canEdit && s.enabled} onChange={(next) => void save(next)} />
|
||||
)}
|
||||
{s.selection !== "bursts" && (
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.deliver}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.selection}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.selection} onChange={(e) => void save({ ...s, selection: e.target.value as AutopilotSettings["selection"] })}>
|
||||
|
||||
@@ -139,6 +139,13 @@ const PRESETS = {
|
||||
longEdge: 4000,
|
||||
...DESTINATION_EXAMPLES.fpaM19,
|
||||
},
|
||||
fpaW17: {
|
||||
label: "Cloud W17",
|
||||
kind: "NEXTCLOUD",
|
||||
baseUrl: "https://cloud.photoreport.pt",
|
||||
longEdge: 4000,
|
||||
...DESTINATION_EXAMPLES.fpaW17,
|
||||
},
|
||||
liga: {
|
||||
label: "Estrutura Liga",
|
||||
kind: "NEXTCLOUD",
|
||||
|
||||
@@ -14,6 +14,17 @@ import { kv } from "./kv.js";
|
||||
import { localPhotos } from "./local.js";
|
||||
import { localId, offlineQueue } from "./queue.js";
|
||||
|
||||
/** One pick per export group, otherwise the event's own number. Matches the server. */
|
||||
function picksFor(settings: AutopilotSettings): number {
|
||||
if (settings.deliverExports.length > 0) {
|
||||
return Math.min(10, settings.deliverExports.length);
|
||||
}
|
||||
if (settings.deliverTargetIds.length > 0) {
|
||||
return Math.min(5, settings.deliverTargetIds.length);
|
||||
}
|
||||
return settings.picksPerBurst;
|
||||
}
|
||||
|
||||
/** Same settle window as the server: a burst is decided once no new frame has arrived for this long. */
|
||||
const BURST_SETTLE_MS = 15_000;
|
||||
const PENDING_KEY = (orgId: string, eventId: string) => `autopilot:pending:${orgId}:${eventId}`;
|
||||
@@ -98,7 +109,7 @@ export async function planLocalAutopilot(args: {
|
||||
const pending = await loadPending(args.orgId, args.event.id);
|
||||
const next = [...pending.filter((f) => f.sha256 !== frame.sha256), frame];
|
||||
await savePending(args.orgId, args.event.id, next);
|
||||
scheduleSettle(args.orgId, args.event.id, settings.picksPerBurst, settings.burstGapSec * 1000);
|
||||
scheduleSettle(args.orgId, args.event.id, picksFor(settings), settings.burstGapSec * 1000);
|
||||
}
|
||||
|
||||
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
|
||||
@@ -136,7 +136,7 @@ export function DeliveryPage() {
|
||||
</td>
|
||||
<td className="border-b border-line px-3 py-1.5 text-right">
|
||||
{i.status === "FAILED" && (
|
||||
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
|
||||
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load, () => load())}>
|
||||
{t.retry}
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -12,9 +12,9 @@ What the shell adds today:
|
||||
- Refresh token in the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service).
|
||||
Without a keychain the session stays in memory and ends when the app closes.
|
||||
- Local FTP server for cameras (`src/ftp.rs`, Library → **FTP local**). See below.
|
||||
- USB tether (`src/camera.rs` + `camera_mac.m`, Library → **USB**): pulses the PTP session so the body stays
|
||||
shootable (no permanent computer/busy screen), pulls new shots to the open event, syncs the clock. EOS Utility
|
||||
must not hold the cable.
|
||||
- USB tether (Library → **USB**): a short PTP session lists the card and downloads what was asked, then
|
||||
closes so the body can shoot. macOS uses Image Capture (`camera_mac.m`). Linux uses libgphoto2. Windows uses
|
||||
the portable-device API. EOS Utility must not hold the cable. The Mac build is the one that sets the camera clock.
|
||||
- Local catalogue (`src/catalog.rs`, Preferências → **Catálogo local**). See below.
|
||||
- Works without network: when the server can't be reached at start-up, the window opens the copy of the web app
|
||||
bundled in the installer (photo engine included), so the catalogue, local FTP and editing originals on disk go on;
|
||||
@@ -41,7 +41,9 @@ signed shell at once; the API reads the latest
|
||||
installer through, so the private repository stays private. Installers are signed with the release key
|
||||
(`tauri signer generate`): the private key and its password are the Gitea secrets `TAURI_SIGNING_PRIVATE_KEY` and
|
||||
`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`, the public key is the variable `TAURI_UPDATER_PUBKEY` (compiled into the app
|
||||
as `PHOTOREPORT_UPDATER_PUBKEY`). A build without the public key never updates itself.
|
||||
as `PHOTOREPORT_UPDATER_PUBKEY`). A release build also reads that same public key from `updater-pubkey.txt` when the
|
||||
variable is unset, and checks again in the background, so the installed app replaces itself. A debug build without
|
||||
the variable never updates itself.
|
||||
|
||||
## Local FTP (camera → this computer → event)
|
||||
|
||||
|
||||
Generated
+9256
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,13 @@ description = "PhotoReport desktop: the web app in a native shell, with keychain
|
||||
name = "photoreport_desktop_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
# Production serves the interface from this computer. Without this feature Tauri treats every
|
||||
# build as development and the window opens http://localhost:5173, which stays blank unless
|
||||
# `tauri dev` is running. `tauri dev` turns the feature off and uses the dev server.
|
||||
[features]
|
||||
default = ["custom-protocol"]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
cc = "1"
|
||||
@@ -44,6 +51,21 @@ rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
[target.'cfg(all(target_os = "macos", target_arch = "aarch64"))'.dependencies]
|
||||
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "download-binaries", "copy-dylibs", "api-31", "tls-native", "coreml"] }
|
||||
|
||||
# Linux USB: libgphoto2 (PTP). The Mac build keeps Image Capture and does not link this.
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
gphoto2 = "=3.4.1"
|
||||
|
||||
# Windows USB: the portable-device API, which speaks PTP through the driver Windows already loaded.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows = { version = "0.61", features = [
|
||||
"Win32_Devices_PortableDevices",
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Variant",
|
||||
] }
|
||||
|
||||
# Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells
|
||||
# a disassembler what machine code does, not what the functions were called.
|
||||
[profile.release]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
fn main() {
|
||||
publish_updater_key();
|
||||
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
||||
if target == "macos" {
|
||||
// ImageCaptureCore: PTP cameras (they never mount as a volume).
|
||||
@@ -87,6 +88,27 @@ fn main() {
|
||||
link_coreml_compiler_rt();
|
||||
}
|
||||
|
||||
/// Release builds always carry the official update key, so an installed app can replace itself from the API.
|
||||
/// `option_env!` is not a cargo fingerprint: the key has to be passed with `cargo:rustc-env` or a later compile
|
||||
/// keeps the previous value. A debug build stays without it unless the variable is set for that compile.
|
||||
fn publish_updater_key() {
|
||||
println!("cargo:rerun-if-env-changed=PHOTOREPORT_UPDATER_PUBKEY");
|
||||
let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
|
||||
let path = std::path::Path::new(&manifest).join("updater-pubkey.txt");
|
||||
println!("cargo:rerun-if-changed={}", path.display());
|
||||
let from_env = std::env::var("PHOTOREPORT_UPDATER_PUBKEY").unwrap_or_default();
|
||||
let mut key = from_env.trim().to_string();
|
||||
let profile = std::env::var("PROFILE").unwrap_or_default();
|
||||
if key.is_empty() && profile == "release" {
|
||||
let from_file = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
key = from_file.trim().to_string();
|
||||
}
|
||||
if key.is_empty() {
|
||||
return;
|
||||
}
|
||||
println!("cargo:rustc-env=PHOTOREPORT_UPDATER_PUBKEY={key}");
|
||||
}
|
||||
|
||||
/// ONNX Runtime's Core ML objects call `___isPlatformVersionAtLeast`. That helper lives in compiler-rt, which Rust's
|
||||
/// linker does not pull in, so the desktop build (deployment target 11) fails on the arm64 slice.
|
||||
fn link_coreml_compiler_rt() {
|
||||
@@ -96,7 +118,12 @@ fn link_coreml_compiler_rt() {
|
||||
return;
|
||||
}
|
||||
let Ok(output) = std::process::Command::new("xcrun")
|
||||
.args(["--sdk", "macosx", "clang", "-print-file-name=libclang_rt.osx.a"])
|
||||
.args([
|
||||
"--sdk",
|
||||
"macosx",
|
||||
"clang",
|
||||
"-print-file-name=libclang_rt.osx.a",
|
||||
])
|
||||
.output()
|
||||
else {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- The bundled ONNX runtime is not an Apple-signed library. Notarisation requires the hardened runtime, and that runtime refuses the library unless this is set. -->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,13 +1,17 @@
|
||||
//! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore
|
||||
//! (`camera_mac.m`) briefly opens a PTP session to list/download, then closes it so the body can
|
||||
//! shoot (a held session + `requestEnableTethering` put many cameras on the computer/busy screen).
|
||||
//! The session stays off until the photographer turns the cable on. Nothing is copied until they
|
||||
//! pick files (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb` and the
|
||||
//! web app polls `camera_take` to file them like a local-FTP photo.
|
||||
//! USB tether. A PTP body does not show up as a disk.
|
||||
//! macOS uses Image Capture (`camera_mac.m`): a short session lists and downloads, then closes so
|
||||
//! the body can shoot. Linux uses libgphoto2 and Windows the portable-device API (`camera_link`),
|
||||
//! with the same open-then-close rhythm. Nothing is copied until the photographer picks files
|
||||
//! (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "camera_link.rs"]
|
||||
mod link;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::ftp::{FtpState, IncomingFile};
|
||||
@@ -51,7 +55,7 @@ pub struct CameraFile {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CameraStatus {
|
||||
/// False on systems without ImageCaptureCore (the button stays hidden).
|
||||
/// False only when this build has no USB backend (the button stays hidden).
|
||||
pub supported: bool,
|
||||
pub tether: bool,
|
||||
pub devices: Vec<CameraDevice>,
|
||||
@@ -74,7 +78,11 @@ enum CameraEvent {
|
||||
files: Vec<CameraFile>,
|
||||
},
|
||||
#[serde(rename = "file")]
|
||||
File { path: String, name: String, size: u64 },
|
||||
File {
|
||||
path: String,
|
||||
name: String,
|
||||
size: u64,
|
||||
},
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
@@ -111,6 +119,47 @@ fn queue() -> &'static Mutex<Vec<String>> {
|
||||
Q.get_or_init(|| Mutex::new(Vec::new()))
|
||||
}
|
||||
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))]
|
||||
pub(crate) fn enqueue_line(line: String) {
|
||||
if let Ok(mut q) = queue().lock() {
|
||||
q.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// One still on the card, before it is marked new or already fetched.
|
||||
pub(crate) struct ListedShot {
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub created_ms: Option<i64>,
|
||||
}
|
||||
|
||||
/// The first listing of a tether session is the baseline (nothing is "new"). Later listings mark
|
||||
/// names that were not on that baseline. `fetched` is what this computer already copied.
|
||||
pub(crate) fn files_on_card(
|
||||
shots: &[ListedShot],
|
||||
known: &HashSet<String>,
|
||||
fetched: &HashSet<String>,
|
||||
listing_is_live: bool,
|
||||
) -> Vec<CameraFile> {
|
||||
let mut files = Vec::new();
|
||||
for shot in shots {
|
||||
let is_new = if listing_is_live {
|
||||
!known.contains(&shot.name)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let imported = fetched.contains(&shot.name);
|
||||
files.push(CameraFile {
|
||||
name: shot.name.clone(),
|
||||
size: shot.size,
|
||||
created_ms: shot.created_ms,
|
||||
is_new,
|
||||
imported,
|
||||
});
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
impl CameraState {
|
||||
fn drain(&self) {
|
||||
let pending = match queue().lock() {
|
||||
@@ -211,7 +260,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
|
||||
};
|
||||
match event {
|
||||
CameraEvent::Devices { devices } => inner.devices = devices,
|
||||
CameraEvent::Catalog { camera_id: _, files } => {
|
||||
CameraEvent::Catalog {
|
||||
camera_id: _,
|
||||
files,
|
||||
} => {
|
||||
inner.files = files;
|
||||
inner.catalog_gen = inner.catalog_gen.wrapping_add(1);
|
||||
}
|
||||
@@ -223,16 +275,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn supported() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn supported() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe extern "C" fn on_camera_json(json: *const std::ffi::c_char) {
|
||||
use std::ffi::CStr;
|
||||
@@ -266,7 +312,9 @@ fn set_download_dir(dir: &str) {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn set_download_dir(_dir: &str) {}
|
||||
fn set_download_dir(dir: &str) {
|
||||
link::set_dir(dir);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_tether_native(on: bool) {
|
||||
@@ -274,7 +322,9 @@ fn set_tether_native(on: bool) {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn set_tether_native(_on: bool) {}
|
||||
fn set_tether_native(on: bool) {
|
||||
link::set_tether(on);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn sync_native() {
|
||||
@@ -282,7 +332,9 @@ fn sync_native() {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn sync_native() {}
|
||||
fn sync_native() {
|
||||
link::request_sync();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn import_native(names_json: &str) {
|
||||
@@ -293,7 +345,9 @@ fn import_native(names_json: &str) {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn import_native(_names_json: &str) {}
|
||||
fn import_native(names_json: &str) {
|
||||
link::import_json(names_json);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn refresh_catalog_native() {
|
||||
@@ -301,7 +355,9 @@ fn refresh_catalog_native() {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn refresh_catalog_native() {}
|
||||
fn refresh_catalog_native() {
|
||||
link::refresh();
|
||||
}
|
||||
|
||||
/// Starts the browser once. Safe to call at launch; callbacks only enqueue a string.
|
||||
pub fn start(ftp: &FtpState) {
|
||||
@@ -313,6 +369,8 @@ pub fn start(ftp: &FtpState) {
|
||||
}
|
||||
unsafe { pr_camera_start(on_camera_json) }
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
link::start();
|
||||
let dir = ftp.ingest_dir();
|
||||
let _ = std::fs::create_dir_all(dir.join(".usb"));
|
||||
set_download_dir(&dir.join(".usb").to_string_lossy());
|
||||
@@ -364,6 +422,33 @@ pub fn camera_refresh(cam: tauri::State<'_, CameraState>) -> CameraStatus {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_first_listing_is_not_a_new_shot_and_a_later_one_is() {
|
||||
let shots = vec![
|
||||
ListedShot {
|
||||
name: "old.JPG".into(),
|
||||
size: 10,
|
||||
created_ms: Some(1),
|
||||
},
|
||||
ListedShot {
|
||||
name: "new.JPG".into(),
|
||||
size: 20,
|
||||
created_ms: Some(2),
|
||||
},
|
||||
];
|
||||
let mut known = HashSet::new();
|
||||
known.insert("old.JPG".to_string());
|
||||
let mut fetched = HashSet::new();
|
||||
fetched.insert("old.JPG".to_string());
|
||||
let first = files_on_card(&shots[..1], &known, &fetched, false);
|
||||
assert!(!first[0].is_new);
|
||||
assert!(first[0].imported);
|
||||
let live = files_on_card(&shots, &known, &fetched, true);
|
||||
assert!(!live[0].is_new);
|
||||
assert!(live[1].is_new);
|
||||
assert!(!live[1].imported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_shot_queues_the_jpeg_and_the_raw() {
|
||||
let mut inner = Inner {
|
||||
@@ -424,7 +509,10 @@ mod tests {
|
||||
catalog_gen: 1,
|
||||
};
|
||||
apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#);
|
||||
apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#);
|
||||
apply_event(
|
||||
&mut inner,
|
||||
r#"{"kind":"catalog","cameraId":"abc","files":[]}"#,
|
||||
);
|
||||
assert!(inner.devices.is_empty());
|
||||
assert!(inner.files.is_empty());
|
||||
assert_eq!(inner.catalog_gen, 2);
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Linux USB via libgphoto2. The camera is opened for this pass only and dropped before we return,
|
||||
//! which closes the PTP session.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub struct Shot {
|
||||
pub folder: String,
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub created_ms: Option<i64>,
|
||||
}
|
||||
|
||||
pub struct Report {
|
||||
pub model: Option<String>,
|
||||
pub id: String,
|
||||
pub error: Option<String>,
|
||||
pub shots: Vec<Shot>,
|
||||
pub downloaded: Vec<(String, u64)>,
|
||||
pub clock: Option<String>,
|
||||
pub clock_unsupported: bool,
|
||||
}
|
||||
|
||||
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
|
||||
let context = gphoto2::Context::new().map_err(|err| err.to_string())?;
|
||||
let mut listed = context
|
||||
.list_cameras()
|
||||
.wait()
|
||||
.map_err(|err| err.to_string())?;
|
||||
let Some(desc) = listed.next() else {
|
||||
return Ok(empty());
|
||||
};
|
||||
let camera = context
|
||||
.get_camera(&desc)
|
||||
.wait()
|
||||
.map_err(|err| err.to_string())?;
|
||||
let model = camera.abilities().model().to_string();
|
||||
let roots = card_roots(&camera);
|
||||
let fs = camera.fs();
|
||||
let mut shots = Vec::new();
|
||||
for root in roots {
|
||||
walk(&fs, &root, 0, &mut shots)?;
|
||||
}
|
||||
let mut downloaded = Vec::new();
|
||||
let mut error = None;
|
||||
for shot in &shots {
|
||||
let asked = wanted.iter().any(|name| name == &shot.name);
|
||||
if !asked {
|
||||
continue;
|
||||
}
|
||||
match copy_one(&fs, dir, shot) {
|
||||
Ok(size) => downloaded.push((shot.name.clone(), size)),
|
||||
Err(err) => error = Some(err),
|
||||
}
|
||||
}
|
||||
// Dropping `camera` closes the session before the caller waits.
|
||||
drop(fs);
|
||||
drop(camera);
|
||||
Ok(Report {
|
||||
model: Some(model),
|
||||
id: "gphoto".into(),
|
||||
error,
|
||||
shots,
|
||||
downloaded,
|
||||
clock: None,
|
||||
// libgphoto2 clock widgets differ per body; the panel says the clock was not set.
|
||||
clock_unsupported: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn empty() -> Report {
|
||||
Report {
|
||||
model: None,
|
||||
id: "gphoto".into(),
|
||||
error: None,
|
||||
shots: Vec::new(),
|
||||
downloaded: Vec::new(),
|
||||
clock: None,
|
||||
clock_unsupported: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn card_roots(camera: &gphoto2::Camera) -> Vec<String> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(storages) = camera.storages().wait() {
|
||||
for storage in storages {
|
||||
let Some(base) = storage.base_directory() else {
|
||||
continue;
|
||||
};
|
||||
let text = base.to_string();
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !roots.iter().any(|have| have == &text) {
|
||||
roots.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
if roots.is_empty() {
|
||||
roots.push("/".to_string());
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn walk(
|
||||
fs: &gphoto2::filesys::CameraFS<'_>,
|
||||
folder: &str,
|
||||
depth: u32,
|
||||
shots: &mut Vec<Shot>,
|
||||
) -> Result<(), String> {
|
||||
if depth > 12 {
|
||||
return Ok(());
|
||||
}
|
||||
let files = match fs.list_files(folder).wait() {
|
||||
Ok(files) => files,
|
||||
Err(err) if folder != "/" => {
|
||||
let _ = err;
|
||||
return Ok(());
|
||||
}
|
||||
Err(err) => return Err(err.to_string()),
|
||||
};
|
||||
for name in files {
|
||||
if !is_still(&name) {
|
||||
continue;
|
||||
}
|
||||
let info = fs.file_info(folder, &name).wait().ok();
|
||||
let size = info
|
||||
.as_ref()
|
||||
.and_then(|info| info.file().size())
|
||||
.unwrap_or(0);
|
||||
let created_ms = info
|
||||
.as_ref()
|
||||
.and_then(|info| info.file().mtime())
|
||||
.map(|mtime| {
|
||||
let seconds = mtime as i64;
|
||||
seconds.saturating_mul(1000)
|
||||
});
|
||||
shots.push(Shot {
|
||||
folder: folder.to_string(),
|
||||
name,
|
||||
size,
|
||||
created_ms,
|
||||
});
|
||||
}
|
||||
let folders = match fs.list_folders(folder).wait() {
|
||||
Ok(folders) => folders,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
for name in folders {
|
||||
let child = child_folder(folder, &name);
|
||||
walk(fs, &child, depth + 1, shots)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_one(fs: &gphoto2::filesys::CameraFS<'_>, dir: &Path, shot: &Shot) -> Result<u64, String> {
|
||||
let dest = dir.join(&shot.name);
|
||||
if let Ok(meta) = std::fs::metadata(&dest) {
|
||||
if meta.len() > 0 {
|
||||
return Ok(meta.len());
|
||||
}
|
||||
}
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
fs.download_to(&shot.folder, &shot.name, &dest)
|
||||
.wait()
|
||||
.map_err(|err| err.to_string())?;
|
||||
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
|
||||
Ok(meta.len())
|
||||
}
|
||||
|
||||
fn child_folder(parent: &str, name: &str) -> String {
|
||||
if name.starts_with('/') {
|
||||
return name.to_string();
|
||||
}
|
||||
if parent == "/" {
|
||||
return format!("/{name}");
|
||||
}
|
||||
format!("{parent}/{name}")
|
||||
}
|
||||
|
||||
fn is_still(name: &str) -> bool {
|
||||
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! USB on Linux (libgphoto2) and Windows (portable devices). Same rhythm as the Mac: open, list,
|
||||
//! download what was asked, drop the session so the shutter is free, then wait before the next open.
|
||||
//! The Mac path stays in `camera_mac.m` and is not used here.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{CameraDevice, ListedShot, enqueue_line, files_on_card};
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[path = "camera_gphoto.rs"]
|
||||
mod backend;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[path = "camera_wpd.rs"]
|
||||
mod backend;
|
||||
|
||||
/// How long the body stays free between card reads. Matches the Mac poll.
|
||||
const FREE_MS: u64 = 2500;
|
||||
const STEP_MS: u64 = 200;
|
||||
|
||||
struct Link {
|
||||
tether: AtomicBool,
|
||||
sync: AtomicBool,
|
||||
refresh: AtomicBool,
|
||||
dir: Mutex<String>,
|
||||
pending: Mutex<Vec<String>>,
|
||||
/// Names on the card the first time this tether session listed it. `None` until that pass.
|
||||
known: Mutex<Option<HashSet<String>>>,
|
||||
fetched: Mutex<HashSet<String>>,
|
||||
}
|
||||
|
||||
fn link() -> &'static Link {
|
||||
static LINK: OnceLock<Link> = OnceLock::new();
|
||||
LINK.get_or_init(|| Link {
|
||||
tether: AtomicBool::new(false),
|
||||
sync: AtomicBool::new(false),
|
||||
refresh: AtomicBool::new(false),
|
||||
dir: Mutex::new(String::new()),
|
||||
pending: Mutex::new(Vec::new()),
|
||||
known: Mutex::new(None),
|
||||
fetched: Mutex::new(HashSet::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn start() {
|
||||
static STARTED: AtomicBool = AtomicBool::new(false);
|
||||
if STARTED.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("photoreport-usb".into())
|
||||
.spawn(|| {
|
||||
#[cfg(target_os = "windows")]
|
||||
backend::init_thread();
|
||||
loop {
|
||||
if !link().tether.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(Duration::from_millis(STEP_MS));
|
||||
continue;
|
||||
}
|
||||
pulse_once();
|
||||
let mut waited = 0u64;
|
||||
while waited < FREE_MS && link().tether.load(Ordering::SeqCst) {
|
||||
if link().refresh.swap(false, Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let waiting = link()
|
||||
.pending
|
||||
.lock()
|
||||
.map(|p| !p.is_empty())
|
||||
.unwrap_or(false);
|
||||
if waiting {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(STEP_MS));
|
||||
waited += STEP_MS;
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
pub fn set_dir(dir: &str) {
|
||||
if let Ok(mut slot) = link().dir.lock() {
|
||||
*slot = dir.to_string();
|
||||
}
|
||||
load_fetched(Path::new(dir));
|
||||
}
|
||||
|
||||
pub fn set_tether(on: bool) {
|
||||
link().tether.store(on, Ordering::SeqCst);
|
||||
if !on {
|
||||
if let Ok(mut known) = link().known.lock() {
|
||||
*known = None;
|
||||
}
|
||||
publish_idle();
|
||||
return;
|
||||
}
|
||||
link().refresh.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn request_sync() {
|
||||
link().sync.store(true, Ordering::SeqCst);
|
||||
link().refresh.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn refresh() {
|
||||
link().refresh.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn import_json(names_json: &str) {
|
||||
let Ok(names) = serde_json::from_str::<Vec<String>>(names_json) else {
|
||||
return;
|
||||
};
|
||||
if let Ok(mut pending) = link().pending.lock() {
|
||||
for name in names {
|
||||
if !pending.iter().any(|have| have == &name) {
|
||||
pending.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
link().refresh.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn pulse_once() {
|
||||
let dir = link().dir.lock().map(|d| d.clone()).unwrap_or_default();
|
||||
if dir.is_empty() {
|
||||
return;
|
||||
}
|
||||
let wanted = link().pending.lock().map(|p| p.clone()).unwrap_or_default();
|
||||
let sync = link().sync.swap(false, Ordering::SeqCst);
|
||||
let report = backend::pulse(Path::new(&dir), &wanted, sync);
|
||||
match report {
|
||||
Ok(report) => apply_report(&dir, report),
|
||||
Err(err) => publish_busy(&err),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_report(dir: &str, report: backend::Report) {
|
||||
let Some(model) = report.model else {
|
||||
publish_devices(Vec::new());
|
||||
publish_files("usb", Vec::new());
|
||||
return;
|
||||
};
|
||||
let shots: Vec<ListedShot> = report
|
||||
.shots
|
||||
.iter()
|
||||
.map(|shot| ListedShot {
|
||||
name: shot.name.clone(),
|
||||
size: shot.size,
|
||||
created_ms: shot.created_ms,
|
||||
})
|
||||
.collect();
|
||||
let listing_is_live = {
|
||||
let Ok(mut known) = link().known.lock() else {
|
||||
return;
|
||||
};
|
||||
if known.is_none() {
|
||||
let mut names = HashSet::new();
|
||||
for shot in &shots {
|
||||
names.insert(shot.name.clone());
|
||||
}
|
||||
*known = Some(names);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
};
|
||||
let known = link()
|
||||
.known
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|k| k.clone())
|
||||
.unwrap_or_default();
|
||||
let fetched = link().fetched.lock().map(|f| f.clone()).unwrap_or_default();
|
||||
let files = files_on_card(&shots, &known, &fetched, listing_is_live);
|
||||
let mut clock = report.clock;
|
||||
if clock.is_none() && report.clock_unsupported {
|
||||
clock = Some("unsupported".to_string());
|
||||
}
|
||||
let id = report.id.clone();
|
||||
publish_devices(vec![CameraDevice {
|
||||
id: id.clone(),
|
||||
name: model,
|
||||
vendor_id: 0,
|
||||
product_id: 0,
|
||||
state: "tethered".to_string(),
|
||||
error: report.error,
|
||||
clock,
|
||||
clock_offset: None,
|
||||
catalog_ready: true,
|
||||
}]);
|
||||
publish_files(&id, files);
|
||||
remember_downloaded(dir, &report.downloaded);
|
||||
}
|
||||
|
||||
fn remember_downloaded(dir: &str, downloaded: &[(String, u64)]) {
|
||||
if downloaded.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Ok(mut fetched) = link().fetched.lock() else {
|
||||
return;
|
||||
};
|
||||
let Ok(mut pending) = link().pending.lock() else {
|
||||
return;
|
||||
};
|
||||
for (name, size) in downloaded {
|
||||
if *size == 0 {
|
||||
continue;
|
||||
}
|
||||
fetched.insert(name.clone());
|
||||
pending.retain(|want| want != name);
|
||||
let path = PathBuf::from(dir).join(name);
|
||||
let line = serde_json::json!({
|
||||
"kind": "file",
|
||||
"path": path,
|
||||
"name": name,
|
||||
"size": size,
|
||||
});
|
||||
enqueue_line(line.to_string());
|
||||
}
|
||||
write_fetched(Path::new(dir), &fetched);
|
||||
}
|
||||
|
||||
fn publish_idle() {
|
||||
publish_devices(Vec::new());
|
||||
publish_files("usb", Vec::new());
|
||||
}
|
||||
|
||||
fn publish_busy(err: &str) {
|
||||
publish_devices(vec![CameraDevice {
|
||||
id: "usb".into(),
|
||||
name: "USB".into(),
|
||||
vendor_id: 0,
|
||||
product_id: 0,
|
||||
state: "busy".into(),
|
||||
error: Some(err.to_string()),
|
||||
clock: None,
|
||||
clock_offset: None,
|
||||
catalog_ready: false,
|
||||
}]);
|
||||
}
|
||||
|
||||
fn publish_devices(devices: Vec<CameraDevice>) {
|
||||
let line = serde_json::json!({ "kind": "devices", "devices": devices });
|
||||
enqueue_line(line.to_string());
|
||||
}
|
||||
|
||||
fn publish_files(camera_id: &str, files: Vec<super::CameraFile>) {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Catalog<'a> {
|
||||
kind: &'static str,
|
||||
camera_id: &'a str,
|
||||
files: &'a [super::CameraFile],
|
||||
}
|
||||
let line = serde_json::to_string(&Catalog {
|
||||
kind: "catalog",
|
||||
camera_id,
|
||||
files: &files,
|
||||
});
|
||||
if let Ok(line) = line {
|
||||
enqueue_line(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn fetched_path(dir: &Path) -> PathBuf {
|
||||
dir.join(".fetched")
|
||||
}
|
||||
|
||||
fn load_fetched(dir: &Path) {
|
||||
let text = std::fs::read_to_string(fetched_path(dir)).unwrap_or_default();
|
||||
let Ok(mut fetched) = link().fetched.lock() else {
|
||||
return;
|
||||
};
|
||||
fetched.clear();
|
||||
for line in text.lines() {
|
||||
if !line.is_empty() {
|
||||
fetched.insert(line.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_fetched(dir: &Path, fetched: &HashSet<String>) {
|
||||
let mut names: Vec<&String> = fetched.iter().collect();
|
||||
names.sort();
|
||||
let mut text = String::new();
|
||||
for name in names {
|
||||
text.push_str(name);
|
||||
text.push('\n');
|
||||
}
|
||||
let _ = std::fs::write(fetched_path(dir), text);
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Windows USB via the portable-device API (the PTP driver Windows already owns). The device is
|
||||
//! opened for this pass and released before we return, so the body is not left on the computer screen.
|
||||
|
||||
// The whole module is COM. Edition 2024 does not treat an `unsafe fn` body as an unsafe block.
|
||||
#![allow(unsafe_op_in_unsafe_fn)]
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use windows::{
|
||||
Win32::{
|
||||
Devices::PortableDevices::{
|
||||
IEnumPortableDeviceObjectIDs, IPortableDevice, IPortableDeviceContent,
|
||||
IPortableDeviceKeyCollection, IPortableDeviceManager, IPortableDeviceValues,
|
||||
PortableDevice, PortableDeviceKeyCollection, PortableDeviceManager,
|
||||
PortableDeviceValues, WPD_CLIENT_MAJOR_VERSION, WPD_CLIENT_MINOR_VERSION,
|
||||
WPD_CLIENT_NAME, WPD_CLIENT_REVISION, WPD_DEVICE_OBJECT_ID, WPD_OBJECT_DATE_CREATED,
|
||||
WPD_OBJECT_ORIGINAL_FILE_NAME, WPD_OBJECT_SIZE, WPD_RESOURCE_DEFAULT,
|
||||
},
|
||||
System::Com::{
|
||||
CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,
|
||||
CoTaskMemFree, IStream, STGM_READ,
|
||||
StructuredStorage::{PROPVARIANT, PropVariantClear},
|
||||
},
|
||||
System::Variant::VT_FILETIME,
|
||||
},
|
||||
core::{PCWSTR, PWSTR, w},
|
||||
};
|
||||
|
||||
pub struct Shot {
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub created_ms: Option<i64>,
|
||||
object_id: String,
|
||||
}
|
||||
|
||||
pub struct Report {
|
||||
pub model: Option<String>,
|
||||
pub id: String,
|
||||
pub error: Option<String>,
|
||||
pub shots: Vec<Shot>,
|
||||
pub downloaded: Vec<(String, u64)>,
|
||||
pub clock: Option<String>,
|
||||
pub clock_unsupported: bool,
|
||||
}
|
||||
|
||||
pub fn init_thread() {
|
||||
unsafe {
|
||||
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
|
||||
unsafe { read_card(dir, wanted) }
|
||||
}
|
||||
|
||||
unsafe fn read_card(dir: &Path, wanted: &[String]) -> Result<Report, String> {
|
||||
let manager: IPortableDeviceManager =
|
||||
CoCreateInstance(&PortableDeviceManager, None, CLSCTX_INPROC_SERVER)
|
||||
.map_err(|err| err.to_string())?;
|
||||
let mut count = 0u32;
|
||||
manager
|
||||
.GetDevices(std::ptr::null_mut(), &mut count)
|
||||
.map_err(|err| err.to_string())?;
|
||||
if count == 0 {
|
||||
return Ok(empty());
|
||||
}
|
||||
let mut ids = vec![PWSTR::null(); count as usize];
|
||||
manager
|
||||
.GetDevices(ids.as_mut_ptr(), &mut count)
|
||||
.map_err(|err| err.to_string())?;
|
||||
let device_id = ids.first().copied().unwrap_or(PWSTR::null());
|
||||
let id_text = if device_id.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
device_id.to_string().unwrap_or_default()
|
||||
};
|
||||
for id in &ids {
|
||||
if !id.is_null() && id.0 != device_id.0 {
|
||||
CoTaskMemFree(Some(id.0 as *const _));
|
||||
}
|
||||
}
|
||||
if id_text.is_empty() {
|
||||
return Ok(empty());
|
||||
}
|
||||
|
||||
let device: IPortableDevice = CoCreateInstance(&PortableDevice, None, CLSCTX_INPROC_SERVER)
|
||||
.map_err(|err| err.to_string())?;
|
||||
let client: IPortableDeviceValues =
|
||||
CoCreateInstance(&PortableDeviceValues, None, CLSCTX_INPROC_SERVER)
|
||||
.map_err(|err| err.to_string())?;
|
||||
client
|
||||
.SetStringValue(&WPD_CLIENT_NAME, w!("PhotoReport"))
|
||||
.map_err(|err| err.to_string())?;
|
||||
client
|
||||
.SetUnsignedIntegerValue(&WPD_CLIENT_MAJOR_VERSION, 1)
|
||||
.map_err(|err| err.to_string())?;
|
||||
client
|
||||
.SetUnsignedIntegerValue(&WPD_CLIENT_MINOR_VERSION, 0)
|
||||
.map_err(|err| err.to_string())?;
|
||||
client
|
||||
.SetUnsignedIntegerValue(&WPD_CLIENT_REVISION, 0)
|
||||
.map_err(|err| err.to_string())?;
|
||||
let wide_id = wide(&id_text);
|
||||
let device_name = friendly_name(&manager, PCWSTR(wide_id.as_ptr()));
|
||||
device
|
||||
.Open(PCWSTR(wide_id.as_ptr()), &client)
|
||||
.map_err(|err| err.to_string())?;
|
||||
let content = device.Content().map_err(|err| err.to_string())?;
|
||||
let mut shots = Vec::new();
|
||||
collect(&content, WPD_DEVICE_OBJECT_ID, 0, &mut shots).map_err(|err| err.to_string())?;
|
||||
|
||||
let mut downloaded = Vec::new();
|
||||
let mut error = None;
|
||||
for shot in &shots {
|
||||
let asked = wanted.iter().any(|name| name == &shot.name);
|
||||
if !asked {
|
||||
continue;
|
||||
}
|
||||
match copy_one(&content, dir, shot) {
|
||||
Ok(size) => downloaded.push((shot.name.clone(), size)),
|
||||
Err(err) => error = Some(err),
|
||||
}
|
||||
}
|
||||
if !device_id.is_null() {
|
||||
CoTaskMemFree(Some(device_id.0 as *const _));
|
||||
}
|
||||
// `device` drops here, which closes the PTP session.
|
||||
Ok(Report {
|
||||
model: Some(device_name),
|
||||
id: "wpd".into(),
|
||||
error,
|
||||
shots,
|
||||
downloaded,
|
||||
clock: None,
|
||||
clock_unsupported: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn empty() -> Report {
|
||||
Report {
|
||||
model: None,
|
||||
id: "wpd".into(),
|
||||
error: None,
|
||||
shots: Vec::new(),
|
||||
downloaded: Vec::new(),
|
||||
clock: None,
|
||||
clock_unsupported: false,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn friendly_name(manager: &IPortableDeviceManager, id: PCWSTR) -> String {
|
||||
let mut chars = 0u32;
|
||||
if manager
|
||||
.GetDeviceFriendlyName(id, PWSTR::null(), &mut chars)
|
||||
.is_err()
|
||||
|| chars <= 1
|
||||
{
|
||||
return "USB camera".to_string();
|
||||
}
|
||||
let mut buf = vec![0u16; chars as usize];
|
||||
if manager
|
||||
.GetDeviceFriendlyName(id, PWSTR(buf.as_mut_ptr()), &mut chars)
|
||||
.is_err()
|
||||
{
|
||||
return "USB camera".to_string();
|
||||
}
|
||||
let end = (chars as usize).saturating_sub(1).min(buf.len());
|
||||
let name = String::from_utf16_lossy(&buf[..end]);
|
||||
if name.is_empty() {
|
||||
return "USB camera".to_string();
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
unsafe fn collect(
|
||||
content: &IPortableDeviceContent,
|
||||
parent: PCWSTR,
|
||||
depth: u32,
|
||||
shots: &mut Vec<Shot>,
|
||||
) -> windows::core::Result<()> {
|
||||
if depth > 12 {
|
||||
return Ok(());
|
||||
}
|
||||
let enumerator: IEnumPortableDeviceObjectIDs = content.EnumObjects(0, parent, None)?;
|
||||
loop {
|
||||
let mut batch = [PWSTR::null(); 32];
|
||||
let mut fetched = 0u32;
|
||||
let hr = enumerator.Next(&mut batch, &mut fetched);
|
||||
if hr.is_err() || fetched == 0 {
|
||||
break;
|
||||
}
|
||||
for id in batch.iter().take(fetched as usize) {
|
||||
if id.is_null() {
|
||||
continue;
|
||||
}
|
||||
let object_id = id.to_string().unwrap_or_default();
|
||||
CoTaskMemFree(Some(id.0 as *const _));
|
||||
if object_id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(shot) = shot_of(content, &object_id)? {
|
||||
shots.push(shot);
|
||||
}
|
||||
let child = wide(&object_id);
|
||||
collect(content, PCWSTR(child.as_ptr()), depth + 1, shots)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn shot_of(
|
||||
content: &IPortableDeviceContent,
|
||||
object_id: &str,
|
||||
) -> windows::core::Result<Option<Shot>> {
|
||||
let keys: IPortableDeviceKeyCollection =
|
||||
CoCreateInstance(&PortableDeviceKeyCollection, None, CLSCTX_INPROC_SERVER)?;
|
||||
keys.Add(&WPD_OBJECT_ORIGINAL_FILE_NAME)?;
|
||||
keys.Add(&WPD_OBJECT_SIZE)?;
|
||||
keys.Add(&WPD_OBJECT_DATE_CREATED)?;
|
||||
let properties = content.Properties()?;
|
||||
let object_wide = wide(object_id);
|
||||
let values = properties.GetValues(PCWSTR(object_wide.as_ptr()), &keys)?;
|
||||
let name_ptr = values
|
||||
.GetStringValue(&WPD_OBJECT_ORIGINAL_FILE_NAME)
|
||||
.unwrap_or(PWSTR::null());
|
||||
if name_ptr.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
let name = name_ptr.to_string().unwrap_or_default();
|
||||
CoTaskMemFree(Some(name_ptr.0 as *const _));
|
||||
if !is_still(&name) {
|
||||
return Ok(None);
|
||||
}
|
||||
let size = values
|
||||
.GetUnsignedLargeIntegerValue(&WPD_OBJECT_SIZE)
|
||||
.unwrap_or(0);
|
||||
let created_ms = filetime_ms(&values);
|
||||
Ok(Some(Shot {
|
||||
name,
|
||||
size,
|
||||
created_ms,
|
||||
object_id: object_id.to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
unsafe fn filetime_ms(values: &IPortableDeviceValues) -> Option<i64> {
|
||||
let mut variant = values.GetValue(&WPD_OBJECT_DATE_CREATED).ok()?;
|
||||
let ms = filetime_of(&variant);
|
||||
let _ = PropVariantClear(&mut variant);
|
||||
ms
|
||||
}
|
||||
|
||||
/// 100-nanosecond ticks since 1601-01-01, which is how a portable device stores a capture time.
|
||||
unsafe fn filetime_of(variant: &PROPVARIANT) -> Option<i64> {
|
||||
let header = &variant.Anonymous.Anonymous;
|
||||
if header.vt != VT_FILETIME {
|
||||
return None;
|
||||
}
|
||||
let filetime = header.Anonymous.filetime;
|
||||
let ticks = (u64::from(filetime.dwHighDateTime) << 32) | u64::from(filetime.dwLowDateTime);
|
||||
const EPOCH_DIFF: u64 = 116_444_736_000_000_000;
|
||||
if ticks < EPOCH_DIFF {
|
||||
return None;
|
||||
}
|
||||
let unix_100ns = ticks - EPOCH_DIFF;
|
||||
Some((unix_100ns / 10_000) as i64)
|
||||
}
|
||||
|
||||
unsafe fn copy_one(
|
||||
content: &IPortableDeviceContent,
|
||||
dir: &Path,
|
||||
shot: &Shot,
|
||||
) -> Result<u64, String> {
|
||||
let dest = dir.join(&shot.name);
|
||||
if let Ok(meta) = std::fs::metadata(&dest) {
|
||||
if meta.len() > 0 {
|
||||
return Ok(meta.len());
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(dir).map_err(|err| err.to_string())?;
|
||||
let resources = content.Transfer().map_err(|err| err.to_string())?;
|
||||
let object_wide = wide(&shot.object_id);
|
||||
let mut stream: Option<IStream> = None;
|
||||
let mut optimal = 0u32;
|
||||
resources
|
||||
.GetStream(
|
||||
PCWSTR(object_wide.as_ptr()),
|
||||
&WPD_RESOURCE_DEFAULT,
|
||||
STGM_READ.0 as u32,
|
||||
&mut optimal,
|
||||
&mut stream,
|
||||
)
|
||||
.map_err(|err| err.to_string())?;
|
||||
let stream = stream.ok_or("no_stream")?;
|
||||
let mut file = std::fs::File::create(&dest).map_err(|err| err.to_string())?;
|
||||
let mut buffer = vec![0u8; 1024 * 256];
|
||||
loop {
|
||||
let mut read = 0u32;
|
||||
let hr = stream.Read(
|
||||
buffer.as_mut_ptr() as *mut _,
|
||||
buffer.len() as u32,
|
||||
Some(&mut read),
|
||||
);
|
||||
if hr.is_err() {
|
||||
let _ = std::fs::remove_file(&dest);
|
||||
return Err(hr.to_string());
|
||||
}
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
use std::io::Write;
|
||||
file.write_all(&buffer[..read as usize])
|
||||
.map_err(|err| err.to_string())?;
|
||||
}
|
||||
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
|
||||
Ok(meta.len())
|
||||
}
|
||||
|
||||
fn is_still(name: &str) -> bool {
|
||||
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
|
||||
}
|
||||
|
||||
fn wide(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
@@ -932,7 +932,10 @@ mod tests {
|
||||
let (take, held) = days_that_fit(days, Some(55));
|
||||
assert_eq!(take.len(), 1);
|
||||
assert_eq!(take[0].key, "2026-11-03");
|
||||
assert_eq!(held, vec!["2026-11-04".to_string(), "2026-11-05".to_string()]);
|
||||
assert_eq!(
|
||||
held,
|
||||
vec!["2026-11-04".to_string(), "2026-11-05".to_string()]
|
||||
);
|
||||
let (all, none) = days_that_fit(
|
||||
vec![DayPlan {
|
||||
key: "2026-11-04".into(),
|
||||
|
||||
@@ -126,11 +126,7 @@ impl Deliveries {
|
||||
Path::new(f)
|
||||
.canonicalize()
|
||||
.ok()
|
||||
.and_then(|root| {
|
||||
canon
|
||||
.parent()
|
||||
.map(|p| p.starts_with(&root))
|
||||
})
|
||||
.and_then(|root| canon.parent().map(|p| p.starts_with(&root)))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
if !allowed && !allowed_xmp {
|
||||
|
||||
@@ -266,6 +266,7 @@ fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn memory_gb() -> f64 {
|
||||
let pages = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
|
||||
let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
|
||||
@@ -275,6 +276,34 @@ fn memory_gb() -> f64 {
|
||||
(pages as f64) * (size as f64) / 1e9
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn memory_gb() -> f64 {
|
||||
#[repr(C)]
|
||||
struct MemoryStatus {
|
||||
length: u32,
|
||||
memory_load: u32,
|
||||
total_phys: u64,
|
||||
avail_phys: u64,
|
||||
total_page: u64,
|
||||
avail_page: u64,
|
||||
total_virtual: u64,
|
||||
avail_virtual: u64,
|
||||
avail_extended_virtual: u64,
|
||||
}
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GlobalMemoryStatusEx(status: *mut MemoryStatus) -> i32;
|
||||
}
|
||||
unsafe {
|
||||
let mut status = std::mem::zeroed::<MemoryStatus>();
|
||||
status.length = std::mem::size_of::<MemoryStatus>() as u32;
|
||||
if GlobalMemoryStatusEx(&mut status) == 0 || status.total_phys == 0 {
|
||||
return 8.0;
|
||||
}
|
||||
status.total_phys as f64 / 1e9
|
||||
}
|
||||
}
|
||||
|
||||
/// One engine per core, and only as many as memory can hold (each copy of the model is large).
|
||||
/// `extra_gb` is RAM already taken by the accelerator, so the CPU copies leave room for it.
|
||||
fn engine_cap(extra_gb: f64) -> usize {
|
||||
@@ -334,21 +363,47 @@ fn cpu_ticks() -> Option<(u64, u64)> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
/// `GetSystemTimes`: kernel time already includes idle, so the total is kernel plus user.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn cpu_ticks() -> Option<(u64, u64)> {
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GetSystemTimes(idle: *mut u64, kernel: *mut u64, user: *mut u64) -> i32;
|
||||
}
|
||||
unsafe {
|
||||
let mut idle = 0u64;
|
||||
let mut kernel = 0u64;
|
||||
let mut user = 0u64;
|
||||
if GetSystemTimes(&mut idle, &mut kernel, &mut user) == 0 {
|
||||
return None;
|
||||
}
|
||||
let total = kernel.saturating_add(user);
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((idle, total))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
|
||||
fn cpu_ticks() -> Option<(u64, u64)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Share of the CPU that was busy between two samples. `idle` is included in `total`.
|
||||
fn cpu_fraction(idle_delta: u64, total_delta: u64) -> Option<f64> {
|
||||
if total_delta == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(1.0 - (idle_delta as f64) / (total_delta as f64))
|
||||
}
|
||||
|
||||
fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option<f64> {
|
||||
let now = cpu_ticks()?;
|
||||
let used = prev.and_then(|(idle, total)| {
|
||||
let idle_d = now.0.saturating_sub(idle);
|
||||
let total_d = now.1.saturating_sub(total);
|
||||
if total_d == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(1.0 - (idle_d as f64) / (total_d as f64))
|
||||
}
|
||||
let idle_delta = now.0.saturating_sub(idle);
|
||||
let total_delta = now.1.saturating_sub(total);
|
||||
cpu_fraction(idle_delta, total_delta)
|
||||
});
|
||||
*prev = Some(now);
|
||||
used
|
||||
@@ -747,6 +802,13 @@ pub fn faces_read(path: String) -> Result<tauri::ipc::Response, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cpu_fraction_counts_idle_inside_the_total() {
|
||||
let busy = cpu_fraction(25, 100);
|
||||
assert_eq!(busy, Some(0.75));
|
||||
assert_eq!(cpu_fraction(0, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_round_trip_of_a_short_buffer() {
|
||||
let raw = b"faces";
|
||||
|
||||
@@ -1598,9 +1598,18 @@ pub fn ftp_sent(
|
||||
event: String,
|
||||
date: String,
|
||||
) -> Result<String, String> {
|
||||
// Canonical path while the file is still in ingest: that is the string `ftp_info` stored.
|
||||
let source = std::fs::canonicalize(&path)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|_| path.clone());
|
||||
let target = state.sent(&path, &event, &date)?;
|
||||
if let Ok(sha) = crate::local::sha256_file(Path::new(&target)) {
|
||||
index.record(&sha, Path::new(&target));
|
||||
let filed = PathBuf::from(&target);
|
||||
index.retarget(&source, &filed);
|
||||
if source != path {
|
||||
index.retarget(&path, &filed);
|
||||
}
|
||||
if let Ok(sha) = crate::local::sha256_file(&filed) {
|
||||
index.record(&sha, &filed);
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
@@ -102,6 +102,7 @@ pub fn run() {
|
||||
// `tauri dev` serves the dev server: nothing to update.
|
||||
if !cfg!(debug_assertions) {
|
||||
ui::watch(app.handle().clone());
|
||||
updater::watch(app.handle().clone());
|
||||
}
|
||||
// Always the interface on this computer (`tauri dev`: the dev server). No download to start, and it
|
||||
// works without a network; new versions arrive in the background (see `ui`).
|
||||
|
||||
@@ -95,9 +95,68 @@ impl LocalIndex {
|
||||
impl LocalIndex {
|
||||
/// The file recorded for this hash, even if it changed since it arrived (another app, Photo Mechanic, wrote
|
||||
/// captions into it): the same photo, with other metadata. Never handed out as the fingerprinted original.
|
||||
///
|
||||
/// Filing moves the photo out of the ingest folder and a later rewrite changes its hash, so the arrival
|
||||
/// hash can still point at a path that is gone. The copy filed under the same name is that photo.
|
||||
pub fn find_changed(&self, sha256: &str) -> Option<PathBuf> {
|
||||
let path = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
|
||||
path.is_file().then_some(path)
|
||||
let recorded = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
|
||||
if recorded.is_file() {
|
||||
return Some(recorded);
|
||||
}
|
||||
let name = recorded.file_name()?.to_owned();
|
||||
let mut found = self.with(|m| {
|
||||
let mut hits = Vec::new();
|
||||
for (other, path) in m.iter() {
|
||||
if other == sha256 {
|
||||
continue;
|
||||
}
|
||||
let candidate = Path::new(path);
|
||||
if candidate.file_name() != Some(name.as_os_str()) {
|
||||
continue;
|
||||
}
|
||||
if !candidate.is_file() {
|
||||
continue;
|
||||
}
|
||||
hits.push(PathBuf::from(path));
|
||||
}
|
||||
hits
|
||||
});
|
||||
// Two different shoots can reuse a camera name. One remaining file is the one that was filed.
|
||||
if found.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let path = found.pop()?;
|
||||
self.record(sha256, &path);
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// The arrival hash keeps pointing at the file after it leaves the ingest folder. The bytes at the
|
||||
/// destination may already differ (captions written in), so recording only the new hash would lose it.
|
||||
pub fn retarget(&self, from: &str, to: &Path) {
|
||||
let to_owned = to.to_string_lossy().into_owned();
|
||||
if from == to_owned {
|
||||
return;
|
||||
}
|
||||
let file = self.file();
|
||||
let snapshot = self.with(|m| {
|
||||
let mut changed = false;
|
||||
for path in m.values_mut() {
|
||||
if path == from {
|
||||
*path = to_owned.clone();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
serde_json::to_vec(m).ok()
|
||||
});
|
||||
if let Some(bytes) = snapshot {
|
||||
if let Some(dir) = file.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
let _ = std::fs::write(file, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +246,9 @@ pub async fn local_stat(
|
||||
sha256: String,
|
||||
) -> Result<LocalStat, String> {
|
||||
let path = index.find_changed(&sha256).ok_or("not_found")?;
|
||||
let meta = tokio::fs::metadata(&path).await.map_err(|e| e.to_string())?;
|
||||
let meta = tokio::fs::metadata(&path)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut size = meta.len();
|
||||
let mut mtime_ms = meta
|
||||
.modified()
|
||||
@@ -350,6 +411,54 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_filed_copy_when_the_ingest_path_is_gone() {
|
||||
let dir = std::env::temp_dir().join(format!("pr-local-filed-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let ingest = dir.join("ingest");
|
||||
let work = dir.join("work");
|
||||
std::fs::create_dir_all(&ingest).unwrap();
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let arrived = ingest.join("PSR14526.JPG");
|
||||
std::fs::write(&arrived, b"camera jpeg").unwrap();
|
||||
let arrival = sha256_file(&arrived).unwrap();
|
||||
let filed = work.join("PSR14526.JPG");
|
||||
std::fs::write(&filed, b"camera jpeg plus captions").unwrap();
|
||||
let rewritten = sha256_file(&filed).unwrap();
|
||||
|
||||
let index = LocalIndex {
|
||||
file: Some(dir.join("index.json")),
|
||||
..Default::default()
|
||||
};
|
||||
index.record(&arrival, &arrived);
|
||||
index.record(&rewritten, &filed);
|
||||
std::fs::remove_file(&arrived).unwrap();
|
||||
|
||||
assert_eq!(index.find_changed(&arrival), Some(filed.clone()));
|
||||
assert_eq!(index.find(&arrival), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retarget_keeps_the_arrival_hash_on_the_filed_path() {
|
||||
let dir = std::env::temp_dir().join(format!("pr-local-retarget-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let arrived = dir.join("from.JPG");
|
||||
let filed = dir.join("to.JPG");
|
||||
std::fs::write(&arrived, b"same").unwrap();
|
||||
std::fs::write(&filed, b"same").unwrap();
|
||||
let sha = sha256_file(&arrived).unwrap();
|
||||
let index = LocalIndex {
|
||||
file: Some(dir.join("index.json")),
|
||||
..Default::default()
|
||||
};
|
||||
index.record(&sha, &arrived);
|
||||
index.retarget(arrived.to_str().unwrap(), &filed);
|
||||
assert_eq!(index.find_changed(&sha), Some(filed));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filed_jpeg_becomes_a_filmstrip_thumbnail() {
|
||||
let dir = std::env::temp_dir().join(format!("pr-film-{}", std::process::id()));
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
//!
|
||||
//! The app asks the API (`/v1/desktop/update/{target}/{arch}/{version}`), which reads the latest `desktop-v*`
|
||||
//! release. Installers are signed at build time with the release key; the matching public key is compiled in
|
||||
//! (`PHOTOREPORT_UPDATER_PUBKEY`). A build without it (a developer's) never updates itself: there is nothing to
|
||||
//! check a download against.
|
||||
//! (`PHOTOREPORT_UPDATER_PUBKEY`, from the environment or `updater-pubkey.txt` on a release build). A debug build
|
||||
//! without that variable never updates itself: there is nothing to check a download against.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use serde::Serialize;
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
@@ -61,9 +63,22 @@ pub async fn update_check(app: tauri::AppHandle) -> Result<Option<UpdateInfo>, S
|
||||
}
|
||||
|
||||
/// Downloads the new shell, checks its signature, installs it and restarts the app.
|
||||
/// The page and the background check both call this; only one download runs.
|
||||
#[tauri::command]
|
||||
pub async fn update_install(app: tauri::AppHandle) -> Result<(), String> {
|
||||
let update = updater(&app)?
|
||||
let started = INSTALLING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst);
|
||||
if started.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
let result = install_now(&app).await;
|
||||
if result.is_err() {
|
||||
INSTALLING.store(false, Ordering::SeqCst);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn install_now(app: &tauri::AppHandle) -> Result<(), String> {
|
||||
let update = updater(app)?
|
||||
.check()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
@@ -75,6 +90,33 @@ pub async fn update_install(app: tauri::AppHandle) -> Result<(), String> {
|
||||
app.restart();
|
||||
}
|
||||
|
||||
static INSTALLING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
const FIRST: std::time::Duration = std::time::Duration::from_secs(3);
|
||||
const EVERY: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// Checks for a newer shell while the app runs and installs it. The window does not have to ask.
|
||||
pub fn watch(app: tauri::AppHandle) {
|
||||
if PUBKEY.is_none() {
|
||||
return;
|
||||
}
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(FIRST).await;
|
||||
loop {
|
||||
match update_check(app.clone()).await {
|
||||
Ok(Some(_)) => {
|
||||
if let Err(err) = update_install(app.clone()).await {
|
||||
eprintln!("shell update: {err}");
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(err) => eprintln!("shell update: {err}"),
|
||||
}
|
||||
tokio::time::sleep(EVERY).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -88,4 +130,12 @@ mod tests {
|
||||
);
|
||||
assert!(url.starts_with("http"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_builds_ship_the_update_key() {
|
||||
let key = include_str!("../updater-pubkey.txt").trim();
|
||||
assert!(key.starts_with("dW50cnVzdGVk"));
|
||||
assert!(key.len() > 80);
|
||||
assert!(!key.chars().any(|c| c.is_whitespace()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEExODYxQ0JERTgzQzIwMTkKUldRWklEem92UnlHb2RUc0RRN2plalV0bndQVTVySFJQOGtuM3pQNDFtaDZFSld6ZnZya1FCeFEK
|
||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const info = await load(id);
|
||||
return { title: `Cara · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Cara · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function FacePage({ params }: Params) {
|
||||
|
||||
@@ -5,6 +5,13 @@ import { load } from "./load";
|
||||
/** The archive shell: the page the URL asked for, in its owner's template (`data-look`, archive.css). */
|
||||
export async function ArchiveFrame({ id, start }: { id: string; start?: View }) {
|
||||
const info = await load(id);
|
||||
if (!info) {
|
||||
return (
|
||||
<main className="wrap empty">
|
||||
<p>Temporariamente indisponível. Tenta novamente dentro de uns minutos.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
// On the archive's own address (the middleware rewrote `/g/…` to here) its links stay at the root.
|
||||
const atRoot = (await headers()).get("x-arquivo-root") === "1";
|
||||
return <ArchiveView info={{ ...info, base: atRoot ? "" : `/arquivo/${info.id}` }} start={start} />;
|
||||
|
||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const info = await load(id);
|
||||
return { title: `Galeria · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Galeria · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function GalleryPage({ params }: Params) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it, vi, afterEach } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
notFound: () => {
|
||||
const err = new Error("notFound");
|
||||
err.name = "NotFound";
|
||||
throw err;
|
||||
},
|
||||
}));
|
||||
|
||||
const { load } = await import("./load");
|
||||
|
||||
const archiveBody = {
|
||||
id: "d26ceb8e-c146-4f68-abaf-c79ce3981b2d",
|
||||
name: "Test Archive",
|
||||
cloud: "cloud1",
|
||||
organization: "org1",
|
||||
};
|
||||
|
||||
function mockFetch(responses: Record<string, { status: number; body: unknown }>) {
|
||||
global.fetch = vi.fn(async (url: string | URL) => {
|
||||
const path = new URL(url).pathname;
|
||||
const match = Object.entries(responses).find(([key]) => path.includes(key));
|
||||
if (!match) return new Response("{}", { status: 404 });
|
||||
const { status, body } = match[1];
|
||||
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
describe("archive load — graceful degradation", () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("returns archive info on 200", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 200, body: archiveBody } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).not.toBeNull();
|
||||
expect(info?.name).toBe("Test Archive");
|
||||
});
|
||||
|
||||
it("returns null on 500 (transient error, no throw)", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 500, body: {} } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on 502 (transient error, no throw)", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 502, body: {} } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null on 503 (transient error, no throw)", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 503, body: {} } });
|
||||
const info = await load(archiveBody.id);
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it("throws notFound on 404", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 404, body: {} } });
|
||||
await expect(load(archiveBody.id)).rejects.toThrow("notFound");
|
||||
});
|
||||
|
||||
it("throws notFound on 400", async () => {
|
||||
mockFetch({ "/v1/archive/": { status: 400, body: {} } });
|
||||
await expect(load(archiveBody.id)).rejects.toThrow("notFound");
|
||||
});
|
||||
});
|
||||
@@ -15,10 +15,10 @@ export interface ArchiveInfo {
|
||||
base?: string;
|
||||
}
|
||||
|
||||
export async function load(id: string): Promise<ArchiveInfo> {
|
||||
export async function load(id: string): Promise<ArchiveInfo | null> {
|
||||
if (!/^[0-9a-f-]{36}$/i.test(id)) notFound();
|
||||
const res = await fetch(`${API}/v1/archive/${id}`, { cache: "no-store" });
|
||||
if (res.status === 404 || res.status === 400) notFound();
|
||||
if (!res.ok) throw new Error(`archive ${id}: ${res.status}`);
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as ArchiveInfo;
|
||||
}
|
||||
@@ -10,7 +10,7 @@ const UUID = /^[0-9a-f-]{36}$/i;
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const info = await load(id);
|
||||
return { title: `Pessoa · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Pessoa · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function PersonPage({ params }: Params) {
|
||||
|
||||
@@ -8,7 +8,7 @@ type Params = { params: Promise<{ id: string }>; searchParams: Promise<{ t?: str
|
||||
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const info = await load((await params).id);
|
||||
return { title: `Arquivo · ${info.name}`, robots: { index: false } };
|
||||
return { title: info ? `Arquivo · ${info.name}` : "Arquivo", robots: { index: false } };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 {
|
||||
site = await getSite();
|
||||
} catch (err) {
|
||||
if (!(err instanceof NotFound)) throw err;
|
||||
if (!(err instanceof NotFound)) {
|
||||
// Transient API/DB errors (e.g. Postgres pool exhaustion) must not crash the layout —
|
||||
// instrumentation.ts reports every thrown error to errors.bitreport.pt, creating an error
|
||||
// loop. Render a minimal shell so the page returns 200 without a thrown error.
|
||||
return (
|
||||
<html lang="pt">
|
||||
<body>
|
||||
<ErrorReporter />
|
||||
<main className="wrap empty">
|
||||
<p>Temporariamente indisponível. Tenta novamente dentro de uns minutos.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
// The events domain (events.photoreport.pt) has no storefront: its event pages (QR page, kiosk) and the
|
||||
// archive's sign-in pages stand alone.
|
||||
if (path.startsWith("/e/") || path.startsWith("/arquivo/")) {
|
||||
|
||||
@@ -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 { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
|
||||
import { eventTitle, longDate } from "../lib/format";
|
||||
import { load } from "./home-data";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const SPORT_NAMES: Record<string, string> = { andebol: "Andebol", futebol: "Futebol", futsal: "Futsal", basquetebol: "Basquetebol", voleibol: "Voleibol", hoquei: "Hóquei", "hóquei em patins": "Hóquei em patins", rugby: "Râguebi", atletismo: "Atletismo" };
|
||||
const sportName = (s: string) => SPORT_NAMES[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
|
||||
|
||||
async function load(q: string, sport: string) {
|
||||
try {
|
||||
const filtered = !!(q || sport);
|
||||
return await Promise.all([getSite(), getGalleries({ q, sport }), filtered ? Promise.resolve([]) : getLatest(), filtered ? Promise.resolve([]) : getPopular()]);
|
||||
} catch (err) {
|
||||
if (err instanceof NotFound) return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Home: search, sport shortcuts, the photos that just arrived, then the galleries. */
|
||||
export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string; desporto?: string }> }) {
|
||||
const params = await searchParams;
|
||||
|
||||
+16
-5
@@ -330,14 +330,20 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
|
||||
sides (`M19`, `ESP-M19`), and merges the Men's EHF EURO Cup match sheets from `www.eurohandball.com`
|
||||
(`GetStandingMatches` / `GetMatchDetails` — same shape as club sheets, with shirt numbers and `res.ehf.eu`
|
||||
headshots for the nominated 16). Portuguese CIPAs from the FPA call-up stay as `externalId` when the name
|
||||
matches; photo/number come from the sheet. Youth camps (sub-17, sub-19, sub-20, men or women) come from
|
||||
matches; photo/number come from the sheet. The same pass reads the Women's U17 EHF EURO qualification
|
||||
(`W17-EURO`, content `139009`: Portugal–Italy `202712010502014`, 27 Nov 2026 19:00 in Águas Santas, and the
|
||||
rest of that tournament). Portugal is team `W17`; every other country is `<code>-W17` (Italy is `ITA-W17`). The nominated sheet
|
||||
fills numbers and headshots once the EHF publishes it. The FPA camp lists that same match as a friendly
|
||||
(`Sub-17 feminina`): it is folded into `W17-EURO`, and an event already opened on it stays on the one fixture.
|
||||
Youth camps (sub-17, sub-19, sub-20, men or women) come from
|
||||
recent posts on `portal.fpa.pt`: the call-up PDF (CIPA, no shirt number from the list order) and the
|
||||
"Jogos Particulares" calendar. A sheet with a real squad replaces that age group; a post the site does not
|
||||
return leaves the plantel we already have. The November 2026 M19 list and the Spain name list are only the
|
||||
seed when that team is still empty. Those friendlies are fixtures (`m19-por-esp-20261105`,
|
||||
`m19-esp-por-20261107`) so picking the game links that plantel, not the senior one. A folder or title that
|
||||
says sub-19 / M19 (not "Encontro Nacional") is that age group. Cloud delivery for these games is the
|
||||
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`), created from the organisation's
|
||||
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`) and "Cloud W17"
|
||||
(`…/Seleções Nacionais/W17/…`), each created from the organisation's
|
||||
existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills
|
||||
gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on
|
||||
every sports refresh. Example match: Portugal–Switzerland `202811130101002`.
|
||||
@@ -474,9 +480,14 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
|
||||
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
|
||||
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
|
||||
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
|
||||
author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the
|
||||
event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games
|
||||
by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
|
||||
author (`artist`: the photographer's name from the IPTC creator). The upload only reaches the photographer's
|
||||
desk. The public game shows the photo after publish: `POST /api/photo-sync/<image id>`, or
|
||||
`POST /api/photo-sync/match/<game>` when the desk has no single-image publish (the same call as
|
||||
"Sincronizar com zerozero"). A 403 signs in again once (a stale session uses that status, not 401). The same
|
||||
refusal after the new login still counts as delivered: the file is on the desk. Any other publish failure fails
|
||||
the delivery. The "folder" is the game:
|
||||
chosen for the event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's
|
||||
upcoming games by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
|
||||
(`DELETE /api/images/<id>` takes it back).
|
||||
|
||||
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
|
||||
|
||||
+15
-4
@@ -10,7 +10,8 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
the webhook secret from `.env`), checks `ref == refs/heads/main`, and that the push touched a path this
|
||||
container owns (table below). Otherwise it answers 202 and does nothing.
|
||||
3. It runs `infra/deploy/<service>.sh <sha>` under a lock (one deploy at a time per container):
|
||||
- `git fetch` + `git reset --hard <sha>` in `/srv/photoreport`
|
||||
- `git fetch`; a sha that is not the tip of `origin/main` is logged and skipped (exit 0, anti-downgrade, BIT-34038)
|
||||
- `git reset --hard <sha>` in `/srv/photoreport`
|
||||
- `pnpm install --frozen-lockfile` / `cargo build --release -p <crate>` as needed
|
||||
- build only the affected package (`pnpm --filter <pkg> build`)
|
||||
- API only: `prisma migrate deploy`
|
||||
@@ -131,9 +132,19 @@ downloads only the files that changed, checks each hash and uses the new version
|
||||
photographer reloads). The installer's own copy is the fallback, and wins when it is newer.
|
||||
|
||||
macOS builds on a Mac registered once as a runner (`bash infra/desktop/macos-runner.sh`, with a registration token
|
||||
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Its builds carry the updater key, so
|
||||
apps installed from a release update themselves; an app compiled by hand without the key never does. A release made
|
||||
while the Mac is off waits for it.
|
||||
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Release builds carry the updater
|
||||
public key (`updater-pubkey.txt`, or `TAURI_UPDATER_PUBKEY` when CI sets it), so an installed app replaces itself
|
||||
from the next signed `desktop-v*` release. A debug build without the variable never does. A release made while the
|
||||
Mac is off waits for it.
|
||||
|
||||
Windows `.msi` builds on a runner labelled `windows` (Git bash, and the WebView2 step in the workflow). None is
|
||||
registered yet, so a `desktop-v*` tag waits for that job until one is online. Linux installs `libgphoto2-dev`
|
||||
for the USB camera.
|
||||
|
||||
Notarisation uses a Developer ID in `APPLE_SIGNING_IDENTITY` plus either `APPLE_ID`, `APPLE_PASSWORD` and
|
||||
`APPLE_TEAM_ID`, or `APPLE_API_ISSUER`, `APPLE_API_KEY` and `APPLE_API_KEY_PATH`. Those secrets are not on this
|
||||
Gitea yet, so Mac builds stay signed without notarisation. When the identity is set, the hardened runtime is on
|
||||
and `apps/desktop/src-tauri/entitlements.plist` lets the bundled ONNX library load.
|
||||
|
||||
## Importing the old app.photoreport.pt
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
|
||||
const SCRIPT = path.resolve(__dirname, "../../deploy/deploy.sh");
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), "deploy-guard-"));
|
||||
afterAll(() => rmSync(tmp, { recursive: true, force: true }));
|
||||
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd, encoding: "utf8" }).trim();
|
||||
|
||||
describe("deploy.sh anti-downgrade (BIT-34038)", () => {
|
||||
it("skips an old ancestor SHA with exit 0 and leaves the checkout untouched", () => {
|
||||
const origin = path.join(tmp, "origin.git");
|
||||
const work = path.join(tmp, "work");
|
||||
git(tmp, "init", "-q", "--bare", "-b", "main", origin);
|
||||
git(tmp, "clone", "-q", origin, work);
|
||||
git(work, "commit", "-q", "--allow-empty", "-m", "old");
|
||||
const oldSha = git(work, "rev-parse", "HEAD");
|
||||
git(work, "commit", "-q", "--allow-empty", "-m", "new");
|
||||
const tip = git(work, "rev-parse", "HEAD");
|
||||
git(work, "push", "-q", "origin", "main");
|
||||
|
||||
const r = spawnSync("bash", [SCRIPT, "pending", oldSha], {
|
||||
env: { ...process.env, DEPLOY_REPO_DIR: work, DEPLOY_BRANCH: "main" },
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain("SKIP");
|
||||
expect(git(work, "rev-parse", "HEAD")).toBe(tip);
|
||||
|
||||
// The tip itself is deployed (the "workers" service is a no-op build).
|
||||
const ok = spawnSync("bash", [SCRIPT, "workers", tip], {
|
||||
env: { ...process.env, DEPLOY_REPO_DIR: work, DEPLOY_BRANCH: "main" },
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(ok.status).toBe(0);
|
||||
expect(ok.stdout).toContain("succeeded");
|
||||
});
|
||||
});
|
||||
@@ -187,6 +187,17 @@ run_service() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Anti-downgrade (BIT-34038): a redelivered webhook for an older commit is still an ancestor of origin/main, so the
|
||||
# ancestry check in checkout() lets it through and `reset --hard` would move the site backwards (BIT-34036). Only the
|
||||
# tip of origin/main is deployed; anything else is logged and skipped with exit 0 (the receiver reports success, no
|
||||
# action). The newer push has its own webhook. The rollback below goes through checkout() directly, unaffected.
|
||||
git fetch --quiet origin "$BRANCH" || die "git fetch origin $BRANCH failed"
|
||||
TIP="$(git rev-parse "origin/$BRANCH")"
|
||||
if [[ "$SHA" != "$TIP" ]]; then
|
||||
log "SKIP: $SHA is not the tip of origin/$BRANCH ($TIP); refusing to deploy $SERVICE (anti-downgrade)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
PREVIOUS="$(git rev-parse HEAD)"
|
||||
log "deploying $SERVICE: $PREVIOUS -> $SHA"
|
||||
backup_env
|
||||
|
||||
@@ -84,6 +84,10 @@ CFG
|
||||
export APPLE_SIGNING_IDENTITY="$local_id"
|
||||
# Not a Developer ID: no notarisation, so no hardened runtime (it would refuse the bundled ONNX library).
|
||||
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":false}}}')
|
||||
else
|
||||
# Developer ID. Notarisation (when APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID, or the API key, are set)
|
||||
# requires the hardened runtime. The entitlements let the bundled ONNX library load.
|
||||
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":true,"entitlements":"entitlements.plist"}}}')
|
||||
fi
|
||||
echo "Signing as: $APPLE_SIGNING_IDENTITY"
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# WebView2 is the window engine of the Windows installer. Windows 11 already has it.
|
||||
# A desktop-v tag on a Windows runner installs the evergreen runtime when this key is missing.
|
||||
$ErrorActionPreference = "Stop"
|
||||
$key = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
|
||||
if (Test-Path $key) {
|
||||
exit 0
|
||||
}
|
||||
$dest = Join-Path $env:TEMP "webview2-bootstrapper.exe"
|
||||
Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/p/?LinkId=2124703" -OutFile $dest
|
||||
Start-Process $dest -ArgumentList "/silent", "/install" -Wait
|
||||
@@ -61,6 +61,22 @@ export const AutopilotSettings = z.object({
|
||||
* legacy pair below. Empty: use `deliverTargetId` / `restTargetId` when set.
|
||||
*/
|
||||
deliverTargetIds: z.array(z.string().uuid()).max(10).default([]),
|
||||
/**
|
||||
* One frame of each burst per row. `alsoTargetIds` receive that same frame (Cofina Direto and Arquivo) and
|
||||
* are not a separate pick. `count` is how many photos that destination takes over the match (null: no cap).
|
||||
* `originals`: the camera file, without the develop render. Empty: `deliverTargetIds`, one destination each.
|
||||
*/
|
||||
deliverExports: z
|
||||
.array(
|
||||
z.object({
|
||||
targetId: z.string().uuid(),
|
||||
alsoTargetIds: z.array(z.string().uuid()).max(4).default([]),
|
||||
count: z.number().int().min(1).max(2000).nullable().default(null),
|
||||
originals: z.boolean().default(false),
|
||||
}),
|
||||
)
|
||||
.max(10)
|
||||
.default([]),
|
||||
/** Legacy first export (null: don't). Kept for older clients; folded into `deliverTargetIds` when that is empty. */
|
||||
deliverTargetId: z.string().uuid().nullable().default(null),
|
||||
/**
|
||||
@@ -88,6 +104,12 @@ export const AutopilotSettings = z.object({
|
||||
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.
|
||||
*/
|
||||
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>;
|
||||
|
||||
|
||||
@@ -238,6 +238,21 @@ describe("delivery paths", () => {
|
||||
expect(renderFileName(DESTINATION_EXAMPLES.fpaM19.fileName, { ...m19, n: 3 }, "R1_0003.JPG")).toBe("PS_POR x ESP_3.jpg");
|
||||
});
|
||||
|
||||
it("matches the women's under-17 cloud folder", () => {
|
||||
const w17 = buildVars({
|
||||
home: "Portugal",
|
||||
away: "Itália",
|
||||
homeShort: "POR",
|
||||
awayShort: "ITA",
|
||||
competition: "W17 EHF EURO",
|
||||
startsAt: new Date("2026-11-27T19:00:00Z"),
|
||||
});
|
||||
expect(renderFolder(DESTINATION_EXAMPLES.fpaW17.folder, w17)).toBe(
|
||||
"/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA/",
|
||||
);
|
||||
expect(renderFileName(DESTINATION_EXAMPLES.fpaW17.fileName, { ...w17, n: 1 }, "R1_0001.JPG")).toBe("PS_POR x ITA_1.jpg");
|
||||
});
|
||||
|
||||
it("matches the Liga folder and keeps the camera name", () => {
|
||||
const liga = buildVars({ home: "Casa Pia", away: "Sporting", round: 1, matchNumber: 1, startsAt: new Date("2025-08-09T18:00:00Z") });
|
||||
expect(renderFolder(DESTINATION_EXAMPLES.liga.folder, liga)).toBe("/LPBetclic 25-26/Jornada 1/1. Casa Pia x Sporting/");
|
||||
|
||||
@@ -82,6 +82,11 @@ export const DESTINATION_EXAMPLES = {
|
||||
folder: "/FPA/Fotos/{season}/Seleções Nacionais/M19/{dateCompact} - {homeShort} x {awayShort}/",
|
||||
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
|
||||
},
|
||||
/** Women's under-17. Same account as the club cloud; its own folder under Seleções Nacionais. */
|
||||
fpaW17: {
|
||||
folder: "/FPA/Fotos/{season}/Seleções Nacionais/W17/{dateCompact} - {homeShort} x {awayShort}/",
|
||||
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
|
||||
},
|
||||
liga: {
|
||||
folder: "/LPBetclic {seasonShort}/Jornada {round}/{matchNumber}. {home} x {away}/",
|
||||
fileName: "{originalName}",
|
||||
|
||||
Reference in new issue
Block a user