{"version":3,"file":"index.mjs","sources":["../../src/pool-diagnostics/index.ts"],"sourcesContent":["import os from 'node:os';\nimport { performance } from 'node:perf_hooks';\nimport type { Knex } from 'knex';\n\nimport { createThrottle } from '../utils/throttle';\nimport { collectPoolTimeoutDetails, POOL_TIMEOUT_CODE, type KnexClientLike } from './details';\nimport { createEventLoopMonitor, type EventLoopMonitor } from './event-loop';\nimport { appendDocsLink, formatPoolTimeoutWarning } from './format';\nimport { deepenStack } from './stack';\n\nexport { POOL_TIMEOUT_CODE } from './details';\nexport type { PoolState, PoolTimeoutDetails } from './details';\nexport type { EventLoopDelay } from './event-loop';\nexport { POOL_TIMEOUT_DOCS_URL } from './format';\n\nconst ACQUIRE_TIMEOUT_PREFIX = 'Knex: Timeout acquiring a connection';\nconst WARNING_INTERVAL_MS = 30_000;\n\ninterface DiagnosableClient extends KnexClientLike {\n  acquireConnection(): Promise<unknown>;\n}\n\nexport interface PoolDiagnosticsOptions {\n  logger: { warn(message: string): void };\n  getPhase?: () => string | undefined;\n  now?: () => number;\n  hostname?: string;\n  pid?: number;\n  intervalMs?: number;\n  /** Injected in tests; null turns the event loop measurement off. */\n  eventLoopMonitor?: EventLoopMonitor | null;\n}\n\nexport interface PoolDiagnostics {\n  dispose(): void;\n}\n\n/** knex also uses KnexTimeoutError for query timeouts; only pool acquire timeouts are described. */\nexport const isPoolAcquireTimeout = (error: unknown): error is Error =>\n  error instanceof Error &&\n  error.name === 'KnexTimeoutError' &&\n  error.message.startsWith(ACQUIRE_TIMEOUT_PREFIX);\n\n/** An earlier install (for example another copy of this package) already described this error. */\nconst isDescribed = (error: Error) =>\n  (error as { details?: { code?: unknown } | null }).details?.code === POOL_TIMEOUT_CODE;\n\nconst replaceMessage = (error: Error, message: string) => {\n  const previous = error.message;\n  error.message = message;\n\n  // V8 builds `stack` lazily; once something has read it, its first line keeps the old text\n  if (typeof error.stack === 'string' && !error.stack.includes(message)) {\n    error.stack = error.stack.replace(previous, () => message);\n  }\n};\n\n/**\n * Wraps acquireConnection on the knex client Strapi created. On a pool acquire timeout, the same\n * error object gets a deeper stack, a docs link and `details`; at most one warning block per\n * interval goes to the logger. Facts are collected before the error is changed, so a failure while\n * collecting leaves the error's class, name and message as knex made them (its stack may already be\n * deeper); a failing logger only loses the warning. An error that already carries `details` from\n * an earlier install is passed through.\n */\nexport const installPoolDiagnostics = (\n  knex: Knex,\n  options: PoolDiagnosticsOptions\n): PoolDiagnostics => {\n  const client = knex.client as unknown as DiagnosableClient;\n  // Monotonic: a wall clock step must not distort waitedMs or the throttle\n  const now = options.now ?? (() => performance.now());\n  const hostname = options.hostname ?? os.hostname();\n  const pid = options.pid ?? process.pid;\n  const throttle = createThrottle({ intervalMs: options.intervalMs ?? WARNING_INTERVAL_MS, now });\n  const eventLoop =\n    options.eventLoopMonitor === undefined\n      ? createEventLoopMonitor({ now })\n      : options.eventLoopMonitor;\n\n  const safePhase = () => {\n    try {\n      return options.getPhase?.();\n    } catch {\n      return undefined;\n    }\n  };\n\n  const describeTimeout = (error: Error, waitedMs: number) => {\n    try {\n      const details = collectPoolTimeoutDetails(client, {\n        waitedMs,\n        cause: (error as { cause?: unknown }).cause,\n        eventLoopDelay: eventLoop?.read(),\n        phase: safePhase(),\n        hostname,\n        pid,\n      });\n      const message = appendDocsLink(error.message);\n      const { emit, suppressed } = throttle.take();\n      const warning = emit ? formatPoolTimeoutWarning(details, { suppressed }) : undefined;\n\n      // Everything that can throw has run; only now change the error\n      replaceMessage(error, message);\n      Object.assign(error, { details });\n\n      if (warning) {\n        options.logger.warn(warning);\n      }\n    } catch {\n      // Diagnostics never change the failure itself\n    }\n  };\n\n  const hadOwn = Object.prototype.hasOwnProperty.call(client, 'acquireConnection');\n  const original = client.acquireConnection;\n\n  client.acquireConnection = async function acquireConnectionWithDiagnostics(\n    this: DiagnosableClient\n  ) {\n    const startedAt = now();\n\n    try {\n      return await original.call(this);\n    } catch (error) {\n      // An outer second install must not overwrite `details` or log a second block\n      if (isPoolAcquireTimeout(error) && !isDescribed(error)) {\n        try {\n          // Called here so this function is the first re-captured frame\n          deepenStack(error);\n        } catch {\n          // keep knex's stack\n        }\n        describeTimeout(error, now() - startedAt);\n      }\n\n      throw error;\n    }\n  };\n\n  return {\n    dispose() {\n      if (hadOwn) {\n        client.acquireConnection = original;\n      } else {\n        delete (client as Partial<DiagnosableClient>).acquireConnection;\n      }\n      eventLoop?.stop();\n    },\n  };\n};\n"],"names":["ACQUIRE_TIMEOUT_PREFIX","WARNING_INTERVAL_MS","isPoolAcquireTimeout","error","Error","name","message","startsWith","isDescribed","details","code","POOL_TIMEOUT_CODE","replaceMessage","previous","stack","includes","replace","installPoolDiagnostics","knex","options","client","now","performance","hostname","os","pid","process","throttle","createThrottle","intervalMs","eventLoop","eventLoopMonitor","undefined","createEventLoopMonitor","safePhase","getPhase","describeTimeout","waitedMs","collectPoolTimeoutDetails","cause","eventLoopDelay","read","phase","appendDocsLink","emit","suppressed","take","warning","formatPoolTimeoutWarning","Object","assign","logger","warn","hadOwn","prototype","hasOwnProperty","call","original","acquireConnection","acquireConnectionWithDiagnostics","startedAt","deepenStack","dispose","stop"],"mappings":";;;;;;;;;AAeA,MAAMA,sBAAAA,GAAyB,sCAAA;AAC/B,MAAMC,mBAAAA,GAAsB,KAAA;AAqB5B,qGACO,MAAMC,oBAAAA,GAAuB,CAACC,QACnCA,KAAAA,YAAiBC,KAAAA,IACjBD,KAAAA,CAAME,IAAI,KAAK,kBAAA,IACfF,KAAAA,CAAMG,OAAO,CAACC,UAAU,CAACP,sBAAAA;AAE3B,mGACA,MAAMQ,WAAAA,GAAc,CAACL,QACnB,KAACA,CAAkDM,OAAO,EAAEC,IAAAA,KAASC,iBAAAA;AAEvE,MAAMC,cAAAA,GAAiB,CAACT,KAAAA,EAAcG,OAAAA,GAAAA;IACpC,MAAMO,QAAAA,GAAWV,MAAMG,OAAO;AAC9BH,IAAAA,KAAAA,CAAMG,OAAO,GAAGA,OAAAA;;IAGhB,IAAI,OAAOH,KAAAA,C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