Keep ZeroZero uploads alive when the worker is busy.
ci / rust (push) Successful in 4m11s
ci / typescript (push) Successful in 7m20s

Cap face analysis at what one Node thread can commit, prefer IPv4 so a dead IPv6 route cannot fail the fetch, and leave a photo on the desk when ZeroZero says it is already there. Desktop originals go out one at a time so the app does not freeze on "A enviar…".
This commit is contained in:
1sonhador committed 2026-10-15 20:14:04 +01:00
1 parent 673a06c9dd
commit 1fa97ca3bb
9 files changed
+116 -26

No files matched your search

+6 -3
View File
@@ -336,11 +336,14 @@ export class DeliveryService {
const creator = typeof iptc?.values.creator === "string" ? iptc.values.creator.split(" / ")[0]!.trim() : "";
const remote = await client.upload(folder + fileName, data, { author: creator || item.photo.uploader?.name || undefined });
const remotePath = typeof remote === "string" ? remote : folder + fileName;
// The new version is up: the previous one is taken back where a new upload does not replace it (ZeroZero).
if (item.replacesPath && item.replacesPath !== remotePath && client instanceof ZerozeroTransport) {
// "synced-…" means the desk already had this file, so this attempt did not put a new image up.
// Taking the previous one back here would remove the only copy (the new upload never landed).
const alreadyThere = remotePath.includes("/synced-");
if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath && client instanceof ZerozeroTransport) {
await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous version not taken back"));
}
update = { status: "DONE", remotePath, byteSize: data.length, lastError: null, finishedAt: new Date(), deliveredSeq: item.photo.developSeq, replacesPath: null };
const storedPath = alreadyThere && item.replacesPath ? item.replacesPath : remotePath;
update = { status: "DONE", remotePath: storedPath, byteSize: data.length, lastError: null, finishedAt: new Date(), deliveredSeq: item.photo.developSeq, replacesPath: null };
log.info({ itemId, remotePath }, "delivery: uploaded");
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
+14 -1
View File
@@ -77,6 +77,19 @@ function splitSetCookie(v: string | null): string[] {
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
/** `fetch` hides the socket error on `cause`. Keep the code (ETIMEDOUT, ECONNRESET, …) in the delivery error. */
export function fetchFailure(err: unknown): string {
const error = err as { message?: string; cause?: { code?: string; message?: string; errors?: { code?: string }[] } };
const message = error?.message || "fetch failed";
const cause = error?.cause;
const codes = new Set<string>();
if (cause?.code) codes.add(cause.code);
for (const item of cause?.errors ?? []) if (item.code) codes.add(item.code);
const extra = [...codes];
if (!extra.length && cause?.message && cause.message !== message) extra.push(cause.message);
return extra.length ? `${message} (${extra.join(", ")})` : message;
}
export class ZerozeroClient {
private readonly jar = new CookieJar();
private account: { role: string; name: string | null } | null = null;
@@ -103,7 +116,7 @@ export class ZerozeroClient {
try {
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (err) {
throw new TransportError(`zerozero: ${(err as Error).message}`, true);
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
}
this.jar.store(current, res.headers);
const location = res.headers.get("location");
+4 -2
View File
@@ -43,8 +43,10 @@ export function planCapacity(
return {
cpus,
memoryGb: Math.round(memoryGb * 10) / 10,
// Face processes wait idle when there is nothing to analyse (memory only): enough for an archive's backlog.
faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 64),
// Face binaries use the cores and wait idle when there is nothing to analyse. Their results are committed
// by this one Node thread, which also uploads to ZeroZero. Dozens at once stall that thread: deliveries
// fail with "fetch failed" and face transactions expire. FACES_PROCESSES in the environment still overrides.
faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 6),
ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32),
archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32),
// A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share.
+12
View File
@@ -0,0 +1,12 @@
import { setDefaultResultOrder } from "node:dns";
import { setDefaultAutoSelectFamily } from "node:net";
/**
* Use IPv4 only. fotos.zerozero.pt (Cloudflare) publishes IPv6 addresses this network cannot reach.
* Happy Eyeballs then fails the whole request ("fetch failed") even though IPv4 is fine.
* Call before any request. An IPv6-only host would need this removed.
*/
export function preferIpv4(): void {
setDefaultResultOrder("ipv4first");
setDefaultAutoSelectFamily(false);
}
+2
View File
@@ -1,7 +1,9 @@
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { buildApp, reporterFor } from "./app.js";
import { loadConfig } from "./config.js";
import { createDb } from "./db.js";
preferIpv4();
const config = loadConfig();
const db = createDb(config.DATABASE_URL);
const reporter = reporterFor(config);
+2
View File
@@ -1,6 +1,7 @@
import { existsSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { reporterFor } from "./lib/reporter.js";
import pino from "pino";
import { loadConfig } from "./config.js";
@@ -32,6 +33,7 @@ import { InvoicingService, InvoicingWorker } from "./invoicing/service.js";
* Background worker: FTP ingest and the delivery queue. One per installation, next to the SFTPGo drop folder
* and the storage (PM2 app `photoreport-worker`, never clustered: it owns the drop folder).
*/
preferIpv4();
const config = loadConfig();
// Error lines (and warnings carrying an error) also go to errors.bitreport.pt, as do crashes.
const reporter = reporterFor(config);
+2 -2
View File
@@ -8,8 +8,8 @@ describe("capacity", () => {
const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB });
const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB });
expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, delivery: 4 });
expect(big).toMatchObject({ cpus: 32, faces: 28, ingest: 8, archive: 9, archiveBurst: 91, render: 4, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 38, archiveBurst: 91, archiveDownloads: 960 });
expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 4, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 6, archiveBurst: 91, archiveDownloads: 960 });
// A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine.
expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 });
});
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { fetchFailure } from "../src/delivery/zerozero.js";
describe("zerozero fetch errors", () => {
it("keeps the socket code that fetch hides on cause", () => {
const err = new TypeError("fetch failed");
(err as { cause?: unknown }).cause = { code: "ETIMEDOUT", message: "connect ETIMEDOUT" };
expect(fetchFailure(err)).toBe("fetch failed (ETIMEDOUT)");
});
it("joins every address error when happy eyeballs fails them all", () => {
const err = new TypeError("fetch failed");
(err as { cause?: unknown }).cause = { errors: [{ code: "ENETUNREACH" }, { code: "ECONNREFUSED" }] };
expect(fetchFailure(err)).toBe("fetch failed (ENETUNREACH, ECONNREFUSED)");
});
});
+58 -18
View File
@@ -39,34 +39,74 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
);
}
/** Several megabytes through IPC. Dozens at once freeze the webview on "A enviar…" and the send never finishes. */
const ORIGINAL_IPC_MS = 45_000;
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
return new Promise((resolve) => {
let settled = false;
const finish = (value: T | "timeout" | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const timer = setTimeout(() => finish("timeout"), ms);
work.then(
(value) => finish(value),
() => finish(null),
);
});
}
/**
* Desktop app: when someone needs the full original of a photo this computer keeps (100% zoom on the web, an export
* made on the server), the server asks over the live channel and this sends it in the background.
* made on the server, delivery to ZeroZero), the server asks over the live channel and this sends it.
* One original at a time, so the webview stays responsive and the next ask can run.
*/
function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"]; add: ReturnType<typeof useUploadQueue>["add"] }) {
const sending = useRef(new Set<string>());
const queue = useRef<{ sha256: string; photoId: string }[]>([]);
const busy = useRef(false);
const pump = useCallback(() => {
if (busy.current) return;
const next = queue.current.shift();
if (!next) return;
busy.current = true;
const release = () => {
sending.current.delete(next.sha256);
busy.current = false;
pump();
};
void (async () => {
const bytes = await withTimeout(localOriginal(next.sha256), ORIGINAL_IPC_MS);
if (bytes && bytes !== "timeout") {
add([new File([bytes], `${next.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => release());
return;
}
if (bytes !== "timeout") {
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
// photo's original, which the server checks is the same photo.
try {
const changed = await withTimeout(localOriginalChanged(next.sha256), ORIGINAL_IPC_MS);
if (changed && changed !== "timeout") await api.sendOriginal(next.photoId, new Blob([changed], { type: "image/jpeg" }), `${next.sha256}.jpg`);
} catch {
/* not the same photo, or offline: asked again later */
}
}
release();
})();
}, [add, api]);
const onMessage = useCallback(
(m: LibraryMessage) => {
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
sending.current.add(m.sha256);
void localOriginal(m.sha256).then(async (bytes) => {
if (bytes) {
add([new File([bytes], `${m.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => sending.current.delete(m.sha256));
return;
}
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
// photo's original, which the server checks is the same photo.
try {
const changed = await localOriginalChanged(m.sha256);
if (changed) await api.sendOriginal(m.photoId, new Blob([changed], { type: "image/jpeg" }), `${m.sha256}.jpg`);
} catch {
/* not the same photo, or offline: asked again later */
} finally {
sending.current.delete(m.sha256);
}
});
queue.current.push({ sha256: m.sha256, photoId: m.photoId });
pump();
},
[add, api],
[pump],
);
useLibraryLive(api, onMessage);
return null;