diff --git a/config/recipes/frontend-capability-recipes.json b/config/recipes/frontend-capability-recipes.json index 03df1d6a..4afd4d02 100644 --- a/config/recipes/frontend-capability-recipes.json +++ b/config/recipes/frontend-capability-recipes.json @@ -195,7 +195,7 @@ "lifecycleMethods": ["release-file-ref", "release-or-dispose-preview-leases", "cancel-via-AbortSignal", "reconcile-or-explicitly-abort-upload", "close-checkpoint-store", "dispose-capability-and-image-runtime", "dispose-browser-file-runtime-on-logout-or-account-switch"], "owner": "project-owner-required", "securityPrivacy": ["Treat file name, extension, MIME and lastModified as untrusted metadata.", "Resolve only exact composition-issued file and image policy object identities; callers cannot raise byte, candidate, pixel, quality, format, lifetime or origin ceilings.", "Use opaque file references and verification receipts bound to an inspected immutable file snapshot and the exact registered profile; reject replay through another profile even when an inspection rule ID matches.", "Treat presigned URLs as bearer capabilities; bind exact method, resource or upload part, offset, length, media type, checksum, origin, path, query, headers and expiry in an in-memory identity vault.", "Use credentials omit, redirect error, no-referrer and no-store for direct data-plane fetch; never persist or observe URL, query, signed header, capability, file name or raw backend message, and never emit digest, raw ETag or receipt values to diagnostics or telemetry.", "A strict account-partitioned upload checkpoint may persist only the protocol-defined SHA-256 file fingerprint, per-part checksum and bounded opaque non-authorizing part receipt token required for server reconciliation; no bearer token or raw signed capability is allowed.", "Persist only strict non-authorizing upload checkpoints and reconcile them with server-authoritative status and re-hashed local parts before completion.", "Require a synchronous server-issued browser-managed download capability whose receipt exactly equals the caller's branded capability receipt and whose resource, media type, safe extension, maximum bytes, optional digest and expiry all match before handoff.", "Expose File, OPFS, Cache and transfer byte streams only as chunk-level closed Results; stop after the first failure, cancel native readers and never throw a raw native exception across the port.", "Accept Image CDN assets only through immutable allowlisted or signature-verified descriptors and registered preset identities; reject active formats, arbitrary transforms, pixel/decode-budget overflow and unsafe cache policy.", "Upload completion remains QUARANTINED until backend scan and promotion; client capability checks are not an authorization boundary.", "Active content preview requires isolation or download-only treatment."], - "bundleBudgetGzipBytes": 55800, + "bundleBudgetGzipBytes": 55900, "fallback": "Accessible native file input, same-origin authorized server upload/download and a single bounded server-selected image rendition; generated artifacts above the buffer budget move to server-side generation.", "removal": ["Stop new capability and upload-session issuance, then cancel active reads and transfers.", "Reconcile or explicitly abort active multipart sessions and let backend TTL cleanup remove ambiguous orphans.", "Remove non-secret checkpoints according to account and retention policy.", "Release file references, revoke preview object-URL leases and dispose file, capability and image runtimes.", "Remove transfer/image feature facades and composition, then prove browser-transfer sources are absent from the production module inventory."], "serverStatePolicy": "query-cache-metadata-only" diff --git a/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts b/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts index a76f9499..5c5eb4ee 100644 --- a/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts +++ b/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts @@ -229,6 +229,32 @@ export function createImageCdnRuntime( AssetSnapshot, Set >(); + /** + * 2026-11-01 01-04. The probe phase (slot wait, probe, recording the pass) + * running for an asset+preset pair. It settles only after the pass is + * recorded or the probe failed. Waiting for the raw probe or the slot was + * not enough: the slot is handed on when the raw probe settles, a few + * microtasks before the passing call records its pass. + */ + const probePhases = new WeakMap< + AssetSnapshot, + Map> + >(); + const startProbePhase = ( + asset: AssetSnapshot, + preset: ResolvedImageCdnPreset, + ): (() => void) => { + let settle = () => {}; + const phase = new Promise((resolve) => { + settle = resolve; + }); + const phases = probePhases.get(asset) ?? new Map(); + probePhases.set(asset, phases.set(preset, phase)); + return () => { + if (phases.get(preset) === phase) phases.delete(preset); + settle(); + }; + }; const observer = snapshotObserver(dependencies.observer); let acceptedAssets = new WeakMap(); @@ -590,89 +616,115 @@ export function createImageCdnRuntime( if (!probe || !request.signal) { return browserDataFailure("UNSUPPORTED", "IMAGE_RESOLVE"); } - const primary = primaryCandidate(preset); - let probeResult: BrowserDataResult; - const probeScope = openOperation(request.signal); - try { - const slot = await probeScope.race( - acquireProbeSlot(), - releaseProbeSlot, - ); - if (slot.kind !== "VALUE") { - throw capabilityVerificationAbortException(); - } - let task: Promise>; + // 2026-11-01 01-04. A probe of the same asset and preset that is + // already running is waited out, and its recorded pass reused. Only + // the wait is shared: each call keeps its own signal, and a failed + // probe is not reused, so the waiting call then probes for itself. + // The passing call checked expiry when it recorded the pass, in the + // same task this wait resumes in. + const running = probePhases.get(asset)?.get(preset); + if (running) { + const waitScope = openOperation(request.signal); try { - task = Promise.resolve(probe({ - absoluteUrl: descriptor.src, - expectedMediaType: descriptor.fallbackMediaType, - expectedWidth: primary.pixelWidth, - expectedHeight: primary.pixelHeight, - maxEncodedBytes: preset.maxEncodedBytes, - maxDecodedPixels: preset.maxTransformedPixels, - maxDecodedBytes: preset.maxDecodedBytes, - delivery: asset.delivery, - minimumPublicMaxAgeSeconds: - asset.origin.minimumPublicMaxAgeSeconds, - referrerPolicy: descriptor.referrerPolicy, - signal: probeScope.signal, - })); - } catch (error) { - task = Promise.reject(error); + await raceImageRuntime(waitScope, running); + } catch { + return closed + ? imageRuntimeClosedFailure() + : browserDataFailure("ABORTED", "IMAGE_RESOLVE"); + } finally { + closeOperation(waitScope); } - // The slot belongs to the raw probe, not to this wrapper (as for - // capability verification, TR-RR-07). - void task.then(releaseProbeSlot, releaseProbeSlot); - probeResult = await raceImageRuntime(probeScope, task); - } catch { - probeResult = closed - ? imageRuntimeClosedFailure() - : request.signal.aborted - ? browserDataFailure("ABORTED", "IMAGE_RESOLVE") - : browserDataFailure("UNAVAILABLE", "IMAGE_RESOLVE", { - retryable: true, - recovery: "RETRY", - }); - } finally { - closeOperation(probeScope); } - if (closed) probeResult = imageRuntimeClosedFailure(); - observeImageTerminal( - observer, - probeResult, - 1, - probeResult.ok - ? probeResult.value.encodedBytes - : undefined, - ); - if (!probeResult.ok) return probeResult; - if ( - !validProbeReceipt( - probeResult.value, - descriptor.src, - descriptor.fallbackMediaType, - primary, - preset.maxEncodedBytes, - ) - ) { - return browserDataFailure( - "INTEGRITY_FAILED", - "IMAGE_RESOLVE", - ); + if (!passedProbes.get(asset)?.has(preset)) { + const endProbePhase = startProbePhase(asset, preset); + try { + const primary = primaryCandidate(preset); + let probeResult: BrowserDataResult; + const probeScope = openOperation(request.signal); + try { + const slot = await probeScope.race( + acquireProbeSlot(), + releaseProbeSlot, + ); + if (slot.kind !== "VALUE") { + throw capabilityVerificationAbortException(); + } + let task: Promise>; + try { + task = Promise.resolve(probe({ + absoluteUrl: descriptor.src, + expectedMediaType: descriptor.fallbackMediaType, + expectedWidth: primary.pixelWidth, + expectedHeight: primary.pixelHeight, + maxEncodedBytes: preset.maxEncodedBytes, + maxDecodedPixels: preset.maxTransformedPixels, + maxDecodedBytes: preset.maxDecodedBytes, + delivery: asset.delivery, + minimumPublicMaxAgeSeconds: + asset.origin.minimumPublicMaxAgeSeconds, + referrerPolicy: descriptor.referrerPolicy, + signal: probeScope.signal, + })); + } catch (error) { + task = Promise.reject(error); + } + // The slot belongs to the raw probe, not to this wrapper (as for + // capability verification, TR-RR-07). + void task.then(releaseProbeSlot, releaseProbeSlot); + probeResult = await raceImageRuntime(probeScope, task); + } catch { + probeResult = closed + ? imageRuntimeClosedFailure() + : request.signal.aborted + ? browserDataFailure("ABORTED", "IMAGE_RESOLVE") + : browserDataFailure("UNAVAILABLE", "IMAGE_RESOLVE", { + retryable: true, + recovery: "RETRY", + }); + } finally { + closeOperation(probeScope); + } + if (closed) probeResult = imageRuntimeClosedFailure(); + observeImageTerminal( + observer, + probeResult, + 1, + probeResult.ok + ? probeResult.value.encodedBytes + : undefined, + ); + if (!probeResult.ok) return probeResult; + if ( + !validProbeReceipt( + probeResult.value, + descriptor.src, + descriptor.fallbackMediaType, + primary, + preset.maxEncodedBytes, + ) + ) { + return browserDataFailure( + "INTEGRITY_FAILED", + "IMAGE_RESOLVE", + ); + } + if (request.signal.aborted) { + return browserDataFailure("ABORTED", "IMAGE_RESOLVE"); + } + const postProbeExpiry = checkExpiry( + asset, + now, + hardLimits.minCapabilityRemainingMs, + ); + if (postProbeExpiry) return postProbeExpiry; + passedProbes.set( + asset, + (passedProbes.get(asset) ?? new Set()).add(preset), + ); + } finally { + endProbePhase(); + } } - if (request.signal.aborted) { - return browserDataFailure("ABORTED", "IMAGE_RESOLVE"); - } - const postProbeExpiry = checkExpiry( - asset, - now, - hardLimits.minCapabilityRemainingMs, - ); - if (postProbeExpiry) return postProbeExpiry; - passedProbes.set( - asset, - (passedProbes.get(asset) ?? new Set()).add(preset), - ); } if (closed) return imageRuntimeClosedFailure(); diff --git a/tests/unit/image-cdn-runtime.test.ts b/tests/unit/image-cdn-runtime.test.ts index cc9f3b48..4fa90623 100644 --- a/tests/unit/image-cdn-runtime.test.ts +++ b/tests/unit/image-cdn-runtime.test.ts @@ -5,6 +5,7 @@ import type { ImageCapabilityVerifier, ImagePresetReference, ImageProbeRequest, + ImageResourceProbePort, PublicImmutableImageAsset, } from "../../src/application/ports/browser-transfer/image-cdn.ts"; import { @@ -1537,6 +1538,97 @@ describe("image probe cost (01-11)", () => { expect(peak).toBe(2); }); + describe("one asset resolved by several calls at once (2026-11-01 01-04)", () => { + const unavailable = { + ok: false as const, + error: { + code: "UNAVAILABLE" as const, + operation: "IMAGE_RESOLVE" as const, + retryable: true, + recovery: "RETRY" as const, + }, + }; + const sharedAsset = (probe: ImageResourceProbePort["probe"]) => { + const runtime = createImageCdnRuntime({ + policies: policies(), + probe: { probe }, + maxConcurrentProbes: 2, + }); + const accepted = runtime.assets.acceptPublicImmutable(publicAsset()); + if (!accepted.ok) throw new Error("accept failed"); + return (signal = new AbortController().signal) => + runtime.presentation.resolve({ asset: accepted.value, preset, signal }); + }; + const gated = () => { + let open = () => {}; + const gate = new Promise((resolve) => { + open = resolve; + }); + return { gate, open }; + }; + + it("probes once and lets the other calls reuse the pass", async () => { + const { gate, open } = gated(); + // Only the first probe waits for the gate; a duplicate probe would + // answer at once and show up as an extra call. + const probe = vi.fn(async (request: ImageProbeRequest) => { + if (probe.mock.calls.length === 1) await gate; + return receipt(request); + }); + const resolve = sharedAsset(probe); + + const pending = Array.from({ length: 5 }, () => resolve()); + await vi.waitFor(() => expect(probe).toHaveBeenCalled()); + open(); + const results = await Promise.all(pending); + + expect(results.every((result) => result.ok)).toBe(true); + expect(probe).toHaveBeenCalledTimes(1); + }); + + it("probes again for a waiting call when the running probe fails", async () => { + const { gate, open } = gated(); + const probe = vi.fn(async (request: ImageProbeRequest) => { + if (probe.mock.calls.length > 1) return receipt(request); + await gate; + return unavailable; + }); + const resolve = sharedAsset(probe); + + const first = resolve(); + const waiting = resolve(); + await vi.waitFor(() => expect(probe).toHaveBeenCalled()); + open(); + + expect((await first).ok).toBe(false); + expect((await waiting).ok).toBe(true); + expect(probe).toHaveBeenCalledTimes(2); + }); + + it("lets a waiting call abort without ending the running probe", async () => { + const { gate, open } = gated(); + const probe = vi.fn(async (request: ImageProbeRequest) => { + await gate; + return receipt(request); + }); + const resolve = sharedAsset(probe); + + const running = resolve(); + await vi.waitFor(() => expect(probe).toHaveBeenCalled()); + const controller = new AbortController(); + const waiting = resolve(controller.signal); + controller.abort(); + + expect(await waiting).toMatchObject({ + ok: false, + error: { code: "ABORTED" }, + }); + open(); + expect((await running).ok).toBe(true); + expect(probe).toHaveBeenCalledTimes(1); + }); + }); + it("gives a waiting caller's slot back when it aborts before its turn", async () => { const releases: (() => void)[] = []; const probe = vi.fn(async (request: ImageProbeRequest) => {