LCOV - code coverage report
Current view: top level - src/platform/telemetry - imageFailureDiagnostics.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 92.5 % 40 37
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { ImageLoadFailureMetadata } from '@comfyorg/telemetry/types'
       2              : 
       3              : /**
       4              :  * An `<img>` `error` event carries no status, no headers and no body — the
       5              :  * browser tells you it failed and nothing else. That is why FE-1595 needed the
       6              :  * reporting artist's Network tab: `app:image_load_failed` fired on every broken
       7              :  * preview but could not say whether the cause was an expired session cookie
       8              :  * (401), a missing output (404), or a dropped connection.
       9              :  *
      10              :  * So we re-request the same URL once, only after a failure, and report the
      11              :  * status the browser would not give us. The probe is deliberately cheap and
      12              :  * deliberately incapable of making things worse:
      13              :  *
      14              :  * - `Range: bytes=0-0` asks for a single byte, so a probe of a 20MB output does
      15              :  *   not re-download it. Servers that ignore `Range` answer 200 with the body,
      16              :  *   which is why the response is never read.
      17              :  * - `credentials: 'include'` mirrors how the browser sent the original `<img>`
      18              :  *   request. Probing without it would send no cookie and manufacture the very
      19              :  *   401 we are trying to measure.
      20              :  * - Failures resolve to `probe_failed`/`probe_blocked` rather than throwing. A
      21              :  *   diagnostic must never become the second error in the report.
      22              :  */
      23              : 
      24              : /** Probes are capped per page so a node retrying a missing file in a loop cannot amplify. */
      25         2356 : const MAX_PROBES_PER_PAGE = 20
      26              : 
      27              : /**
      28              :  * A probe that outlives this is worth less than the request it occupies. Kept
      29              :  * short because the report is emitted after it: a long budget turns every
      30              :  * failed image into a window where a page unload loses the event entirely.
      31              :  */
      32         2356 : const PROBE_TIMEOUT_MS = 2_000
      33              : 
      34         2356 : let probesIssued = 0
      35              : 
      36              : /** Test seam — the cap is module state that would otherwise leak across cases. */
      37              : export function resetImageFailureProbesForTest(): void {
      38              :   probesIssued = 0
      39              : }
      40              : 
      41              : /**
      42              :  * `type` in an `/api/view` URL distinguishes a generated output from a user
      43              :  * upload. A 404 on `output` means the result expired or was swept; a 404 on
      44              :  * `input` means the upload never landed. They are different bugs and the
      45              :  * current event cannot tell them apart.
      46              :  */
      47           83 : function resourceKind(url: URL): ImageLoadFailureMetadata['resource_kind'] {
      48           83 :   const type = url.searchParams.get('type')
      49           83 :   if (type === 'output' || type === 'input' || type === 'temp') return type
      50           83 :   return url.searchParams.has('filename') ? 'unspecified' : 'not_api_view'
      51              : }
      52              : 
      53              : /**
      54              :  * The filename shape separates "a generation we produced" from "a template
      55              :  * asset we ship". Template thumbnails 404ing is a packaging bug on our side;
      56              :  * a hashed output 404ing is a retention/lifecycle bug. Reporting the shape
      57              :  * rather than the name keeps user-authored filenames out of telemetry.
      58              :  */
      59           83 : function filenameKind(url: URL): ImageLoadFailureMetadata['filename_kind'] {
      60           83 :   const filename = url.searchParams.get('filename')
      61           83 :   if (!filename) return 'none'
      62           83 :   if (filename.startsWith('template-')) return 'template'
      63           83 :   if (/^[0-9a-f]{64}\./i.test(filename)) return 'content_hash'
      64           83 :   return 'named'
      65              : }
      66              : 
      67              : /**
      68              :  * Resolves if the page starts going away, so a pending probe cannot hold the
      69              :  * report hostage. Never resolves otherwise — it only ever loses the race.
      70              :  *
      71              :  * The caller aborts `signal` once the race settles. Without that the listener
      72              :  * outlives every probe that wins, and this runs on *every* failed image —
      73              :  * including those past the probe cap, where a node retrying a missing file can
      74              :  * produce hundreds in one session.
      75              :  */
      76           83 : function abandonOnUnload(
      77              :   signal: AbortSignal
      78              : ): Promise<Pick<ImageLoadFailureMetadata, 'probe_outcome'>> {
      79           83 :   return new Promise((resolve) => {
      80           83 :     window.addEventListener(
      81              :       'pagehide',
      82              :       () => resolve({ probe_outcome: 'probe_abandoned' }),
      83              :       { once: true, signal }
      84              :     )
      85              :   })
      86              : }
      87              : 
      88           83 : async function probeStatus(
      89              :   src: string
      90              : ): Promise<Pick<ImageLoadFailureMetadata, 'status' | 'probe_outcome'>> {
      91           83 :   if (probesIssued >= MAX_PROBES_PER_PAGE) {
      92            0 :     return { probe_outcome: 'probe_capped' }
      93              :   }
      94           83 :   probesIssued += 1
      95              : 
      96           83 :   try {
      97           83 :     const response = await fetch(src, {
      98              :       method: 'GET',
      99              :       credentials: 'include',
     100              :       headers: { Range: 'bytes=0-0' },
     101              :       // Our own status is the finding. Following a redirect would report the
     102              :       // status of wherever `/api/view` sent us — a signed storage URL answering
     103              :       // 200 or 403 on its own terms — and attribute it to our endpoint.
     104              :       redirect: 'manual',
     105              :       signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
     106              :     })
     107              :     // A manual-redirect response is opaque: status reads 0 and no header is
     108              :     // legible. That the endpoint redirected is still the answer, so it gets its
     109              :     // own outcome rather than being reported as a status of 0.
     110           81 :     if (response.type === 'opaqueredirect') {
     111            0 :       return { probe_outcome: 'probe_redirected' }
     112              :     }
     113              :     // The body is never read: `Range` already bounded it, and cancelling here
     114              :     // releases the connection instead of buffering an image we will not show.
     115              :     // A cancel on an already-errored body rejects, and an unhandled rejection
     116              :     // becomes a spurious Sentry report — so it is swallowed explicitly.
     117           83 :     void response.body?.cancel().catch(() => {})
     118           83 :     return { status: response.status, probe_outcome: 'probed' }
     119              :   } catch (error) {
     120              :     // An opaque/CORS/offline failure is itself the finding: the request never
     121              :     // reached a server that could answer, so no status exists to report.
     122            1 :     return {
     123              :       probe_outcome:
     124              :         error instanceof DOMException && error.name === 'TimeoutError'
     125              :           ? 'probe_timeout'
     126              :           : 'probe_failed'
     127              :     }
     128              :   }
     129              : }
     130              : 
     131              : /**
     132              :  * Builds the metadata for one failed preview. Never throws and never rejects.
     133              :  *
     134              :  * `page_age_ms` is the field that would have identified FE-1595 on its own: the
     135              :  * session-cookie bug could only strike a page open longer than the cookie's
     136              :  * 2-hour life, so an auth-caused failure population skews old while a 404
     137              :  * population does not. It is page age, not session age — a reload mints a fresh
     138              :  * cookie, which is exactly the boundary that matters.
     139              :  */
     140           83 : export async function describeImageLoadFailure(
     141              :   src: string
     142              : ): Promise<ImageLoadFailureMetadata> {
     143           83 :   const base: ImageLoadFailureMetadata = {
     144              :     source: 'node_image_preview',
     145              :     page_age_ms: Math.round(performance.now()),
     146              :     online: navigator.onLine,
     147              :     resource_kind: 'not_api_view',
     148              :     filename_kind: 'none',
     149              :     probe_outcome: 'probe_blocked'
     150              :   }
     151              : 
     152              :   // An empty src is not a malformed URL — it resolves to the page itself, so
     153              :   // probing it would re-request the HTML document and report a 200 for an image
     154              :   // that never loaded. Reject it before parsing.
     155           83 :   if (!src.trim()) return { ...base, probe_outcome: 'invalid_src' }
     156              : 
     157           83 :   let url: URL
     158           83 :   try {
     159           83 :     url = new URL(src, window.location.href)
     160              :   } catch {
     161              :     // A malformed src never reached the network, so there is nothing to probe
     162              :     // and the shape fields would be fabrications.
     163            0 :     return { ...base, probe_outcome: 'invalid_src' }
     164              :   }
     165              : 
     166           83 :   const shape = {
     167              :     ...base,
     168              :     resource_kind: resourceKind(url),
     169              :     filename_kind: filenameKind(url),
     170              :     same_origin: url.origin === window.location.origin
     171              :   }
     172              : 
     173              :   // Cross-origin images are opaque to `fetch` without CORS, so a probe would
     174              :   // report our own failure rather than the server's answer.
     175           83 :   if (!shape.same_origin) return shape
     176              : 
     177              :   // The report is emitted after the probe resolves, so a page unload mid-probe
     178              :   // would drop the event — the diagnostic would cost us the very failure it
     179              :   // describes. Losing the status is survivable; losing the report is not.
     180           83 :   const settled = new AbortController()
     181           83 :   try {
     182           83 :     return {
     183              :       ...shape,
     184              :       ...(await Promise.race([
     185              :         probeStatus(src),
     186              :         abandonOnUnload(settled.signal)
     187              :       ]))
     188              :     }
     189              :   } finally {
     190              :     // Drops the pagehide listener whichever side won.
     191           79 :     settled.abort()
     192              :   }
     193              : }
        

Generated by: LCOV version 2.0-1