{"version":3,"file":"fetch-transport.mjs","names":[],"sources":["../../../../src/platform/browser/transport/fetch-transport.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IExporterTransport } from '../../../exporter-transport';\nimport type { ExportResponse } from '../../../export-response';\nimport { context, diag } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport {\n  isExportHTTPErrorRetryable,\n  parseRetryAfterToMills,\n} from '../../../is-export-retryable';\nimport type { HeadersFactory } from '../../../configuration/otlp-http-configuration';\n\n/**\n * Maximum total body size for concurrent keepalive requests.\n * Browsers enforce a 64KiB cumulative limit across all pending keepalive requests.\n * We use 60KB to leave headroom for headers.\n * @see https://github.com/whatwg/fetch/issues/679\n * @see https://blog.huli.tw/2025/01/06/en/navigator-sendbeacon-64kib-and-source-code/\n */\nconst MAX_KEEPALIVE_BODY_SIZE = 60 * 1024;\n\n/**\n * Maximum concurrent keepalive requests.\n * Chrome enforces 9 concurrent keepalive fetch requests per renderer process.\n * @see https://github.com/whatwg/fetch/issues/679\n * Quote: \"If the renderer process is processing more than 9 requests with keepalive set, we reject a new request\"\n */\nconst MAX_KEEPALIVE_REQUESTS = 9;\n\n/**\n * Track cumulative body size charged against the keepalive budget.\n * This is necessary because the 64KiB limit is cumulative, not per-request.\n * Charged from request start until the response body drains, which is later\n * than the request completing: that is when the browser gives the quota back.\n */\nlet pendingBodySize = 0;\n\n/**\n * Track number of requests holding keepalive budget, on the same terms as\n * {@link pendingBodySize}.\n */\nlet pendingKeepaliveCount = 0;\n\nexport interface FetchTransportParameters {\n  url: string;\n  headers: HeadersFactory;\n}\n\nclass FetchTransport implements IExporterTransport {\n  private _parameters: FetchTransportParameters;\n\n  constructor(parameters: FetchTransportParameters) {\n    this._parameters = parameters;\n  }\n\n  async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n    const abortController = new AbortController();\n    const timeout = setTimeout(() => abortController.abort(), timeoutMillis);\n    // Fetch API may be wrapped by an instrumentation like `@opentelemetry/instrumentation-fetch`.\n    // In that case the instrumentation would create a new Span for this request,\n    // creating an indirect endless loop Export -> Span -> Export.\n    // `__original` lets the call bypass one wrapper; the suppressed context\n    // below covers a `fetch` that was wrapped more than once.\n    let fetchApi = globalThis.fetch;\n    // @ts-expect-error -- fetch could be wrapped\n    if (typeof fetchApi.__original === 'function') {\n      // @ts-expect-error -- fetch could be wrapped\n      fetchApi = fetchApi.__original;\n    }\n\n    const requestSize = data.byteLength;\n\n    // Determine if we can use keepalive based on cumulative browser limits.\n    // We must check BEFORE adding to pending totals to avoid exceeding limits.\n    const wouldExceedSize =\n      pendingBodySize + requestSize > MAX_KEEPALIVE_BODY_SIZE;\n    const wouldExceedCount = pendingKeepaliveCount >= MAX_KEEPALIVE_REQUESTS;\n    const useKeepalive = !wouldExceedSize && !wouldExceedCount;\n\n    if (useKeepalive) {\n      pendingBodySize += requestSize;\n      pendingKeepaliveCount++;\n    } else {\n      const reason = wouldExceedSize ? 'size limit' : 'count limit';\n      diag.debug(\n        `keepalive disabled: ${(requestSize / 1024).toFixed(1)}KB payload, ${pendingKeepaliveCount} pending (${reason})`\n      );\n    }\n\n    // Captured before the first `await`, which a synchronous context manager\n    // would not survive.\n    const suppressedContext = suppressTracing(context.active());\n\n    // Idempotent so that a double call cannot drive the counters negative,\n    // which would defeat the cap check above for every later request.\n    let released = false;\n    const release = () => {\n      if (released) {\n        return;\n      }\n      released = true;\n      if (useKeepalive) {\n        pendingBodySize -= requestSize;\n        pendingKeepaliveCount--;\n      }\n      clearTimeout(timeout);\n    };\n    let drainOwnsCleanup = false;\n\n    try {\n      const url = new URL(this._parameters.url);\n      // Resolve headers before entering the suppressed fetch context.\n      const headers = await this._parameters.headers();\n      const response = await context.with(suppressedContext, () =>\n        fetchApi(url.href, {\n          method: 'POST',\n          headers,\n          body: data,\n          signal: abortController.signal,\n          keepalive: useKeepalive,\n          // `location.origin` reports the URL's origin even when the document's\n          // origin is opaque (\"null\", e.g. a sandboxed iframe), where a\n          // same-origin request is rejected; `globalThis.origin` does not.\n          mode: globalThis.location\n            ? globalThis.origin === url.origin\n              ? 'same-origin'\n              : 'cors'\n            : 'no-cors',\n        })\n      );\n\n      // Not awaited: the status already decides the export outcome, and a\n      // collector that stalls mid-body must not hold up the caller.\n      const drained = drainResponseBody(response);\n      // Timer stays armed through the drain: an abort errors the body, so a\n      // stalled drain still settles rather than holding the budget forever.\n      // Released on rejection too, though the drain swallows its errors today:\n      // a missed release would hold the keepalive budget for the page's life.\n      void drained.then(release, release);\n      // Set before any return, or `finally` frees the budget before it drains.\n      drainOwnsCleanup = true;\n\n      if (response.status >= 200 && response.status <= 299) {\n        diag.debug(`export response success (status: ${response.status})`);\n        return { status: 'success' };\n      } else if (isExportHTTPErrorRetryable(response.status)) {\n        diag.warn(`export response retryable (status: ${response.status})`);\n        const retryAfter = response.headers.get('Retry-After');\n        const retryInMillis = parseRetryAfterToMills(retryAfter);\n        return { status: 'retryable', retryInMillis };\n      }\n      diag.error(`export response failure (status: ${response.status})`);\n      return {\n        status: 'failure',\n        error: new Error(\n          `Fetch request failed with non-retryable status ${response.status}`\n        ),\n      };\n    } catch (error) {\n      if (isFetchNetworkErrorRetryable(error)) {\n        diag.warn(`export request retryable (network error: ${error})`);\n        return {\n          status: 'retryable',\n          error: new Error('Fetch request encountered a network error', {\n            cause: error,\n          }),\n        };\n      }\n      diag.error(`export request failure (error: ${error})`);\n      return {\n        status: 'failure',\n        error: new Error('Fetch request errored', { cause: error }),\n      };\n    } finally {\n      // Cleanup here only for a failure before the response arrived; past that\n      // point the drain owns it.\n      if (!drainOwnsCleanup) {\n        release();\n      }\n    }\n  }\n\n  shutdown() {\n    // Intentionally left empty, nothing to do.\n  }\n}\n\n/**\n * Creates an exporter transport that uses `fetch` to send the data\n * @param parameters applied to each request made by transport\n */\nexport function createFetchTransport(\n  parameters: FetchTransportParameters\n): IExporterTransport {\n  return new FetchTransport(parameters);\n}\n\nfunction isFetchNetworkErrorRetryable(error: unknown): boolean {\n  return error instanceof TypeError && !error.cause;\n}\n\n/**\n * Reads the response body to its end and discards it.\n *\n * Chromium gives the request's share of the keepalive quota back only once the\n * response body has been read to the end, and it skips the buffering consumer\n * that would otherwise drain the body on its own when the response carries a\n * `Cache-Control: no-store` header, which collectors commonly send. Leaving the\n * body unread then leaks the quota until the document goes away and every\n * following keepalive export stays pending forever. Cancelling the body is the\n * client-abort path and releases the quota far more slowly than reading it to\n * the end, so the body is read rather than cancelled.\n *\n * Never rejects. Its settlement, not its outcome, is what releases the\n * request's keepalive budget, so a caller that ignores it leaks that budget\n * for the life of the document.\n *\n * @see https://fetch.spec.whatwg.org/#fetch-processresponseendofbody\n * @see https://issues.chromium.org/issues/546438373\n */\nasync function drainResponseBody(response: Response): Promise<void> {\n  try {\n    // Empty and opaque responses have no body to read.\n    const body = response.body;\n    if (body == null) {\n      return;\n    }\n\n    // Throws when the body is already locked to another reader, which happens\n    // when the same response is handed to more than one export.\n    const reader = body.getReader();\n    try {\n      // Chunks are dropped as they arrive: the payload is not used, and\n      // buffering it - with `response.arrayBuffer()` for instance - would keep\n      // a response of arbitrary size in memory.\n      let chunk = await reader.read();\n      while (!chunk.done) {\n        chunk = await reader.read();\n      }\n    } finally {\n      // The reader keeps the body locked until it is released, which would\n      // make a later export handed the same response fail to acquire a reader\n      // and skip the drain.\n      reader.releaseLock();\n    }\n  } catch (error) {\n    // The export outcome is decided by the response status, a body that cannot\n    // be read must not change it.\n    diag.debug(`error reading export response body: ${error}`);\n  }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,MAAM,0BAA0B;;;;;;;AAQhC,MAAM,yBAAyB;;;;;;;AAQ/B,IAAI,kBAAkB;;;;;AAMtB,IAAI,wBAAwB;AAO5B,IAAM,iBAAN,MAAmD;CACjD;CAEA,YAAY,YAAsC;EAChD,KAAK,cAAc;CACrB;CAEA,MAAM,KAAK,MAAkB,eAAgD;EAC3E,MAAM,kBAAkB,IAAI,gBAAgB;E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