{"version":3,"file":"instrumentation.cjs","names":["InstrumentationBase","PACKAGE_NAME","PACKAGE_VERSION","InstrumentationNodeModuleDefinition","InstrumentationNodeModuleFile","ATTR_DB_SYSTEM_NAME","ATTR_DB_COLLECTION_NAME","ATTR_DB_OPERATION_NAME","ATTR_DB_NAMESPACE","ATTR_SERVER_ADDRESS","ATTR_SERVER_PORT","ATTR_DB_QUERY_TEXT","api","isWrapped"],"sources":["../src/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport * as constants from './constants';\nimport {\n  InstrumentationBase,\n  InstrumentationNodeModuleDefinition,\n  InstrumentationNodeModuleFile,\n  isWrapped,\n} from '@opentelemetry/instrumentation';\nimport * as utils from './utils';\nimport { KnexInstrumentationConfig } from './types';\nimport {\n  ATTR_DB_COLLECTION_NAME,\n  ATTR_DB_NAMESPACE,\n  ATTR_DB_OPERATION_NAME,\n  ATTR_DB_QUERY_TEXT,\n  ATTR_DB_SYSTEM_NAME,\n  ATTR_SERVER_ADDRESS,\n  ATTR_SERVER_PORT,\n} from '@opentelemetry/semantic-conventions';\n\nconst contextSymbol = Symbol('opentelemetry.instrumentation-knex.context');\nconst DEFAULT_CONFIG: KnexInstrumentationConfig = {\n  maxQueryLength: 1022,\n  requireParentSpan: false,\n};\n\nexport class KnexInstrumentation extends InstrumentationBase<KnexInstrumentationConfig> {\n  constructor(config: KnexInstrumentationConfig = {}) {\n    super(PACKAGE_NAME, PACKAGE_VERSION, { ...DEFAULT_CONFIG, ...config });\n  }\n\n  override setConfig(config: KnexInstrumentationConfig = {}) {\n    super.setConfig({ ...DEFAULT_CONFIG, ...config });\n  }\n\n  init() {\n    const module = new InstrumentationNodeModuleDefinition(\n      constants.MODULE_NAME,\n      constants.SUPPORTED_VERSIONS\n    );\n\n    module.files.push(\n      this.getClientNodeModuleFileInstrumentation('src'),\n      this.getClientNodeModuleFileInstrumentation('lib'),\n      this.getRunnerNodeModuleFileInstrumentation('src'),\n      this.getRunnerNodeModuleFileInstrumentation('lib'),\n      this.getRunnerNodeModuleFileInstrumentation('lib/execution')\n    );\n\n    return module;\n  }\n\n  private getRunnerNodeModuleFileInstrumentation(basePath: string) {\n    return new InstrumentationNodeModuleFile(\n      `knex/${basePath}/runner.js`,\n      constants.SUPPORTED_VERSIONS,\n      (Runner: any, moduleVersion) => {\n        this.ensureWrapped(\n          Runner.prototype,\n          'query',\n          this.createQueryWrapper(moduleVersion)\n        );\n        return Runner;\n      },\n      (Runner: any, moduleVersion) => {\n        this._unwrap(Runner.prototype, 'query');\n        return Runner;\n      }\n    );\n  }\n\n  private getClientNodeModuleFileInstrumentation(basePath: string) {\n    return new InstrumentationNodeModuleFile(\n      `knex/${basePath}/client.js`,\n      constants.SUPPORTED_VERSIONS,\n      (Client: any) => {\n        this.ensureWrapped(\n          Client.prototype,\n          'queryBuilder',\n          this.storeContext.bind(this)\n        );\n        this.ensureWrapped(\n          Client.prototype,\n          'schemaBuilder',\n          this.storeContext.bind(this)\n        );\n        this.ensureWrapped(\n          Client.prototype,\n          'raw',\n          this.storeContext.bind(this)\n        );\n        return Client;\n      },\n      (Client: any) => {\n        this._unwrap(Client.prototype, 'queryBuilder');\n        this._unwrap(Client.prototype, 'schemaBuilder');\n        this._unwrap(Client.prototype, 'raw');\n        return Client;\n      }\n    );\n  }\n\n  private createQueryWrapper(moduleVersion?: string) {\n    const instrumentation = this;\n\n    return function wrapQuery(original: (...args: any[]) => any) {\n      return function wrapped_logging_method(this: any, query: any) {\n        const table = utils.extractTableName(this.builder);\n        // `method` actually refers to the knex API method - Not exactly \"operation\"\n        // in the spec sense, but matches most of the time.\n        const operation = query?.method;\n        // Use connectionSettings rather than config.connection so that function-based\n        // connection configs (e.g. `connection: async () => ({ host, user, ... })`) are\n        // resolved to their actual values before we read them.\n        const connectionSettings = this.client.connectionSettings;\n        // Knex can be configured with a connectionString instead of explicit fields.\n        // Fall back to parsing the connectionString if filename and database are not set.\n        const connectionString = connectionSettings?.connectionString;\n        const name =\n          connectionSettings?.filename ||\n          connectionSettings?.database ||\n          utils.extractDatabaseFromConnectionString(connectionString);\n        const { maxQueryLength } = instrumentation.getConfig();\n\n        const attributes: api.Attributes = {\n          'knex.version': moduleVersion,\n        };\n\n        Object.assign(attributes, {\n          [ATTR_DB_SYSTEM_NAME]: utils.mapSystem(this.client.driverName),\n          [ATTR_DB_COLLECTION_NAME]: table,\n          [ATTR_DB_OPERATION_NAME]: operation,\n          [ATTR_DB_NAMESPACE]: name,\n          // Fall back to parsing host and port from connectionString if not explicitly set.\n          [ATTR_SERVER_ADDRESS]:\n            connectionSettings?.host ??\n            utils.extractHostFromConnectionString(connectionString),\n          [ATTR_SERVER_PORT]:\n            connectionSettings?.port ??\n            utils.extractPortFromConnectionString(connectionString),\n        });\n\n        if (maxQueryLength) {\n          // filters both undefined and 0\n          const queryText = utils.limitLength(query?.sql, maxQueryLength);\n          attributes[ATTR_DB_QUERY_TEXT] = queryText;\n        }\n\n        const parentContext =\n          this.builder[contextSymbol] || api.context.active();\n        const parentSpan = api.trace.getSpan(parentContext);\n        const hasActiveParent =\n          parentSpan && api.trace.isSpanContextValid(parentSpan.spanContext());\n        if (instrumentation._config.requireParentSpan && !hasActiveParent) {\n          return original.bind(this)(...arguments);\n        }\n\n        const span = instrumentation.tracer.startSpan(\n          utils.getName(name, operation, table),\n          {\n            kind: api.SpanKind.CLIENT,\n            attributes,\n          },\n          parentContext\n        );\n        const spanContext = api.trace.setSpan(api.context.active(), span);\n\n        return api.context\n          .with(spanContext, original, this, ...arguments)\n          .then((result: unknown) => {\n            span.end();\n            return result;\n          })\n          .catch((err: any) => {\n            // knex adds full query with all the binding values to the message,\n            // we want to undo that without changing the original error\n            const formatter = utils.getFormatter(this);\n            const fullQuery = formatter(query.sql, query.bindings || []);\n            const message = err.message.replace(fullQuery + ' - ', '');\n            const exc = utils.otelExceptionFromKnexError(err, message);\n            span.recordException(exc);\n            span.setStatus({ code: api.SpanStatusCode.ERROR, message });\n            span.end();\n            throw err;\n          });\n      };\n    };\n  }\n\n  private storeContext(original: Function) {\n    return function wrapped_logging_method(this: any) {\n      const builder = original.apply(this, arguments);\n      // Builder is a custom promise type and when awaited it fails to propagate context.\n      // We store the parent context at the moment of initiating the builder\n      // otherwise we'd have nothing to attach the span as a child for in `query`.\n      Object.defineProperty(builder, contextSymbol, {\n        value: api.context.active(),\n      });\n      return builder;\n    };\n  }\n\n  ensureWrapped(obj: any, methodName: string, wrapper: (original: any) => any) {\n    if (isWrapped(obj[methodName])) {\n      this._unwrap(obj, methodName);\n    }\n    this._wrap(obj, methodName, wrapper);\n  }\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,gBAAgB,OAAO,4CAA4C;AACzE,MAAM,iBAA4C;CAChD,gBAAgB;CAChB,mBAAmB;AACrB;AAEA,IAAa,sBAAb,cAAyCA,+BAAAA,oBAA+C;CACtF,YAAY,SAAoC,CAAC,GAAG;EAClD,MAAMC,gBAAAA,cAAcC,gBAAAA,iBAAiB;GAAE,GAAG;GAAgB,GAAG;EAAO,CAAC;CACvE;CAEA,UAAmB,SAAoC,CAAC,GAAG;EACzD,MAAM,UAAU;GAAE,GAAG;GAAgB,GAAG;EAAO,CAAC;CAClD;CAEA,OAAO;EACL,MAAM,SAAS,IAAIC,+BAAAA,oCAAAA,kBAAAA,aAAAA,kBAAAA,kBAGnB;EAEA,OAAO,MAAM,KACX,KAAK,uCAAuC,KAAK,GACjD,KAAK,uCAAuC,KAAK,GACjD,KAAK,uCAAuC,KAAK,GACjD,KAAK,uCAAuC,KAAK,GACjD,KAAK,uCAAuC,eAAe,CAC7D;EAEA,OAAO;CACT;CAEA,uCAA+C,UAAkB;EAC/D,OAAO,IAAIC,+BAAAA,8BACT,QAAQ,SAAS,aAAA,kBAAA,qBAEhB,QAAa,kBAAkB;GAC9B,KAAK,cACH,OA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