From 4f5a2fd48421d7180c69b8d3c4877952f1fb4978 Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 19 Oct 2026 16:43:21 +0100 Subject: [PATCH] Retry an upload chunk when the access token expires mid-send. Reading several full originals at once froze the desktop webview, so a chunk left after the 15-minute token had expired and the photo was marked failed. --- apps/app/src/library/LocalFtp.tsx | 8 ++- apps/app/src/library/uploads.test.ts | 86 ++++++++++++++++++++++++++++ apps/app/src/library/uploads.ts | 37 ++++++++---- packages/sdk/src/client.test.ts | 40 +++++++++++++ packages/sdk/src/client.ts | 19 ++++-- 5 files changed, 174 insertions(+), 16 deletions(-) create mode 100644 apps/app/src/library/uploads.test.ts diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index 711626a..4edc306 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -52,6 +52,11 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/ /** Photos read from disk and in the upload queue at once (each is held in memory until sent). */ const IN_FLIGHT = 6; +/** + * Full originals are read through the webview as well. Several at once freeze it, a chunk sits until the access + * token expires, and the server answers 401. Two leaves room for the upload to leave. + */ +const IN_FLIGHT_ORIGINALS = 2; const POLL_MS = 1000; /** The shell put the file back on the queue because the camera has not finished sending it. */ @@ -106,7 +111,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn }, []); const pump = useCallback(() => { - while (inFlight.current < IN_FLIGHT && backlog.current.length) { + const room = originalsRef.current ? IN_FLIGHT_ORIGINALS : IN_FLIGHT; + while (inFlight.current < room && backlog.current.length) { const f = backlog.current.shift()!; const to = targetRef.current; inFlight.current++; diff --git a/apps/app/src/library/uploads.test.ts b/apps/app/src/library/uploads.test.ts new file mode 100644 index 0000000..4108941 --- /dev/null +++ b/apps/app/src/library/uploads.test.ts @@ -0,0 +1,86 @@ +import type { ApiClient } from "@photoreport/sdk"; +import { afterEach, describe, expect, it } from "vitest"; +import { sendResumable } from "./uploads.js"; + +class FakeXHR { + static handler: (method: string, url: string, auth: string) => { status: number; body: unknown } = () => ({ status: 500, body: {} }); + method = ""; + url = ""; + auth = ""; + status = 0; + responseText = ""; + timeout = 0; + upload = { onprogress: null as ((e: { loaded: number }) => void) | null }; + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + ontimeout: (() => void) | null = null; + open(method: string, url: string) { + this.method = method; + this.url = url; + } + setRequestHeader(name: string, value: string) { + if (name.toLowerCase() === "authorization") this.auth = value; + } + send() { + const res = FakeXHR.handler(this.method, this.url, this.auth); + this.status = res.status; + this.responseText = JSON.stringify(res.body); + this.onload?.(); + } +} + +const realXHR = globalThis.XMLHttpRequest; + +afterEach(() => { + globalThis.XMLHttpRequest = realXHR; +}); + +function apiWith(start: string) { + let token = start; + const replaced: string[] = []; + const api = { + absolute: (path: string) => `https://api${path}`, + realtimeToken: async () => token, + replaceRejectedToken: async (rejected: string) => { + replaced.push(rejected); + token = "new"; + return token; + }, + } as unknown as ApiClient; + return { api, replaced }; +} + +describe("sendResumable", () => { + it("refreshes and sends the same chunk again when the token expired", async () => { + globalThis.XMLHttpRequest = FakeXHR as unknown as typeof XMLHttpRequest; + const puts: string[] = []; + FakeXHR.handler = (method, url, auth) => { + if (method === "POST") return { status: 201, body: { id: "up-1", offset: 0, size: 8 } }; + puts.push(auth); + if (auth === "Bearer old") return { status: 401, body: { error: "invalid_access_token" } }; + return { status: 201, body: { offset: 8, status: "ingested" } }; + }; + const { api, replaced } = apiWith("old"); + const file = new File([new Uint8Array(8)], "PSR.JPG", { type: "image/jpeg" }); + const res = await sendResumable(api, "org", file, "event", () => {}); + expect(res.status).toBe(201); + expect(puts).toEqual(["Bearer old", "Bearer new"]); + expect(replaced).toEqual(["old"]); + }); + + it("does not retry a refusal that is not an expired token", async () => { + globalThis.XMLHttpRequest = FakeXHR as unknown as typeof XMLHttpRequest; + let puts = 0; + FakeXHR.handler = (method) => { + if (method === "POST") return { status: 201, body: { id: "up-1", offset: 0, size: 8 } }; + puts++; + return { status: 415, body: { error: "unsupported_type" } }; + }; + const { api, replaced } = apiWith("old"); + const file = new File([new Uint8Array(8)], "PSR.JPG", { type: "image/jpeg" }); + const res = await sendResumable(api, "org", file, undefined, () => {}); + expect(res.status).toBe(415); + expect(puts).toBe(1); + expect(replaced).toEqual([]); + }); +}); diff --git a/apps/app/src/library/uploads.ts b/apps/app/src/library/uploads.ts index 79e1066..2df6b31 100644 --- a/apps/app/src/library/uploads.ts +++ b/apps/app/src/library/uploads.ts @@ -1,5 +1,5 @@ import type { PhotoSummary } from "@photoreport/contracts"; -import type { ApiClient } from "@photoreport/sdk"; +import { ApiError, type ApiClient } from "@photoreport/sdk"; import { isNetworkError } from "../offline/queue.js"; import { useCallback, useRef, useState } from "react"; @@ -19,6 +19,8 @@ const ACCEPTED = /\.jpe?g$/i; const CHUNK = 4 * 1024 * 1024; const RETRIES = 8; +/** A chunk can wait this long behind other photos being read. Start it with a token that still outlasts that. */ +const CHUNK_TOKEN_SEC = 180; function xhr( method: string, @@ -77,29 +79,34 @@ export async function sendResumable( origin?: DesktopOrigin, ): Promise<{ status: number; body: unknown }> { const fingerprint = `${file.name}:${file.size}:${file.lastModified}`; - const begin = await xhr( - "POST", - api.absolute(`/v1/orgs/${orgId}/uploads/resumable`), - await api.realtimeToken(), - JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }), - "application/json", - ); + const beginBody = JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }); + let failures = 0; + let begin: { status: number; body: unknown }; + for (;;) { + const token = await api.realtimeToken(CHUNK_TOKEN_SEC); + begin = await xhr("POST", api.absolute(`/v1/orgs/${orgId}/uploads/resumable`), token, beginBody, "application/json"); + if (begin.status !== 401) break; + if (++failures > RETRIES) return begin; + await api.replaceRejectedToken(token); + await sleep(Math.min(5_000, 400 * failures)); + } if (begin.status !== 200 && begin.status !== 201) return begin; // The server already has this photo (a preview of it, or the original): nothing to send. if ((begin.body as { status?: string }).status === "duplicate") return begin; const { id } = begin.body as { id: string }; let offset = (begin.body as { offset: number }).offset; - let failures = 0; /** The last bytes went out: the server may be busy filing the photo, or already done with it. */ let sentAll = false; for (;;) { const end = Math.min(file.size, offset + CHUNK); const last = end >= file.size; + let token = ""; try { + token = await api.realtimeToken(CHUNK_TOKEN_SEC); const res = await xhr( "PUT", api.absolute(`/v1/uploads/${id}?offset=${offset}`), - await api.realtimeToken(), + token, file.slice(offset, end), "application/offset+octet-stream", (loaded) => onProgress((offset + loaded) / file.size), @@ -108,6 +115,13 @@ export async function sendResumable( ); // The upload is gone after all bytes went out earlier: the server filed the photo and our answer was lost. if (res.status === 404 && sentAll) return { status: 201, body: { status: "created" } }; + // Expired while this chunk waited to leave the computer. The server did not keep these bytes. + if (res.status === 401) { + if (++failures > RETRIES) return res; + await api.replaceRejectedToken(token); + await sleep(Math.min(5_000, 400 * failures)); + continue; + } if (last) sentAll = true; if (res.status === 409) { offset = (res.body as { offset: number }).offset; @@ -120,10 +134,11 @@ export async function sendResumable( onProgress(offset / file.size); if (offset >= file.size) return res; } catch (err) { + if (err instanceof ApiError && err.status === 401) throw err; if (++failures > RETRIES) throw err; await sleep(Math.min(30_000, 1000 * 2 ** failures)); // Where did the server get to? - const at = await xhr("GET", api.absolute(`/v1/uploads/${id}`), await api.realtimeToken(), null, "").catch(() => null); + const at = await xhr("GET", api.absolute(`/v1/uploads/${id}`), await api.realtimeToken(CHUNK_TOKEN_SEC), null, "").catch(() => null); if (at?.status === 200) offset = (at.body as { offset: number }).offset; else if (at?.status === 404 && (sentAll || last)) return { status: 201, body: { status: "created" } }; } diff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.ts index a9fe3e6..58f7858 100644 --- a/packages/sdk/src/client.test.ts +++ b/packages/sdk/src/client.test.ts @@ -89,6 +89,46 @@ describe("ApiClient", () => { expect(lost).toHaveBeenCalledOnce(); }); + function jwt(secondsFromNow: number): string { + const exp = Math.floor(Date.now() / 1000) + secondsFromNow; + const payload = btoa(JSON.stringify({ exp })).replace(/\+/g, "-").replace(/\//g, "_"); + return `h.${payload}.s`; + } + + it("refreshes a token that would expire during an upload", async () => { + const soon = jwt(500); + const later = jwt(900); + let refreshes = 0; + const { fetch } = fakeFetch((url) => { + if (!url.endsWith("/refresh")) return { status: 200, body: {} }; + refreshes++; + return { status: 200, body: { accessToken: later, expiresIn: 900 } }; + }); + const api = new ApiClient({ baseUrl: "https://api", fetch, refreshStore: memoryStore("r") }); + (api as unknown as { accessToken: string }).accessToken = soon; + expect(await api.realtimeToken()).toBe(soon); + expect(await api.realtimeToken(600)).toBe(later); + expect(refreshes).toBe(1); + }); + + it("replaces a rejected token once for every caller that still holds it", async () => { + const old = jwt(120); + const next = jwt(900); + let refreshes = 0; + const { fetch } = fakeFetch((url) => { + if (!url.endsWith("/refresh")) return { status: 200, body: {} }; + refreshes++; + return { status: 200, body: { accessToken: next, expiresIn: 900 } }; + }); + const api = new ApiClient({ baseUrl: "https://api", fetch, refreshStore: memoryStore("r") }); + (api as unknown as { accessToken: string }).accessToken = old; + const got = await Promise.all([api.replaceRejectedToken(old), api.replaceRejectedToken(old), api.replaceRejectedToken(old)]); + expect(got).toEqual([next, next, next]); + expect(refreshes).toBe(1); + expect(await api.replaceRejectedToken(old)).toBe(next); + expect(refreshes).toBe(1); + }); + it("maps device polling errors", async () => { const answers = ["authorization_pending", "slow_down", "access_denied", "expired_token"]; const { fetch } = fakeFetch(() => ({ status: 400, body: { error: answers.shift() } })); diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 7543947..a6cb157 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -78,11 +78,22 @@ export class ApiClient { } /** - * An access token valid for at least another minute, for connections the client makes itself (realtime, - * uploads with progress through XMLHttpRequest). + * An access token valid for at least `minValidSeconds` (a minute, unless the caller says otherwise), for + * connections the client makes itself (realtime, uploads with progress through XMLHttpRequest). + * A chunk can sit in the webview while other photos are read from disk; the server rejects it once it expires. */ - async realtimeToken(): Promise { - if ((!this.accessToken || expiresWithin(this.accessToken, 60)) && !(await this.refresh())) throw new ApiError(401, "not_signed_in", null); + async realtimeToken(minValidSeconds = 60): Promise { + if ((!this.accessToken || expiresWithin(this.accessToken, minValidSeconds)) && !(await this.refresh())) throw new ApiError(401, "not_signed_in", null); + return this.accessToken as string; + } + + /** + * A new access token after a request that used `rejected` came back 401. Callers still holding that token share + * one refresh, so several uploads failing together rotate the session once. + */ + async replaceRejectedToken(rejected: string): Promise { + if (this.accessToken && this.accessToken !== rejected && !expiresWithin(this.accessToken, 60)) return this.accessToken; + if (!(await this.refresh())) throw new ApiError(401, "not_signed_in", null); return this.accessToken as string; } -- 2.47.3