@opentelemetry/instrumentation-aws-sdk 0.53.0 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,7 +65,7 @@ The instrumentations are collecting the following attributes:
65
65
  | `rpc.system` | string | Always equals "aws-api" | |
66
66
  | `rpc.method` | string | he name of the operation corresponding to the request, as returned by the AWS SDK. If the SDK does not provide a way to retrieve a name, the name of the command SHOULD be used, removing the suffix `Command` if present, resulting in a PascalCase name with no spaces. | `PutObject` |
67
67
  | `rpc.service` | string | The name of the service to which a request is made, as returned by the AWS SDK. If the SDK does not provide a away to retrieve a name, the name of the SDK's client interface for a service SHOULD be used, removing the suffix `Client` if present, resulting in a PascalCase name with no spaces. | `S3`, `DynamoDB`, `Route53` |
68
- | `aws.region` | string | Region name for the request | "eu-west-1" |
68
+ | `cloud.region` | string | Region name for the request | "eu-west-1" |
69
69
 
70
70
  ### Custom User Attributes
71
71
 
@@ -112,6 +112,7 @@ Attributes collected:
112
112
  | `rpc.method` | The name of the (logical) method being called. | |
113
113
  | `rpc.service` | The full (logical) name of the service being called. | |
114
114
  | `rpc.system` | A string identifying the remoting system. | |
115
+ | `cloud.region` | The AWS Region where the requested service is being accessed. | |
115
116
  | `aws.dynamodb.attribute_definitions` | The JSON-serialized value of each item in the `AttributeDefinitions` request field. | dynamodb |
116
117
  | `aws.dynamodb.consistent_read` | The value of the `ConsistentRead` request parameter. | dynamodb |
117
118
  | `aws.dynamodb.consumed_capacity` | The JSON-serialized value of each item in the `ConsumedCapacity` response field. | dynamodb |
@@ -166,7 +166,7 @@ class AwsInstrumentation extends instrumentation_1.InstrumentationBase {
166
166
  Promise.resolve(regionPromise)
167
167
  .then(resolvedRegion => {
168
168
  normalizedRequest.region = resolvedRegion;
169
- span.setAttribute(enums_1.AttributeNames.AWS_REGION, resolvedRegion);
169
+ span.setAttribute(enums_1.AttributeNames.CLOUD_REGION, resolvedRegion);
170
170
  })
171
171
  .catch(e => {
172
172
  // there is nothing much we can do in this case.
@@ -198,7 +198,11 @@ class AwsInstrumentation extends instrumentation_1.InstrumentationBase {
198
198
  request: normalizedRequest,
199
199
  requestId: requestId,
200
200
  };
201
- self.servicesExtensions.responseHook(normalizedResponse, span, self.tracer, self.getConfig(), startTime);
201
+ const override = self.servicesExtensions.responseHook(normalizedResponse, span, self.tracer, self.getConfig(), startTime);
202
+ if (override) {
203
+ response.output = override;
204
+ normalizedResponse.data = override;
205
+ }
202
206
  self._callUserResponseHook(span, normalizedResponse);
203
207
  return response;
204
208
  })
@@ -223,7 +227,9 @@ class AwsInstrumentation extends instrumentation_1.InstrumentationBase {
223
227
  throw err;
224
228
  })
225
229
  .finally(() => {
226
- span.end();
230
+ if (!requestMetadata.isStream) {
231
+ span.end();
232
+ }
227
233
  });
228
234
  promiseWithResponseLogic
229
235
  .then(res => {
@@ -1 +1 @@
1
- {"version":3,"file":"aws-sdk.js","sourceRoot":"","sources":["../../src/aws-sdk.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAO4B;AAC5B,8CAA8D;AAC9D,mCAAyC;AACzC,yCAAgD;AAQhD,kBAAkB;AAClB,uCAA0D;AAC1D,oEAOwC;AAQxC,mCAKiB;AACjB,yCAAsC;AAEtC,8EAAgF;AAEhF,MAAM,oBAAoB,GAAG,MAAM,CACjC,qDAAqD,CACtD,CAAC;AAKF,MAAa,kBAAmB,SAAQ,qCAAgD;IACtF,MAAM,CAAU,SAAS,GAAG,SAAS,CAAC;IAItC,YAAY,SAAsC,EAAE;QAClD,KAAK,CAAC,sBAAY,EAAE,yBAAe,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAES,IAAI;QACZ,MAAM,gCAAgC,GAAG,IAAI,+CAA6B,CACxE,uDAAuD,EACvD,CAAC,iBAAiB,CAAC,EACnB,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,EACrC,IAAI,CAAC,uBAAu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BAC1B,MAAM,GAAG,CAAC;wBACZ,CAAC,CAAC;6BACD,OAAO,CAAC,GAAG,EAAE;4BACZ,IAAI,CAAC,GAAG,EAAE,CAAC;wBACb,CAAC,CAAC,CAAC;wBACL,wBAAwB;6BACrB,IAAI,CAAC,GAAG,CAAC,EAAE;4BACV,OAAO,CAAC,GAAG,CAAC,CAAC;wBACf,CAAC,CAAC;6BACD,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;oBAC/B,CAAC,CAAC,CAAC;gBACP,CAAC,CAAC,CAAC;gBAEH,OAAO,eAAe,CAAC,UAAU;oBAC/B,CAAC,CAAC,IAAA,mBAAW,EAAC,cAAc,EAAE,qBAAqB,EAAE,CAAC,CAAC;oBACvD,CAAC,CAAC,cAAc,CAAC;YACrB,CAAC,CAAC;YACF,OAAO,cAAc,CAAC;QACxB,CAAC,CAAC;IACJ,CAAC;IAEO,qBAAqB,CAAI,gBAAuC;QACtE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,+BAA+B,EAAE;YACpD,OAAO,aAAO,CAAC,IAAI,CAAC,IAAA,sBAAe,EAAC,aAAO,CAAC,MAAM,EAAE,CAAC,EAAE,gBAAgB,CAAC,CAAC;SAC1E;aAAM;YACL,OAAO,gBAAgB,EAAE,CAAC;SAC3B;IACH,CAAC;IAEQ,wBAAwB;QAC/B,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE;YAC5B,IAAI,CAAC,kBAAkB,GAAG,IAAI,6BAAkB,EAAE,CAAC;SACpD;QACD,IAAI,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9D,CAAC;;AAxZU,gDAAkB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Span,\n SpanKind,\n context,\n trace,\n diag,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport { hrTime, suppressTracing } from '@opentelemetry/core';\nimport { AttributeNames } from './enums';\nimport { ServicesExtensions } from './services';\nimport {\n AwsSdkInstrumentationConfig,\n AwsSdkRequestHookInformation,\n AwsSdkResponseHookInformation,\n NormalizedRequest,\n NormalizedResponse,\n} from './types';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type {\n MiddlewareStack,\n HandlerExecutionContext,\n Command as AwsV3Command,\n Handler as AwsV3MiddlewareHandler,\n InitializeHandlerArguments,\n} from '@aws-sdk/types';\nimport {\n bindPromise,\n extractAttributesFromNormalizedRequest,\n normalizeV3Request,\n removeSuffixFromStringIfExists,\n} from './utils';\nimport { propwrap } from './propwrap';\nimport { RequestMetadata } from './services/ServiceExtension';\nimport { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';\n\nconst V3_CLIENT_CONFIG_KEY = Symbol(\n 'opentelemetry.instrumentation.aws-sdk.client.config'\n);\ntype V3PluginCommand = AwsV3Command<any, any, any, any, any> & {\n [V3_CLIENT_CONFIG_KEY]?: any;\n};\n\nexport class AwsInstrumentation extends InstrumentationBase<AwsSdkInstrumentationConfig> {\n static readonly component = 'aws-sdk';\n // need declare since initialized in callbacks from super constructor\n private declare servicesExtensions: ServicesExtensions;\n\n constructor(config: AwsSdkInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n protected init(): InstrumentationModuleDefinition[] {\n const v3MiddlewareStackFileOldVersions = new InstrumentationNodeModuleFile(\n '@aws-sdk/middleware-stack/dist/cjs/MiddlewareStack.js',\n ['>=3.1.0 <3.35.0'],\n this.patchV3ConstructStack.bind(this),\n this.unpatchV3ConstructStack.bind(this)\n );\n const v3MiddlewareStackFileNewVersions = new InstrumentationNodeModuleFile(\n '@aws-sdk/middleware-stack/dist-cjs/MiddlewareStack.js',\n ['>=3.35.0'],\n this.patchV3ConstructStack.bind(this),\n this.unpatchV3ConstructStack.bind(this)\n );\n\n // as for aws-sdk v3.13.1, constructStack is exported from @aws-sdk/middleware-stack as\n // getter instead of function, which fails shimmer.\n // so we are patching the MiddlewareStack.js file directly to get around it.\n const v3MiddlewareStack = new InstrumentationNodeModuleDefinition(\n '@aws-sdk/middleware-stack',\n ['^3.1.0'],\n undefined,\n undefined,\n [v3MiddlewareStackFileOldVersions, v3MiddlewareStackFileNewVersions]\n );\n\n // Patch for @smithy/middleware-stack for @aws-sdk/* packages v3.363.0+.\n // As of @smithy/middleware-stack@2.1.0 `constructStack` is only available\n // as a getter, so we cannot use `this._wrap()`.\n const self = this;\n const v3SmithyMiddlewareStack = new InstrumentationNodeModuleDefinition(\n '@smithy/middleware-stack',\n ['>=2.0.0'],\n (moduleExports, moduleVersion) => {\n const newExports = propwrap(\n moduleExports,\n 'constructStack',\n (orig: any) => {\n self._diag.debug('propwrapping aws-sdk v3 constructStack');\n return self._getV3ConstructStackPatch(moduleVersion, orig);\n }\n );\n return newExports;\n }\n );\n\n const v3SmithyClient = new InstrumentationNodeModuleDefinition(\n '@aws-sdk/smithy-client',\n ['^3.1.0'],\n this.patchV3SmithyClient.bind(this),\n this.unpatchV3SmithyClient.bind(this)\n );\n\n // patch for new @smithy/smithy-client for aws-sdk packages v3.363.0+\n const v3NewSmithyClient = new InstrumentationNodeModuleDefinition(\n '@smithy/smithy-client',\n ['>=1.0.3'],\n this.patchV3SmithyClient.bind(this),\n this.unpatchV3SmithyClient.bind(this)\n );\n\n return [\n v3MiddlewareStack,\n v3SmithyMiddlewareStack,\n v3SmithyClient,\n v3NewSmithyClient,\n ];\n }\n\n protected patchV3ConstructStack(moduleExports: any, moduleVersion?: string) {\n this._wrap(\n moduleExports,\n 'constructStack',\n this._getV3ConstructStackPatch.bind(this, moduleVersion)\n );\n return moduleExports;\n }\n\n protected unpatchV3ConstructStack(moduleExports: any) {\n this._unwrap(moduleExports, 'constructStack');\n return moduleExports;\n }\n\n protected patchV3SmithyClient(moduleExports: any) {\n this._wrap(\n moduleExports.Client.prototype,\n 'send',\n this._getV3SmithyClientSendPatch.bind(this)\n );\n return moduleExports;\n }\n\n protected unpatchV3SmithyClient(moduleExports: any) {\n this._unwrap(moduleExports.Client.prototype, 'send');\n return moduleExports;\n }\n\n private _startAwsV3Span(\n normalizedRequest: NormalizedRequest,\n metadata: RequestMetadata\n ): Span {\n const name =\n metadata.spanName ??\n `${normalizedRequest.serviceName}.${normalizedRequest.commandName}`;\n const newSpan = this.tracer.startSpan(name, {\n kind: metadata.spanKind ?? SpanKind.CLIENT,\n attributes: {\n ...extractAttributesFromNormalizedRequest(normalizedRequest),\n ...metadata.spanAttributes,\n },\n });\n\n return newSpan;\n }\n\n private _callUserPreRequestHook(\n span: Span,\n request: NormalizedRequest,\n moduleVersion: string | undefined\n ) {\n const { preRequestHook } = this.getConfig();\n if (preRequestHook) {\n const requestInfo: AwsSdkRequestHookInformation = {\n moduleVersion,\n request,\n };\n safeExecuteInTheMiddle(\n () => preRequestHook(span, requestInfo),\n (e: Error | undefined) => {\n if (e)\n diag.error(\n `${AwsInstrumentation.component} instrumentation: preRequestHook error`,\n e\n );\n },\n true\n );\n }\n }\n\n private _callUserResponseHook(span: Span, response: NormalizedResponse) {\n const { responseHook } = this.getConfig();\n if (!responseHook) return;\n\n const responseInfo: AwsSdkResponseHookInformation = {\n response,\n };\n safeExecuteInTheMiddle(\n () => responseHook(span, responseInfo),\n (e: Error | undefined) => {\n if (e)\n diag.error(\n `${AwsInstrumentation.component} instrumentation: responseHook error`,\n e\n );\n },\n true\n );\n }\n\n private _getV3ConstructStackPatch(\n moduleVersion: string | undefined,\n original: (...args: unknown[]) => MiddlewareStack<any, any>\n ) {\n const self = this;\n return function constructStack(\n this: any,\n ...args: unknown[]\n ): MiddlewareStack<any, any> {\n const stack: MiddlewareStack<any, any> = original.apply(this, args);\n self.patchV3MiddlewareStack(moduleVersion, stack);\n return stack;\n };\n }\n\n private _getV3SmithyClientSendPatch(\n original: (...args: unknown[]) => Promise<any>\n ) {\n return function send(\n this: any,\n command: V3PluginCommand,\n ...args: unknown[]\n ): Promise<any> {\n command[V3_CLIENT_CONFIG_KEY] = this.config;\n return original.apply(this, [command, ...args]);\n };\n }\n\n private patchV3MiddlewareStack(\n moduleVersion: string | undefined,\n middlewareStackToPatch: MiddlewareStack<any, any>\n ) {\n if (!isWrapped(middlewareStackToPatch.resolve)) {\n this._wrap(\n middlewareStackToPatch,\n 'resolve',\n this._getV3MiddlewareStackResolvePatch.bind(this, moduleVersion)\n );\n }\n\n // 'clone' and 'concat' functions are internally calling 'constructStack' which is in same\n // module, thus not patched, and we need to take care of it specifically.\n this._wrap(\n middlewareStackToPatch,\n 'clone',\n this._getV3MiddlewareStackClonePatch.bind(this, moduleVersion)\n );\n this._wrap(\n middlewareStackToPatch,\n 'concat',\n this._getV3MiddlewareStackClonePatch.bind(this, moduleVersion)\n );\n }\n\n private _getV3MiddlewareStackClonePatch(\n moduleVersion: string | undefined,\n original: (...args: any[]) => MiddlewareStack<any, any>\n ) {\n const self = this;\n return function (this: any, ...args: any[]) {\n const newStack = original.apply(this, args);\n self.patchV3MiddlewareStack(moduleVersion, newStack);\n return newStack;\n };\n }\n\n private _getV3MiddlewareStackResolvePatch(\n moduleVersion: string | undefined,\n original: (\n _handler: any,\n context: HandlerExecutionContext\n ) => AwsV3MiddlewareHandler<any, any>\n ) {\n const self = this;\n return function (\n this: any,\n _handler: any,\n awsExecutionContext: HandlerExecutionContext\n ): AwsV3MiddlewareHandler<any, any> {\n const origHandler = original.call(this, _handler, awsExecutionContext);\n const patchedHandler = function (\n this: any,\n command: InitializeHandlerArguments<any> & {\n [V3_CLIENT_CONFIG_KEY]?: any;\n }\n ): Promise<any> {\n const clientConfig = command[V3_CLIENT_CONFIG_KEY];\n const regionPromise = clientConfig?.region?.();\n const serviceName =\n clientConfig?.serviceId ??\n removeSuffixFromStringIfExists(\n // Use 'AWS' as a fallback serviceName to match type definition.\n // In practice, `clientName` should always be set.\n awsExecutionContext.clientName || 'AWS',\n 'Client'\n );\n const commandName =\n awsExecutionContext.commandName ?? command.constructor?.name;\n const normalizedRequest = normalizeV3Request(\n serviceName,\n commandName,\n command.input,\n undefined\n );\n const requestMetadata = self.servicesExtensions.requestPreSpanHook(\n normalizedRequest,\n self.getConfig(),\n self._diag\n );\n const startTime = hrTime();\n const span = self._startAwsV3Span(normalizedRequest, requestMetadata);\n const activeContextWithSpan = trace.setSpan(context.active(), span);\n\n const handlerPromise = new Promise((resolve, reject) => {\n Promise.resolve(regionPromise)\n .then(resolvedRegion => {\n normalizedRequest.region = resolvedRegion;\n span.setAttribute(AttributeNames.AWS_REGION, resolvedRegion);\n })\n .catch(e => {\n // there is nothing much we can do in this case.\n // we'll just continue without region\n diag.debug(\n `${AwsInstrumentation.component} instrumentation: failed to extract region from async function`,\n e\n );\n })\n .finally(() => {\n self._callUserPreRequestHook(\n span,\n normalizedRequest,\n moduleVersion\n );\n const resultPromise = context.with(activeContextWithSpan, () => {\n self.servicesExtensions.requestPostSpanHook(normalizedRequest);\n return self._callOriginalFunction(() =>\n origHandler.call(this, command)\n );\n });\n const promiseWithResponseLogic = resultPromise\n .then(response => {\n const requestId = response.output?.$metadata?.requestId;\n if (requestId) {\n span.setAttribute(AttributeNames.AWS_REQUEST_ID, requestId);\n }\n\n const httpStatusCode =\n response.output?.$metadata?.httpStatusCode;\n if (httpStatusCode) {\n span.setAttribute(\n SEMATTRS_HTTP_STATUS_CODE,\n httpStatusCode\n );\n }\n\n const extendedRequestId =\n response.output?.$metadata?.extendedRequestId;\n if (extendedRequestId) {\n span.setAttribute(\n AttributeNames.AWS_REQUEST_EXTENDED_ID,\n extendedRequestId\n );\n }\n\n const normalizedResponse: NormalizedResponse = {\n data: response.output,\n request: normalizedRequest,\n requestId: requestId,\n };\n self.servicesExtensions.responseHook(\n normalizedResponse,\n span,\n self.tracer,\n self.getConfig(),\n startTime\n );\n self._callUserResponseHook(span, normalizedResponse);\n return response;\n })\n .catch(err => {\n const requestId = err?.RequestId;\n if (requestId) {\n span.setAttribute(AttributeNames.AWS_REQUEST_ID, requestId);\n }\n\n const httpStatusCode = err?.$metadata?.httpStatusCode;\n if (httpStatusCode) {\n span.setAttribute(\n SEMATTRS_HTTP_STATUS_CODE,\n httpStatusCode\n );\n }\n\n const extendedRequestId = err?.extendedRequestId;\n if (extendedRequestId) {\n span.setAttribute(\n AttributeNames.AWS_REQUEST_EXTENDED_ID,\n extendedRequestId\n );\n }\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n span.recordException(err);\n throw err;\n })\n .finally(() => {\n span.end();\n });\n promiseWithResponseLogic\n .then(res => {\n resolve(res);\n })\n .catch(err => reject(err));\n });\n });\n\n return requestMetadata.isIncoming\n ? bindPromise(handlerPromise, activeContextWithSpan, 2)\n : handlerPromise;\n };\n return patchedHandler;\n };\n }\n\n private _callOriginalFunction<T>(originalFunction: (...args: any[]) => T): T {\n if (this.getConfig().suppressInternalInstrumentation) {\n return context.with(suppressTracing(context.active()), originalFunction);\n } else {\n return originalFunction();\n }\n }\n\n override _updateMetricInstruments() {\n if (!this.servicesExtensions) {\n this.servicesExtensions = new ServicesExtensions();\n }\n this.servicesExtensions.updateMetricInstruments(this.meter);\n }\n}\n"]}
1
+ {"version":3,"file":"aws-sdk.js","sourceRoot":"","sources":["../../src/aws-sdk.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAO4B;AAC5B,8CAA8D;AAC9D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AAC;YACrB,CAAC,CAAC;YACF,OAAO,cAAc,CAAC;QACxB,CAAC,CAAC;IACJ,CAAC;IAEO,qBAAqB,CAAI,gBAAuC;QACtE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,+BAA+B,EAAE;YACpD,OAAO,aAAO,CAAC,IAAI,CAAC,IAAA,sBAAe,EAAC,aAAO,CAAC,MAAM,EAAE,CAAC,EAAE,gBAAgB,CAAC,CAAC;SAC1E;aAAM;YACL,OAAO,gBAAgB,EAAE,CAAC;SAC3B;IACH,CAAC;IAEQ,wBAAwB;QAC/B,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE;YAC5B,IAAI,CAAC,kBAAkB,GAAG,IAAI,6BAAkB,EAAE,CAAC;SACpD;QACD,IAAI,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9D,CAAC;;AA9ZU,gDAAkB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Span,\n SpanKind,\n context,\n trace,\n diag,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport { hrTime, suppressTracing } from '@opentelemetry/core';\nimport { AttributeNames } from './enums';\nimport { ServicesExtensions } from './services';\nimport {\n AwsSdkInstrumentationConfig,\n AwsSdkRequestHookInformation,\n AwsSdkResponseHookInformation,\n NormalizedRequest,\n NormalizedResponse,\n} from './types';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type {\n MiddlewareStack,\n HandlerExecutionContext,\n Command as AwsV3Command,\n Handler as AwsV3MiddlewareHandler,\n InitializeHandlerArguments,\n} from '@aws-sdk/types';\nimport {\n bindPromise,\n extractAttributesFromNormalizedRequest,\n normalizeV3Request,\n removeSuffixFromStringIfExists,\n} from './utils';\nimport { propwrap } from './propwrap';\nimport { RequestMetadata } from './services/ServiceExtension';\nimport { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';\n\nconst V3_CLIENT_CONFIG_KEY = Symbol(\n 'opentelemetry.instrumentation.aws-sdk.client.config'\n);\ntype V3PluginCommand = AwsV3Command<any, any, any, any, any> & {\n [V3_CLIENT_CONFIG_KEY]?: any;\n};\n\nexport class AwsInstrumentation extends InstrumentationBase<AwsSdkInstrumentationConfig> {\n static readonly component = 'aws-sdk';\n // need declare since initialized in callbacks from super constructor\n private declare servicesExtensions: ServicesExtensions;\n\n constructor(config: AwsSdkInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n protected init(): InstrumentationModuleDefinition[] {\n const v3MiddlewareStackFileOldVersions = new InstrumentationNodeModuleFile(\n '@aws-sdk/middleware-stack/dist/cjs/MiddlewareStack.js',\n ['>=3.1.0 <3.35.0'],\n this.patchV3ConstructStack.bind(this),\n this.unpatchV3ConstructStack.bind(this)\n );\n const v3MiddlewareStackFileNewVersions = new InstrumentationNodeModuleFile(\n '@aws-sdk/middleware-stack/dist-cjs/MiddlewareStack.js',\n ['>=3.35.0'],\n this.patchV3ConstructStack.bind(this),\n this.unpatchV3ConstructStack.bind(this)\n );\n\n // as for aws-sdk v3.13.1, constructStack is exported from @aws-sdk/middleware-stack as\n // getter instead of function, which fails shimmer.\n // so we are patching the MiddlewareStack.js file directly to get around it.\n const v3MiddlewareStack = new InstrumentationNodeModuleDefinition(\n '@aws-sdk/middleware-stack',\n ['^3.1.0'],\n undefined,\n undefined,\n [v3MiddlewareStackFileOldVersions, v3MiddlewareStackFileNewVersions]\n );\n\n // Patch for @smithy/middleware-stack for @aws-sdk/* packages v3.363.0+.\n // As of @smithy/middleware-stack@2.1.0 `constructStack` is only available\n // as a getter, so we cannot use `this._wrap()`.\n const self = this;\n const v3SmithyMiddlewareStack = new InstrumentationNodeModuleDefinition(\n '@smithy/middleware-stack',\n ['>=2.0.0'],\n (moduleExports, moduleVersion) => {\n const newExports = propwrap(\n moduleExports,\n 'constructStack',\n (orig: any) => {\n self._diag.debug('propwrapping aws-sdk v3 constructStack');\n return self._getV3ConstructStackPatch(moduleVersion, orig);\n }\n );\n return newExports;\n }\n );\n\n const v3SmithyClient = new InstrumentationNodeModuleDefinition(\n '@aws-sdk/smithy-client',\n ['^3.1.0'],\n this.patchV3SmithyClient.bind(this),\n this.unpatchV3SmithyClient.bind(this)\n );\n\n // patch for new @smithy/smithy-client for aws-sdk packages v3.363.0+\n const v3NewSmithyClient = new InstrumentationNodeModuleDefinition(\n '@smithy/smithy-client',\n ['>=1.0.3'],\n this.patchV3SmithyClient.bind(this),\n this.unpatchV3SmithyClient.bind(this)\n );\n\n return [\n v3MiddlewareStack,\n v3SmithyMiddlewareStack,\n v3SmithyClient,\n v3NewSmithyClient,\n ];\n }\n\n protected patchV3ConstructStack(moduleExports: any, moduleVersion?: string) {\n this._wrap(\n moduleExports,\n 'constructStack',\n this._getV3ConstructStackPatch.bind(this, moduleVersion)\n );\n return moduleExports;\n }\n\n protected unpatchV3ConstructStack(moduleExports: any) {\n this._unwrap(moduleExports, 'constructStack');\n return moduleExports;\n }\n\n protected patchV3SmithyClient(moduleExports: any) {\n this._wrap(\n moduleExports.Client.prototype,\n 'send',\n this._getV3SmithyClientSendPatch.bind(this)\n );\n return moduleExports;\n }\n\n protected unpatchV3SmithyClient(moduleExports: any) {\n this._unwrap(moduleExports.Client.prototype, 'send');\n return moduleExports;\n }\n\n private _startAwsV3Span(\n normalizedRequest: NormalizedRequest,\n metadata: RequestMetadata\n ): Span {\n const name =\n metadata.spanName ??\n `${normalizedRequest.serviceName}.${normalizedRequest.commandName}`;\n const newSpan = this.tracer.startSpan(name, {\n kind: metadata.spanKind ?? SpanKind.CLIENT,\n attributes: {\n ...extractAttributesFromNormalizedRequest(normalizedRequest),\n ...metadata.spanAttributes,\n },\n });\n\n return newSpan;\n }\n\n private _callUserPreRequestHook(\n span: Span,\n request: NormalizedRequest,\n moduleVersion: string | undefined\n ) {\n const { preRequestHook } = this.getConfig();\n if (preRequestHook) {\n const requestInfo: AwsSdkRequestHookInformation = {\n moduleVersion,\n request,\n };\n safeExecuteInTheMiddle(\n () => preRequestHook(span, requestInfo),\n (e: Error | undefined) => {\n if (e)\n diag.error(\n `${AwsInstrumentation.component} instrumentation: preRequestHook error`,\n e\n );\n },\n true\n );\n }\n }\n\n private _callUserResponseHook(span: Span, response: NormalizedResponse) {\n const { responseHook } = this.getConfig();\n if (!responseHook) return;\n\n const responseInfo: AwsSdkResponseHookInformation = {\n response,\n };\n safeExecuteInTheMiddle(\n () => responseHook(span, responseInfo),\n (e: Error | undefined) => {\n if (e)\n diag.error(\n `${AwsInstrumentation.component} instrumentation: responseHook error`,\n e\n );\n },\n true\n );\n }\n\n private _getV3ConstructStackPatch(\n moduleVersion: string | undefined,\n original: (...args: unknown[]) => MiddlewareStack<any, any>\n ) {\n const self = this;\n return function constructStack(\n this: any,\n ...args: unknown[]\n ): MiddlewareStack<any, any> {\n const stack: MiddlewareStack<any, any> = original.apply(this, args);\n self.patchV3MiddlewareStack(moduleVersion, stack);\n return stack;\n };\n }\n\n private _getV3SmithyClientSendPatch(\n original: (...args: unknown[]) => Promise<any>\n ) {\n return function send(\n this: any,\n command: V3PluginCommand,\n ...args: unknown[]\n ): Promise<any> {\n command[V3_CLIENT_CONFIG_KEY] = this.config;\n return original.apply(this, [command, ...args]);\n };\n }\n\n private patchV3MiddlewareStack(\n moduleVersion: string | undefined,\n middlewareStackToPatch: MiddlewareStack<any, any>\n ) {\n if (!isWrapped(middlewareStackToPatch.resolve)) {\n this._wrap(\n middlewareStackToPatch,\n 'resolve',\n this._getV3MiddlewareStackResolvePatch.bind(this, moduleVersion)\n );\n }\n\n // 'clone' and 'concat' functions are internally calling 'constructStack' which is in same\n // module, thus not patched, and we need to take care of it specifically.\n this._wrap(\n middlewareStackToPatch,\n 'clone',\n this._getV3MiddlewareStackClonePatch.bind(this, moduleVersion)\n );\n this._wrap(\n middlewareStackToPatch,\n 'concat',\n this._getV3MiddlewareStackClonePatch.bind(this, moduleVersion)\n );\n }\n\n private _getV3MiddlewareStackClonePatch(\n moduleVersion: string | undefined,\n original: (...args: any[]) => MiddlewareStack<any, any>\n ) {\n const self = this;\n return function (this: any, ...args: any[]) {\n const newStack = original.apply(this, args);\n self.patchV3MiddlewareStack(moduleVersion, newStack);\n return newStack;\n };\n }\n\n private _getV3MiddlewareStackResolvePatch(\n moduleVersion: string | undefined,\n original: (\n _handler: any,\n context: HandlerExecutionContext\n ) => AwsV3MiddlewareHandler<any, any>\n ) {\n const self = this;\n return function (\n this: any,\n _handler: any,\n awsExecutionContext: HandlerExecutionContext\n ): AwsV3MiddlewareHandler<any, any> {\n const origHandler = original.call(this, _handler, awsExecutionContext);\n const patchedHandler = function (\n this: any,\n command: InitializeHandlerArguments<any> & {\n [V3_CLIENT_CONFIG_KEY]?: any;\n }\n ): Promise<any> {\n const clientConfig = command[V3_CLIENT_CONFIG_KEY];\n const regionPromise = clientConfig?.region?.();\n const serviceName =\n clientConfig?.serviceId ??\n removeSuffixFromStringIfExists(\n // Use 'AWS' as a fallback serviceName to match type definition.\n // In practice, `clientName` should always be set.\n awsExecutionContext.clientName || 'AWS',\n 'Client'\n );\n const commandName =\n awsExecutionContext.commandName ?? command.constructor?.name;\n const normalizedRequest = normalizeV3Request(\n serviceName,\n commandName,\n command.input,\n undefined\n );\n const requestMetadata = self.servicesExtensions.requestPreSpanHook(\n normalizedRequest,\n self.getConfig(),\n self._diag\n );\n const startTime = hrTime();\n const span = self._startAwsV3Span(normalizedRequest, requestMetadata);\n const activeContextWithSpan = trace.setSpan(context.active(), span);\n\n const handlerPromise = new Promise((resolve, reject) => {\n Promise.resolve(regionPromise)\n .then(resolvedRegion => {\n normalizedRequest.region = resolvedRegion;\n span.setAttribute(AttributeNames.CLOUD_REGION, resolvedRegion);\n })\n .catch(e => {\n // there is nothing much we can do in this case.\n // we'll just continue without region\n diag.debug(\n `${AwsInstrumentation.component} instrumentation: failed to extract region from async function`,\n e\n );\n })\n .finally(() => {\n self._callUserPreRequestHook(\n span,\n normalizedRequest,\n moduleVersion\n );\n const resultPromise = context.with(activeContextWithSpan, () => {\n self.servicesExtensions.requestPostSpanHook(normalizedRequest);\n return self._callOriginalFunction(() =>\n origHandler.call(this, command)\n );\n });\n const promiseWithResponseLogic = resultPromise\n .then(response => {\n const requestId = response.output?.$metadata?.requestId;\n if (requestId) {\n span.setAttribute(AttributeNames.AWS_REQUEST_ID, requestId);\n }\n\n const httpStatusCode =\n response.output?.$metadata?.httpStatusCode;\n if (httpStatusCode) {\n span.setAttribute(\n SEMATTRS_HTTP_STATUS_CODE,\n httpStatusCode\n );\n }\n\n const extendedRequestId =\n response.output?.$metadata?.extendedRequestId;\n if (extendedRequestId) {\n span.setAttribute(\n AttributeNames.AWS_REQUEST_EXTENDED_ID,\n extendedRequestId\n );\n }\n\n const normalizedResponse: NormalizedResponse = {\n data: response.output,\n request: normalizedRequest,\n requestId: requestId,\n };\n const override = self.servicesExtensions.responseHook(\n normalizedResponse,\n span,\n self.tracer,\n self.getConfig(),\n startTime\n );\n if (override) {\n response.output = override;\n normalizedResponse.data = override;\n }\n self._callUserResponseHook(span, normalizedResponse);\n return response;\n })\n .catch(err => {\n const requestId = err?.RequestId;\n if (requestId) {\n span.setAttribute(AttributeNames.AWS_REQUEST_ID, requestId);\n }\n\n const httpStatusCode = err?.$metadata?.httpStatusCode;\n if (httpStatusCode) {\n span.setAttribute(\n SEMATTRS_HTTP_STATUS_CODE,\n httpStatusCode\n );\n }\n\n const extendedRequestId = err?.extendedRequestId;\n if (extendedRequestId) {\n span.setAttribute(\n AttributeNames.AWS_REQUEST_EXTENDED_ID,\n extendedRequestId\n );\n }\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n span.recordException(err);\n throw err;\n })\n .finally(() => {\n if (!requestMetadata.isStream) {\n span.end();\n }\n });\n promiseWithResponseLogic\n .then(res => {\n resolve(res);\n })\n .catch(err => reject(err));\n });\n });\n\n return requestMetadata.isIncoming\n ? bindPromise(handlerPromise, activeContextWithSpan, 2)\n : handlerPromise;\n };\n return patchedHandler;\n };\n }\n\n private _callOriginalFunction<T>(originalFunction: (...args: any[]) => T): T {\n if (this.getConfig().suppressInternalInstrumentation) {\n return context.with(suppressTracing(context.active()), originalFunction);\n } else {\n return originalFunction();\n }\n }\n\n override _updateMetricInstruments() {\n if (!this.servicesExtensions) {\n this.servicesExtensions = new ServicesExtensions();\n }\n this.servicesExtensions.updateMetricInstruments(this.meter);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  export declare enum AttributeNames {
2
2
  AWS_OPERATION = "aws.operation",
3
- AWS_REGION = "aws.region",
3
+ CLOUD_REGION = "cloud.region",
4
4
  AWS_SERVICE_API = "aws.service.api",
5
5
  AWS_SERVICE_NAME = "aws.service.name",
6
6
  AWS_SERVICE_IDENTIFIER = "aws.service.identifier",
@@ -19,7 +19,7 @@ exports.AttributeNames = void 0;
19
19
  var AttributeNames;
20
20
  (function (AttributeNames) {
21
21
  AttributeNames["AWS_OPERATION"] = "aws.operation";
22
- AttributeNames["AWS_REGION"] = "aws.region";
22
+ AttributeNames["CLOUD_REGION"] = "cloud.region";
23
23
  AttributeNames["AWS_SERVICE_API"] = "aws.service.api";
24
24
  AttributeNames["AWS_SERVICE_NAME"] = "aws.service.name";
25
25
  AttributeNames["AWS_SERVICE_IDENTIFIER"] = "aws.service.identifier";
@@ -1 +1 @@
1
- {"version":3,"file":"enums.js","sourceRoot":"","sources":["../../src/enums.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,IAAY,cAeX;AAfD,WAAY,cAAc;IACxB,iDAA+B,CAAA;IAC/B,2CAAyB,CAAA;IACzB,qDAAmC,CAAA;IACnC,uDAAqC,CAAA;IACrC,mEAAiD,CAAA;IACjD,mDAAiC,CAAA;IACjC,qEAAmD,CAAA;IACnD,iEAA+C,CAAA;IAE/C,0CAA0C;IAC1C,6IAA6I;IAC7I,uHAAuH;IACvH,iDAA+B,CAAA;IAC/B,qEAAmD,CAAA;AACrD,CAAC,EAfW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAezB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum AttributeNames {\n AWS_OPERATION = 'aws.operation',\n AWS_REGION = 'aws.region',\n AWS_SERVICE_API = 'aws.service.api',\n AWS_SERVICE_NAME = 'aws.service.name',\n AWS_SERVICE_IDENTIFIER = 'aws.service.identifier',\n AWS_REQUEST_ID = 'aws.request.id',\n AWS_REQUEST_EXTENDED_ID = 'aws.request.extended_id',\n AWS_SIGNATURE_VERSION = 'aws.signature.version',\n\n // TODO: Add these semantic attributes to:\n // - https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-semantic-conventions/src/trace/SemanticAttributes.ts\n // For S3, see specification: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/object-stores/s3.md\n AWS_S3_BUCKET = 'aws.s3.bucket',\n AWS_KINESIS_STREAM_NAME = 'aws.kinesis.stream.name',\n}\n"]}
1
+ {"version":3,"file":"enums.js","sourceRoot":"","sources":["../../src/enums.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,IAAY,cAeX;AAfD,WAAY,cAAc;IACxB,iDAA+B,CAAA;IAC/B,+CAA6B,CAAA;IAC7B,qDAAmC,CAAA;IACnC,uDAAqC,CAAA;IACrC,mEAAiD,CAAA;IACjD,mDAAiC,CAAA;IACjC,qEAAmD,CAAA;IACnD,iEAA+C,CAAA;IAE/C,0CAA0C;IAC1C,6IAA6I;IAC7I,uHAAuH;IACvH,iDAA+B,CAAA;IAC/B,qEAAmD,CAAA;AACrD,CAAC,EAfW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAezB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum AttributeNames {\n AWS_OPERATION = 'aws.operation',\n CLOUD_REGION = 'cloud.region',\n AWS_SERVICE_API = 'aws.service.api',\n AWS_SERVICE_NAME = 'aws.service.name',\n AWS_SERVICE_IDENTIFIER = 'aws.service.identifier',\n AWS_REQUEST_ID = 'aws.request.id',\n AWS_REQUEST_EXTENDED_ID = 'aws.request.extended_id',\n AWS_SIGNATURE_VERSION = 'aws.signature.version',\n\n // TODO: Add these semantic attributes to:\n // - https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-semantic-conventions/src/trace/SemanticAttributes.ts\n // For S3, see specification: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/object-stores/s3.md\n AWS_S3_BUCKET = 'aws.s3.bucket',\n AWS_KINESIS_STREAM_NAME = 'aws.kinesis.stream.name',\n}\n"]}
@@ -1,3 +1,3 @@
1
- export * from './aws-sdk';
2
- export * from './types';
1
+ export { AwsInstrumentation } from './aws-sdk';
2
+ export type { AwsSdkDynamoDBStatementSerializer, AwsSdkInstrumentationConfig, AwsSdkRequestCustomAttributeFunction, AwsSdkRequestHookInformation, AwsSdkResponseCustomAttributeFunction, AwsSdkResponseHookInformation, AwsSdkSqsProcessCustomAttributeFunction, AwsSdkSqsProcessHookInformation, CommandInput, NormalizedRequest, NormalizedResponse, } from './types';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,19 +1,6 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AwsInstrumentation = void 0;
17
4
  /*
18
5
  * Copyright The OpenTelemetry Authors
19
6
  *
@@ -29,6 +16,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
16
  * See the License for the specific language governing permissions and
30
17
  * limitations under the License.
31
18
  */
32
- __exportStar(require("./aws-sdk"), exports);
33
- __exportStar(require("./types"), exports);
19
+ var aws_sdk_1 = require("./aws-sdk");
20
+ Object.defineProperty(exports, "AwsInstrumentation", { enumerable: true, get: function () { return aws_sdk_1.AwsInstrumentation; } });
34
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAA0B;AAC1B,0CAAwB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport * from './aws-sdk';\nexport * from './types';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,qCAA+C;AAAtC,6GAAA,kBAAkB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { AwsInstrumentation } from './aws-sdk';\nexport type {\n AwsSdkDynamoDBStatementSerializer,\n AwsSdkInstrumentationConfig,\n AwsSdkRequestCustomAttributeFunction,\n AwsSdkRequestHookInformation,\n AwsSdkResponseCustomAttributeFunction,\n AwsSdkResponseHookInformation,\n AwsSdkSqsProcessCustomAttributeFunction,\n AwsSdkSqsProcessHookInformation,\n CommandInput,\n NormalizedRequest,\n NormalizedResponse,\n} from './types';\n"]}
@@ -116,4 +116,13 @@ export declare const GEN_AI_TOKEN_TYPE_VALUE_INPUT: "input";
116
116
  * Enum value "output" for attribute {@link ATTR_GEN_AI_TOKEN_TYPE}.
117
117
  */
118
118
  export declare const GEN_AI_TOKEN_TYPE_VALUE_OUTPUT: "output";
119
+ /**
120
+ * Originally from '@opentelemetry/semantic-conventions/incubating'
121
+ * https://github.com/open-telemetry/semantic-conventions/blob/main/docs/registry/attributes/aws.md#amazon-sns-attributes
122
+ * The ARN of the AWS SNS Topic. An Amazon SNS [topic](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)
123
+ * is a logical access point that acts as a communication channel.
124
+ * @example arn:aws:sns:us-east-1:123456789012:mystack-mytopic-NZJ5JSMVGFIE
125
+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
126
+ */
127
+ export declare const ATTR_AWS_SNS_TOPIC_ARN: "aws.sns.topic.arn";
119
128
  //# sourceMappingURL=semconv.d.ts.map
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.GEN_AI_TOKEN_TYPE_VALUE_OUTPUT = exports.GEN_AI_TOKEN_TYPE_VALUE_INPUT = exports.GEN_AI_SYSTEM_VALUE_AWS_BEDROCK = exports.GEN_AI_OPERATION_NAME_VALUE_CHAT = exports.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = exports.ATTR_GEN_AI_USAGE_INPUT_TOKENS = exports.ATTR_GEN_AI_TOKEN_TYPE = exports.ATTR_GEN_AI_SYSTEM = exports.ATTR_GEN_AI_RESPONSE_FINISH_REASONS = exports.ATTR_GEN_AI_REQUEST_TOP_P = exports.ATTR_GEN_AI_REQUEST_TEMPERATURE = exports.ATTR_GEN_AI_REQUEST_STOP_SEQUENCES = exports.ATTR_GEN_AI_REQUEST_MODEL = exports.ATTR_GEN_AI_REQUEST_MAX_TOKENS = exports.ATTR_GEN_AI_OPERATION_NAME = void 0;
18
+ exports.ATTR_AWS_SNS_TOPIC_ARN = exports.GEN_AI_TOKEN_TYPE_VALUE_OUTPUT = exports.GEN_AI_TOKEN_TYPE_VALUE_INPUT = exports.GEN_AI_SYSTEM_VALUE_AWS_BEDROCK = exports.GEN_AI_OPERATION_NAME_VALUE_CHAT = exports.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = exports.ATTR_GEN_AI_USAGE_INPUT_TOKENS = exports.ATTR_GEN_AI_TOKEN_TYPE = exports.ATTR_GEN_AI_SYSTEM = exports.ATTR_GEN_AI_RESPONSE_FINISH_REASONS = exports.ATTR_GEN_AI_REQUEST_TOP_P = exports.ATTR_GEN_AI_REQUEST_TEMPERATURE = exports.ATTR_GEN_AI_REQUEST_STOP_SEQUENCES = exports.ATTR_GEN_AI_REQUEST_MODEL = exports.ATTR_GEN_AI_REQUEST_MAX_TOKENS = exports.ATTR_GEN_AI_OPERATION_NAME = void 0;
19
19
  /*
20
20
  * This file contains a copy of unstable semantic convention definitions
21
21
  * used by this package.
@@ -139,4 +139,13 @@ exports.GEN_AI_TOKEN_TYPE_VALUE_INPUT = 'input';
139
139
  * Enum value "output" for attribute {@link ATTR_GEN_AI_TOKEN_TYPE}.
140
140
  */
141
141
  exports.GEN_AI_TOKEN_TYPE_VALUE_OUTPUT = 'output';
142
+ /**
143
+ * Originally from '@opentelemetry/semantic-conventions/incubating'
144
+ * https://github.com/open-telemetry/semantic-conventions/blob/main/docs/registry/attributes/aws.md#amazon-sns-attributes
145
+ * The ARN of the AWS SNS Topic. An Amazon SNS [topic](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)
146
+ * is a logical access point that acts as a communication channel.
147
+ * @example arn:aws:sns:us-east-1:123456789012:mystack-mytopic-NZJ5JSMVGFIE
148
+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
149
+ */
150
+ exports.ATTR_AWS_SNS_TOPIC_ARN = 'aws.sns.topic.arn';
142
151
  //# sourceMappingURL=semconv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"semconv.js","sourceRoot":"","sources":["../../src/semconv.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH;;;;GAIG;AAEH;;;;;;GAMG;AACU,QAAA,0BAA0B,GAAG,uBAAgC,CAAC;AAE3E;;;;;;GAMG;AACU,QAAA,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;;;GAMG;AACU,QAAA,yBAAyB,GAAG,sBAA+B,CAAC;AAEzE;;;;;;GAMG;AACU,QAAA,kCAAkC,GAC7C,+BAAwC,CAAC;AAE3C;;;;;;GAMG;AACU,QAAA,+BAA+B,GAC1C,4BAAqC,CAAC;AAExC;;;;;;GAMG;AACU,QAAA,yBAAyB,GAAG,sBAA+B,CAAC;AAEzE;;;;;;;GAOG;AACU,QAAA,mCAAmC,GAC9C,gCAAyC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;GAkBG;AACU,QAAA,kBAAkB,GAAG,eAAwB,CAAC;AAE3D;;;;;;;GAOG;AACU,QAAA,sBAAsB,GAAG,mBAA4B,CAAC;AAEnE;;;;;;GAMG;AACU,QAAA,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;;;GAMG;AACU,QAAA,+BAA+B,GAC1C,4BAAqC,CAAC;AAExC;;GAEG;AACU,QAAA,gCAAgC,GAAG,MAAe,CAAC;AAEhE;;GAEG;AACU,QAAA,+BAA+B,GAAG,aAAsB,CAAC;AAEtE;;GAEG;AACU,QAAA,6BAA6B,GAAG,OAAgB,CAAC;AAE9D;;GAEG;AACU,QAAA,8BAA8B,GAAG,QAAiB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the operation being performed.\n *\n * @note If one of the predefined values applies, but specific system uses a different name it's **RECOMMENDED** to document it in the semantic conventions for specific GenAI system and use system-specific name in the instrumentation. If a different name is not documented, instrumentation libraries **SHOULD** use applicable predefined value.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name' as const;\n\n/**\n * The maximum number of tokens the model generates for a request.\n *\n * @example 100\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_MAX_TOKENS =\n 'gen_ai.request.max_tokens' as const;\n\n/**\n * The name of the GenAI model a request is being made to.\n *\n * @example \"gpt-4\"\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model' as const;\n\n/**\n * List of sequences that the model will use to stop generating further tokens.\n *\n * @example [\"forest\", \"lived\"]\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_STOP_SEQUENCES =\n 'gen_ai.request.stop_sequences' as const;\n\n/**\n * The temperature setting for the GenAI request.\n *\n * @example 0.0\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_TEMPERATURE =\n 'gen_ai.request.temperature' as const;\n\n/**\n * The top_p sampling setting for the GenAI request.\n *\n * @example 1.0\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_TOP_P = 'gen_ai.request.top_p' as const;\n\n/**\n * Array of reasons the model stopped generating tokens, corresponding to each generation received.\n *\n * @example [\"stop\"]\n * @example [\"stop\", \"length\"]\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_RESPONSE_FINISH_REASONS =\n 'gen_ai.response.finish_reasons' as const;\n\n/**\n * The Generative AI product as identified by the client or server instrumentation.\n *\n * @example \"openai\"\n *\n * @note The `gen_ai.system` describes a family of GenAI models with specific model identified\n * by `gen_ai.request.model` and `gen_ai.response.model` attributes.\n *\n * The actual GenAI product may differ from the one identified by the client.\n * Multiple systems, including Azure OpenAI and Gemini, are accessible by OpenAI client\n * libraries. In such cases, the `gen_ai.system` is set to `openai` based on the\n * instrumentation's best knowledge, instead of the actual system. The `server.address`\n * attribute may help identify the actual system in use for `openai`.\n *\n * For custom model, a custom friendly name **SHOULD** be used.\n * If none of these options apply, the `gen_ai.system` **SHOULD** be set to `_OTHER`.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_SYSTEM = 'gen_ai.system' as const;\n\n/**\n * The type of token being counted.\n *\n * @example input\n * @example output\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_TOKEN_TYPE = 'gen_ai.token.type' as const;\n\n/**\n * The number of tokens used in the GenAI input (prompt).\n *\n * @example 100\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_USAGE_INPUT_TOKENS =\n 'gen_ai.usage.input_tokens' as const;\n\n/**\n * The number of tokens used in the GenAI response (completion).\n *\n * @example 180\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS =\n 'gen_ai.usage.output_tokens' as const;\n\n/**\n * Enum value \"chat\" for attribute {@link ATTR_GEN_AI_OPERATION_NAME}.\n */\nexport const GEN_AI_OPERATION_NAME_VALUE_CHAT = 'chat' as const;\n\n/**\n * Enum value \"aws.bedrock\" for attribute {@link ATTR_GEN_AI_SYSTEM}.\n */\nexport const GEN_AI_SYSTEM_VALUE_AWS_BEDROCK = 'aws.bedrock' as const;\n\n/**\n * Enum value \"input\" for attribute {@link ATTR_GEN_AI_TOKEN_TYPE}.\n */\nexport const GEN_AI_TOKEN_TYPE_VALUE_INPUT = 'input' as const;\n\n/**\n * Enum value \"output\" for attribute {@link ATTR_GEN_AI_TOKEN_TYPE}.\n */\nexport const GEN_AI_TOKEN_TYPE_VALUE_OUTPUT = 'output' as const;\n"]}
1
+ {"version":3,"file":"semconv.js","sourceRoot":"","sources":["../../src/semconv.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH;;;;GAIG;AAEH;;;;;;GAMG;AACU,QAAA,0BAA0B,GAAG,uBAAgC,CAAC;AAE3E;;;;;;GAMG;AACU,QAAA,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;;;GAMG;AACU,QAAA,yBAAyB,GAAG,sBAA+B,CAAC;AAEzE;;;;;;GAMG;AACU,QAAA,kCAAkC,GAC7C,+BAAwC,CAAC;AAE3C;;;;;;GAMG;AACU,QAAA,+BAA+B,GAC1C,4BAAqC,CAAC;AAExC;;;;;;GAMG;AACU,QAAA,yBAAyB,GAAG,sBAA+B,CAAC;AAEzE;;;;;;;GAOG;AACU,QAAA,mCAAmC,GAC9C,gCAAyC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;GAkBG;AACU,QAAA,kBAAkB,GAAG,eAAwB,CAAC;AAE3D;;;;;;;GAOG;AACU,QAAA,sBAAsB,GAAG,mBAA4B,CAAC;AAEnE;;;;;;GAMG;AACU,QAAA,8BAA8B,GACzC,2BAAoC,CAAC;AAEvC;;;;;;GAMG;AACU,QAAA,+BAA+B,GAC1C,4BAAqC,CAAC;AAExC;;GAEG;AACU,QAAA,gCAAgC,GAAG,MAAe,CAAC;AAEhE;;GAEG;AACU,QAAA,+BAA+B,GAAG,aAAsB,CAAC;AAEtE;;GAEG;AACU,QAAA,6BAA6B,GAAG,OAAgB,CAAC;AAE9D;;GAEG;AACU,QAAA,8BAA8B,GAAG,QAAiB,CAAC;AAEhE;;;;;;;GAOG;AACU,QAAA,sBAAsB,GAAG,mBAA4B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the operation being performed.\n *\n * @note If one of the predefined values applies, but specific system uses a different name it's **RECOMMENDED** to document it in the semantic conventions for specific GenAI system and use system-specific name in the instrumentation. If a different name is not documented, instrumentation libraries **SHOULD** use applicable predefined value.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name' as const;\n\n/**\n * The maximum number of tokens the model generates for a request.\n *\n * @example 100\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_MAX_TOKENS =\n 'gen_ai.request.max_tokens' as const;\n\n/**\n * The name of the GenAI model a request is being made to.\n *\n * @example \"gpt-4\"\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model' as const;\n\n/**\n * List of sequences that the model will use to stop generating further tokens.\n *\n * @example [\"forest\", \"lived\"]\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_STOP_SEQUENCES =\n 'gen_ai.request.stop_sequences' as const;\n\n/**\n * The temperature setting for the GenAI request.\n *\n * @example 0.0\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_TEMPERATURE =\n 'gen_ai.request.temperature' as const;\n\n/**\n * The top_p sampling setting for the GenAI request.\n *\n * @example 1.0\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_REQUEST_TOP_P = 'gen_ai.request.top_p' as const;\n\n/**\n * Array of reasons the model stopped generating tokens, corresponding to each generation received.\n *\n * @example [\"stop\"]\n * @example [\"stop\", \"length\"]\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_RESPONSE_FINISH_REASONS =\n 'gen_ai.response.finish_reasons' as const;\n\n/**\n * The Generative AI product as identified by the client or server instrumentation.\n *\n * @example \"openai\"\n *\n * @note The `gen_ai.system` describes a family of GenAI models with specific model identified\n * by `gen_ai.request.model` and `gen_ai.response.model` attributes.\n *\n * The actual GenAI product may differ from the one identified by the client.\n * Multiple systems, including Azure OpenAI and Gemini, are accessible by OpenAI client\n * libraries. In such cases, the `gen_ai.system` is set to `openai` based on the\n * instrumentation's best knowledge, instead of the actual system. The `server.address`\n * attribute may help identify the actual system in use for `openai`.\n *\n * For custom model, a custom friendly name **SHOULD** be used.\n * If none of these options apply, the `gen_ai.system` **SHOULD** be set to `_OTHER`.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_SYSTEM = 'gen_ai.system' as const;\n\n/**\n * The type of token being counted.\n *\n * @example input\n * @example output\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_TOKEN_TYPE = 'gen_ai.token.type' as const;\n\n/**\n * The number of tokens used in the GenAI input (prompt).\n *\n * @example 100\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_USAGE_INPUT_TOKENS =\n 'gen_ai.usage.input_tokens' as const;\n\n/**\n * The number of tokens used in the GenAI response (completion).\n *\n * @example 180\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS =\n 'gen_ai.usage.output_tokens' as const;\n\n/**\n * Enum value \"chat\" for attribute {@link ATTR_GEN_AI_OPERATION_NAME}.\n */\nexport const GEN_AI_OPERATION_NAME_VALUE_CHAT = 'chat' as const;\n\n/**\n * Enum value \"aws.bedrock\" for attribute {@link ATTR_GEN_AI_SYSTEM}.\n */\nexport const GEN_AI_SYSTEM_VALUE_AWS_BEDROCK = 'aws.bedrock' as const;\n\n/**\n * Enum value \"input\" for attribute {@link ATTR_GEN_AI_TOKEN_TYPE}.\n */\nexport const GEN_AI_TOKEN_TYPE_VALUE_INPUT = 'input' as const;\n\n/**\n * Enum value \"output\" for attribute {@link ATTR_GEN_AI_TOKEN_TYPE}.\n */\nexport const GEN_AI_TOKEN_TYPE_VALUE_OUTPUT = 'output' as const;\n\n/**\n * Originally from '@opentelemetry/semantic-conventions/incubating'\n * https://github.com/open-telemetry/semantic-conventions/blob/main/docs/registry/attributes/aws.md#amazon-sns-attributes\n * The ARN of the AWS SNS Topic. An Amazon SNS [topic](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)\n * is a logical access point that acts as a communication channel.\n * @example arn:aws:sns:us-east-1:123456789012:mystack-mytopic-NZJ5JSMVGFIE\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_AWS_SNS_TOPIC_ARN = 'aws.sns.topic.arn' as const;\n"]}
@@ -2,6 +2,7 @@ import { DiagLogger, HrTime, Meter, Span, SpanAttributes, SpanKind, Tracer } fro
2
2
  import { AwsSdkInstrumentationConfig, NormalizedRequest, NormalizedResponse } from '../types';
3
3
  export interface RequestMetadata {
4
4
  isIncoming: boolean;
5
+ isStream?: boolean;
5
6
  spanAttributes?: SpanAttributes;
6
7
  spanKind?: SpanKind;
7
8
  spanName?: string;
@@ -9,7 +10,7 @@ export interface RequestMetadata {
9
10
  export interface ServiceExtension {
10
11
  requestPreSpanHook: (request: NormalizedRequest, config: AwsSdkInstrumentationConfig, diag: DiagLogger) => RequestMetadata;
11
12
  requestPostSpanHook?: (request: NormalizedRequest) => void;
12
- responseHook?: (response: NormalizedResponse, span: Span, tracer: Tracer, config: AwsSdkInstrumentationConfig, startTime: HrTime) => void;
13
+ responseHook?: (response: NormalizedResponse, span: Span, tracer: Tracer, config: AwsSdkInstrumentationConfig, startTime: HrTime) => any | undefined;
13
14
  updateMetricInstruments?: (meter: Meter) => void;
14
15
  }
15
16
  //# sourceMappingURL=ServiceExtension.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceExtension.js","sourceRoot":"","sources":["../../../src/services/ServiceExtension.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n DiagLogger,\n HrTime,\n Meter,\n Span,\n SpanAttributes,\n SpanKind,\n Tracer,\n} from '@opentelemetry/api';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\n\nexport interface RequestMetadata {\n // isIncoming - if true, then the operation callback / promise should be bind with the operation's span\n isIncoming: boolean;\n spanAttributes?: SpanAttributes;\n spanKind?: SpanKind;\n spanName?: string;\n}\n\nexport interface ServiceExtension {\n // called before request is sent, and before span is started\n requestPreSpanHook: (\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ) => RequestMetadata;\n\n // called before request is sent, and after span is started\n requestPostSpanHook?: (request: NormalizedRequest) => void;\n\n responseHook?: (\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) => void;\n\n updateMetricInstruments?: (meter: Meter) => void;\n}\n"]}
1
+ {"version":3,"file":"ServiceExtension.js","sourceRoot":"","sources":["../../../src/services/ServiceExtension.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n DiagLogger,\n HrTime,\n Meter,\n Span,\n SpanAttributes,\n SpanKind,\n Tracer,\n} from '@opentelemetry/api';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\n\nexport interface RequestMetadata {\n // isIncoming - if true, then the operation callback / promise should be bind with the operation's span\n isIncoming: boolean;\n // isStream - if true, then the response is a stream so the span should not be ended by the middleware.\n // the ServiceExtension must end the span itself, generally by wrapping the stream and ending after it is\n // consumed.\n isStream?: boolean;\n spanAttributes?: SpanAttributes;\n spanKind?: SpanKind;\n spanName?: string;\n}\n\nexport interface ServiceExtension {\n // called before request is sent, and before span is started\n requestPreSpanHook: (\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ) => RequestMetadata;\n\n // called before request is sent, and after span is started\n requestPostSpanHook?: (request: NormalizedRequest) => void;\n\n // called after response is received. If value is returned, it replaces the response output.\n responseHook?: (\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) => any | undefined;\n\n updateMetricInstruments?: (meter: Meter) => void;\n}\n"]}
@@ -6,7 +6,7 @@ export declare class ServicesExtensions implements ServiceExtension {
6
6
  constructor();
7
7
  requestPreSpanHook(request: NormalizedRequest, config: AwsSdkInstrumentationConfig, diag: DiagLogger): RequestMetadata;
8
8
  requestPostSpanHook(request: NormalizedRequest): void;
9
- responseHook(response: NormalizedResponse, span: Span, tracer: Tracer, config: AwsSdkInstrumentationConfig, startTime: HrTime): void;
9
+ responseHook(response: NormalizedResponse, span: Span, tracer: Tracer, config: AwsSdkInstrumentationConfig, startTime: HrTime): any;
10
10
  updateMetricInstruments(meter: Meter): void;
11
11
  }
12
12
  //# sourceMappingURL=ServicesExtensions.d.ts.map
@@ -35,7 +35,7 @@ class ServicesExtensions {
35
35
  }
36
36
  responseHook(response, span, tracer, config, startTime) {
37
37
  const serviceExtension = this.services.get(response.request.serviceName);
38
- serviceExtension?.responseHook?.(response, span, tracer, config, startTime);
38
+ return serviceExtension?.responseHook?.(response, span, tracer, config, startTime);
39
39
  }
40
40
  updateMetricInstruments(meter) {
41
41
  for (const serviceExtension of this.services.values()) {
@@ -1 +1 @@
1
- {"version":3,"file":"ServicesExtensions.js","sourceRoot":"","sources":["../../../src/services/ServicesExtensions.ts"],"names":[],"mappings":";;;AAiBA,+BAA4C;A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CAAC;QAChE,IAAI,CAAC,gBAAgB,EAAE,mBAAmB;YAAE,OAAO;QACnD,OAAO,gBAAgB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IAED,YAAY,CACV,QAA4B,EAC5B,IAAU,EACV,MAAc,EACd,MAAmC,EACnC,SAAiB;QAEjB,MAAM,gBAAgB,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACzE,gBAAgB,EAAE,YAAY,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;IAC9E,CAAC;IAED,uBAAuB,CAAC,KAAY;QAClC,KAAK,MAAM,gBAAgB,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE;YACrD,gBAAgB,CAAC,uBAAuB,EAAE,CAAC,KAAK,CAAC,CAAC;SACnD;IACH,CAAC;CACF;AAhDD,gDAgDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Tracer, Span, DiagLogger, Meter, HrTime } from '@opentelemetry/api';\nimport { ServiceExtension, RequestMetadata } from './ServiceExtension';\nimport { SqsServiceExtension } from './sqs';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\nimport { BedrockRuntimeServiceExtension } from './bedrock-runtime';\nimport { DynamodbServiceExtension } from './dynamodb';\nimport { SnsServiceExtension } from './sns';\nimport { LambdaServiceExtension } from './lambda';\nimport { S3ServiceExtension } from './s3';\nimport { KinesisServiceExtension } from './kinesis';\n\nexport class ServicesExtensions implements ServiceExtension {\n services: Map<string, ServiceExtension> = new Map();\n\n constructor() {\n this.services.set('SQS', new SqsServiceExtension());\n this.services.set('SNS', new SnsServiceExtension());\n this.services.set('DynamoDB', new DynamodbServiceExtension());\n this.services.set('Lambda', new LambdaServiceExtension());\n this.services.set('S3', new S3ServiceExtension());\n this.services.set('Kinesis', new KinesisServiceExtension());\n this.services.set('BedrockRuntime', new BedrockRuntimeServiceExtension());\n }\n\n requestPreSpanHook(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n const serviceExtension = this.services.get(request.serviceName);\n if (!serviceExtension)\n return {\n isIncoming: false,\n };\n return serviceExtension.requestPreSpanHook(request, config, diag);\n }\n\n requestPostSpanHook(request: NormalizedRequest) {\n const serviceExtension = this.services.get(request.serviceName);\n if (!serviceExtension?.requestPostSpanHook) return;\n return serviceExtension.requestPostSpanHook(request);\n }\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n const serviceExtension = this.services.get(response.request.serviceName);\n serviceExtension?.responseHook?.(response, span, tracer, config, startTime);\n }\n\n updateMetricInstruments(meter: Meter) {\n for (const serviceExtension of this.services.values()) {\n serviceExtension.updateMetricInstruments?.(meter);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"ServicesExtensions.js","sourceRoot":"","sources":["../../../src/services/ServicesExtensions.ts"],"names":[],"mappings":";;;AAiBA,+BAA4C;AAM5C,uDAAmE;AACnE,yCAAsD;AACtD,+BAA4C;AAC5C,qCAAkD;AAClD,6BAA0C;AAC1C,uCAAoD;AAEpD,MAAa,kBAAkB;IAC7B,QAAQ,GAAkC,IAAI,GAAG,EAAE,CAAC;IAEpD;QACE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,yBAAmB,EAAE,CAAC,C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Q,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QAEzE,OAAO,gBAAgB,EAAE,YAAY,EAAE,CACrC,QAAQ,EACR,IAAI,EACJ,MAAM,EACN,MAAM,EACN,SAAS,CACV,CAAC;IACJ,CAAC;IAED,uBAAuB,CAAC,KAAY;QAClC,KAAK,MAAM,gBAAgB,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE;YACrD,gBAAgB,CAAC,uBAAuB,EAAE,CAAC,KAAK,CAAC,CAAC;SACnD;IACH,CAAC;CACF;AAvDD,gDAuDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Tracer, Span, DiagLogger, Meter, HrTime } from '@opentelemetry/api';\nimport { ServiceExtension, RequestMetadata } from './ServiceExtension';\nimport { SqsServiceExtension } from './sqs';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\nimport { BedrockRuntimeServiceExtension } from './bedrock-runtime';\nimport { DynamodbServiceExtension } from './dynamodb';\nimport { SnsServiceExtension } from './sns';\nimport { LambdaServiceExtension } from './lambda';\nimport { S3ServiceExtension } from './s3';\nimport { KinesisServiceExtension } from './kinesis';\n\nexport class ServicesExtensions implements ServiceExtension {\n services: Map<string, ServiceExtension> = new Map();\n\n constructor() {\n this.services.set('SQS', new SqsServiceExtension());\n this.services.set('SNS', new SnsServiceExtension());\n this.services.set('DynamoDB', new DynamodbServiceExtension());\n this.services.set('Lambda', new LambdaServiceExtension());\n this.services.set('S3', new S3ServiceExtension());\n this.services.set('Kinesis', new KinesisServiceExtension());\n this.services.set('BedrockRuntime', new BedrockRuntimeServiceExtension());\n }\n\n requestPreSpanHook(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n const serviceExtension = this.services.get(request.serviceName);\n if (!serviceExtension)\n return {\n isIncoming: false,\n };\n return serviceExtension.requestPreSpanHook(request, config, diag);\n }\n\n requestPostSpanHook(request: NormalizedRequest) {\n const serviceExtension = this.services.get(request.serviceName);\n if (!serviceExtension?.requestPostSpanHook) return;\n return serviceExtension.requestPostSpanHook(request);\n }\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n const serviceExtension = this.services.get(response.request.serviceName);\n\n return serviceExtension?.responseHook?.(\n response,\n span,\n tracer,\n config,\n startTime\n );\n }\n\n updateMetricInstruments(meter: Meter) {\n for (const serviceExtension of this.services.values()) {\n serviceExtension.updateMetricInstruments?.(meter);\n }\n }\n}\n"]}
@@ -8,8 +8,12 @@ export declare class BedrockRuntimeServiceExtension implements ServiceExtension
8
8
  requestPreSpanHook(request: NormalizedRequest, config: AwsSdkInstrumentationConfig, diag: DiagLogger): RequestMetadata;
9
9
  private requestPreSpanHookConverse;
10
10
  private requestPreSpanHookInvokeModel;
11
- responseHook(response: NormalizedResponse, span: Span, tracer: Tracer, config: AwsSdkInstrumentationConfig, startTime: HrTime): void;
11
+ responseHook(response: NormalizedResponse, span: Span, tracer: Tracer, config: AwsSdkInstrumentationConfig, startTime: HrTime): any;
12
12
  private responseHookConverse;
13
+ private responseHookConverseStream;
14
+ private wrapConverseStreamResponse;
15
+ private static setStopReason;
16
+ private setUsage;
13
17
  private responseHookInvokeModel;
14
18
  }
15
19
  //# sourceMappingURL=bedrock-runtime.d.ts.map
@@ -50,7 +50,9 @@ class BedrockRuntimeServiceExtension {
50
50
  requestPreSpanHook(request, config, diag) {
51
51
  switch (request.commandName) {
52
52
  case 'Converse':
53
- return this.requestPreSpanHookConverse(request, config, diag);
53
+ return this.requestPreSpanHookConverse(request, config, diag, false);
54
+ case 'ConverseStream':
55
+ return this.requestPreSpanHookConverse(request, config, diag, true);
54
56
  case 'InvokeModel':
55
57
  return this.requestPreSpanHookInvokeModel(request, config, diag);
56
58
  }
@@ -58,7 +60,7 @@ class BedrockRuntimeServiceExtension {
58
60
  isIncoming: false,
59
61
  };
60
62
  }
61
- requestPreSpanHookConverse(request, config, diag) {
63
+ requestPreSpanHookConverse(request, config, diag, isStream) {
62
64
  let spanName = semconv_1.GEN_AI_OPERATION_NAME_VALUE_CHAT;
63
65
  const spanAttributes = {
64
66
  [semconv_1.ATTR_GEN_AI_SYSTEM]: semconv_1.GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,
@@ -90,6 +92,7 @@ class BedrockRuntimeServiceExtension {
90
92
  return {
91
93
  spanName,
92
94
  isIncoming: false,
95
+ isStream,
93
96
  spanAttributes,
94
97
  };
95
98
  }
@@ -254,12 +257,45 @@ class BedrockRuntimeServiceExtension {
254
257
  switch (response.request.commandName) {
255
258
  case 'Converse':
256
259
  return this.responseHookConverse(response, span, tracer, config, startTime);
260
+ case 'ConverseStream':
261
+ return this.responseHookConverseStream(response, span, tracer, config, startTime);
257
262
  case 'InvokeModel':
258
263
  return this.responseHookInvokeModel(response, span, tracer, config);
259
264
  }
260
265
  }
261
266
  responseHookConverse(response, span, tracer, config, startTime) {
262
267
  const { stopReason, usage } = response.data;
268
+ BedrockRuntimeServiceExtension.setStopReason(span, stopReason);
269
+ this.setUsage(response, span, usage, startTime);
270
+ }
271
+ responseHookConverseStream(response, span, tracer, config, startTime) {
272
+ return {
273
+ ...response.data,
274
+ // Wrap and replace the response stream to allow processing events to telemetry
275
+ // before yielding to the user.
276
+ stream: this.wrapConverseStreamResponse(response, response.data.stream, span, startTime),
277
+ };
278
+ }
279
+ async *wrapConverseStreamResponse(response, stream, span, startTime) {
280
+ try {
281
+ let usage;
282
+ for await (const item of stream) {
283
+ BedrockRuntimeServiceExtension.setStopReason(span, item.messageStop?.stopReason);
284
+ usage = item.metadata?.usage;
285
+ yield item;
286
+ }
287
+ this.setUsage(response, span, usage, startTime);
288
+ }
289
+ finally {
290
+ span.end();
291
+ }
292
+ }
293
+ static setStopReason(span, stopReason) {
294
+ if (stopReason !== undefined) {
295
+ span.setAttribute(semconv_1.ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [stopReason]);
296
+ }
297
+ }
298
+ setUsage(response, span, usage, startTime) {
263
299
  const sharedMetricAttrs = {
264
300
  [semconv_1.ATTR_GEN_AI_SYSTEM]: semconv_1.GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,
265
301
  [semconv_1.ATTR_GEN_AI_OPERATION_NAME]: semconv_1.GEN_AI_OPERATION_NAME_VALUE_CHAT,
@@ -284,9 +320,6 @@ class BedrockRuntimeServiceExtension {
284
320
  });
285
321
  }
286
322
  }
287
- if (stopReason !== undefined) {
288
- span.setAttribute(semconv_1.ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [stopReason]);
289
- }
290
323
  }
291
324
  responseHookInvokeModel(response, span, tracer, config) {
292
325
  const currentModelId = response.request.commandInput?.modelId;
@@ -1 +1 @@
1
- {"version":3,"file":"bedrock-runtime.js","sourceRoot":"","sources":["../../../src/services/bedrock-runtime.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAS4B;AAE5B,wCAgBoB;AAMpB,8CAI6B;AAE7B,MAAa,8BAA8B;IACjC,UAAU,CAAa;IACvB,iBAAiB,CAAa;IAEtC,uBAAuB,CAAC,KAAY;QAClC,mGAAmG;QACnG,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,eAAe,CAAC,2BAA2B,EAAE;YACnE,IAAI,EAAE,SAAS;YACf,WAAW,EAAE,iDAAiD;YAC9D,SAAS,EAAE,eAAS,CAAC,GAAG;YACxB,MAAM,EAAE;gBACN,wBAAwB,EAAE;oBACxB,C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9D,IAAI,CAAC,YAAY,CAAC,6CAAmC,EAAE;wBACrD,YAAY,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,aAAa;qBAC1C,CAAC,CAAC;iBACJ;aACF;iBAAM,IAAI,cAAc,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;gBAC7C,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,KAAK,SAAS,EAAE;oBACjD,IAAI,CAAC,YAAY,CACf,yCAA+B;oBAC/B,8FAA8F;oBAC9F,+FAA+F;oBAC/F,wFAAwF;oBACxF,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CACnD,CAAC;iBACH;gBACD,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,KAAK,SAAS,EAAE;oBACxD,IAAI,CAAC,YAAY,CAAC,6CAAmC,EAAE;wBACrD,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,WAAW;qBACpC,CAAC,CAAC;iBACJ;aACF;SACF;IACH,CAAC;CACF;AAzcD,wEAycC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Attributes,\n DiagLogger,\n Histogram,\n HrTime,\n Meter,\n Span,\n Tracer,\n ValueType,\n} from '@opentelemetry/api';\nimport { RequestMetadata, ServiceExtension } from './ServiceExtension';\nimport {\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_REQUEST_MAX_TOKENS,\n ATTR_GEN_AI_REQUEST_TEMPERATURE,\n ATTR_GEN_AI_REQUEST_TOP_P,\n ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n ATTR_GEN_AI_TOKEN_TYPE,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n GEN_AI_TOKEN_TYPE_VALUE_INPUT,\n GEN_AI_TOKEN_TYPE_VALUE_OUTPUT,\n} from '../semconv';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\nimport {\n hrTime,\n hrTimeDuration,\n hrTimeToMilliseconds,\n} from '@opentelemetry/core';\n\nexport class BedrockRuntimeServiceExtension implements ServiceExtension {\n private tokenUsage!: Histogram;\n private operationDuration!: Histogram;\n\n updateMetricInstruments(meter: Meter) {\n // https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/#metric-gen_aiclienttokenusage\n this.tokenUsage = meter.createHistogram('gen_ai.client.token.usage', {\n unit: '{token}',\n description: 'Measures number of input and output tokens used',\n valueType: ValueType.INT,\n advice: {\n explicitBucketBoundaries: [\n 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n 16777216, 67108864,\n ],\n },\n });\n\n // https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/#metric-gen_aiclientoperationduration\n this.operationDuration = meter.createHistogram(\n 'gen_ai.client.operation.duration',\n {\n unit: 's',\n description: 'GenAI operation duration',\n advice: {\n explicitBucketBoundaries: [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24,\n 20.48, 40.96, 81.92,\n ],\n },\n }\n );\n }\n\n requestPreSpanHook(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n switch (request.commandName) {\n case 'Converse':\n return this.requestPreSpanHookConverse(request, config, diag);\n case 'InvokeModel':\n return this.requestPreSpanHookInvokeModel(request, config, diag);\n }\n\n return {\n isIncoming: false,\n };\n }\n\n private requestPreSpanHookConverse(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_CHAT;\n const spanAttributes: Attributes = {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n };\n\n const modelId = request.commandInput.modelId;\n if (modelId) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MODEL] = modelId;\n if (spanName) {\n spanName += ` ${modelId}`;\n }\n }\n\n const inferenceConfig = request.commandInput.inferenceConfig;\n if (inferenceConfig) {\n const { maxTokens, temperature, topP, stopSequences } = inferenceConfig;\n if (maxTokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] = maxTokens;\n }\n if (temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] = temperature;\n }\n if (topP !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = topP;\n }\n if (stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = stopSequences;\n }\n }\n\n return {\n spanName,\n isIncoming: false,\n spanAttributes,\n };\n }\n\n private requestPreSpanHookInvokeModel(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n let spanName: string | undefined;\n const spanAttributes: Attributes = {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n // add operation name for InvokeModel API\n };\n\n const modelId = request.commandInput?.modelId;\n if (modelId) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MODEL] = modelId;\n }\n\n if (request.commandInput?.body) {\n const requestBody = JSON.parse(request.commandInput.body);\n if (modelId.includes('amazon.titan')) {\n if (requestBody.textGenerationConfig?.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.textGenerationConfig.temperature;\n }\n if (requestBody.textGenerationConfig?.topP !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] =\n requestBody.textGenerationConfig.topP;\n }\n if (requestBody.textGenerationConfig?.maxTokenCount !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.textGenerationConfig.maxTokenCount;\n }\n if (requestBody.textGenerationConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.textGenerationConfig.stopSequences;\n }\n } else if (modelId.includes('amazon.nova')) {\n if (requestBody.inferenceConfig?.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.inferenceConfig.temperature;\n }\n if (requestBody.inferenceConfig?.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] =\n requestBody.inferenceConfig.top_p;\n }\n if (requestBody.inferenceConfig?.max_new_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.inferenceConfig.max_new_tokens;\n }\n if (requestBody.inferenceConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.inferenceConfig.stopSequences;\n }\n } else if (modelId.includes('anthropic.claude')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.stop_sequences;\n }\n } else if (modelId.includes('meta.llama')) {\n if (requestBody.max_gen_len !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_gen_len;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n // request for meta llama models does not contain stop_sequences field\n } else if (modelId.includes('cohere.command-r')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.message !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n spanAttributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(\n requestBody.message.length / 6\n );\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.stop_sequences;\n }\n } else if (modelId.includes('cohere.command')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.prompt !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n spanAttributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(\n requestBody.prompt.length / 6\n );\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.stop_sequences;\n }\n } else if (modelId.includes('mistral')) {\n if (requestBody.prompt !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n spanAttributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(\n requestBody.prompt.length / 6\n );\n }\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop;\n }\n }\n }\n\n return {\n spanName,\n isIncoming: false,\n spanAttributes,\n };\n }\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n if (!span.isRecording()) {\n return;\n }\n\n switch (response.request.commandName) {\n case 'Converse':\n return this.responseHookConverse(\n response,\n span,\n tracer,\n config,\n startTime\n );\n case 'InvokeModel':\n return this.responseHookInvokeModel(response, span, tracer, config);\n }\n }\n\n private responseHookConverse(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n const { stopReason, usage } = response.data;\n\n const sharedMetricAttrs: Attributes = {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n [ATTR_GEN_AI_REQUEST_MODEL]: response.request.commandInput.modelId,\n };\n\n const durationSecs =\n hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime())) / 1000;\n this.operationDuration.record(durationSecs, sharedMetricAttrs);\n\n if (usage) {\n const { inputTokens, outputTokens } = usage;\n if (inputTokens !== undefined) {\n span.setAttribute(ATTR_GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n\n this.tokenUsage.record(inputTokens, {\n ...sharedMetricAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: GEN_AI_TOKEN_TYPE_VALUE_INPUT,\n });\n }\n if (outputTokens !== undefined) {\n span.setAttribute(ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n\n this.tokenUsage.record(outputTokens, {\n ...sharedMetricAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: GEN_AI_TOKEN_TYPE_VALUE_OUTPUT,\n });\n }\n }\n\n if (stopReason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [stopReason]);\n }\n }\n\n private responseHookInvokeModel(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig\n ) {\n const currentModelId = response.request.commandInput?.modelId;\n if (response.data?.body) {\n const decodedResponseBody = new TextDecoder().decode(response.data.body);\n const responseBody = JSON.parse(decodedResponseBody);\n if (currentModelId.includes('amazon.titan')) {\n if (responseBody.inputTextTokenCount !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.inputTextTokenCount\n );\n }\n if (responseBody.results?.[0]?.tokenCount !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.results[0].tokenCount\n );\n }\n if (responseBody.results?.[0]?.completionReason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.results[0].completionReason,\n ]);\n }\n } else if (currentModelId.includes('amazon.nova')) {\n if (responseBody.usage !== undefined) {\n if (responseBody.usage.inputTokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.usage.inputTokens\n );\n }\n if (responseBody.usage.outputTokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.usage.outputTokens\n );\n }\n }\n if (responseBody.stopReason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.stopReason,\n ]);\n }\n } else if (currentModelId.includes('anthropic.claude')) {\n if (responseBody.usage?.input_tokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.usage.input_tokens\n );\n }\n if (responseBody.usage?.output_tokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.usage.output_tokens\n );\n }\n if (responseBody.stop_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.stop_reason,\n ]);\n }\n } else if (currentModelId.includes('meta.llama')) {\n if (responseBody.prompt_token_count !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.prompt_token_count\n );\n }\n if (responseBody.generation_token_count !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.generation_token_count\n );\n }\n if (responseBody.stop_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.stop_reason,\n ]);\n }\n } else if (currentModelId.includes('cohere.command-r')) {\n if (responseBody.text !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n Math.ceil(responseBody.text.length / 6)\n );\n }\n if (responseBody.finish_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.finish_reason,\n ]);\n }\n } else if (currentModelId.includes('cohere.command')) {\n if (responseBody.generations?.[0]?.text !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n Math.ceil(responseBody.generations[0].text.length / 6)\n );\n }\n if (responseBody.generations?.[0]?.finish_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.generations[0].finish_reason,\n ]);\n }\n } else if (currentModelId.includes('mistral')) {\n if (responseBody.outputs?.[0]?.text !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n Math.ceil(responseBody.outputs[0].text.length / 6)\n );\n }\n if (responseBody.outputs?.[0]?.stop_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.outputs[0].stop_reason,\n ]);\n }\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"bedrock-runtime.js","sourceRoot":"","sources":["../../../src/services/bedrock-runtime.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAS4B;AAE5B,wCAgBoB;AAUpB,8CAI6B;AAE7B,MAAa,8BAA8B;IACjC,UAAU,CAAa;IACvB,iBAAiB,CAAa;IAEtC,uBAAuB,CAAC,KAAY;QAClC,mGAAmG;QACnG,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,eAAe,CAAC,2BAA2B,EAAE;YACnE,IAAI,EAAE,SAAS;YACf,WAAW,EAAE,iDAAiD;YAC9D,SAAS,EAAE,eAAS,CAAC,GAAG;YACxB,MAAM,EAAE;gBACN,wBAAwB,EAAE;oBACxB,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO;oBACrE,QAAQ,EAAE,QAAQ;iBACnB;aACF;SACF,CAAC,CAAC;QAEH,0GAA0G;QAC1G,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC,eAAe,CAC5C,kCAAkC,EAClC;YACE,IAAI,EAAE,GAAG;YACT,WAAW,EAAE,0BAA0B;YACvC,MAAM,EAAE;gBACN,wBAAwB,EAAE;oBACxB,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK;oBACjE,KAAK,EAAE,KAAK,EAAE,KAAK;iBACpB;aACF;SACF,CACF,CAAC;IACJ,CAAC;IAED,kBAAkB,CAChB,OAA0B,EAC1B,MAAmC,EACnC,IAAgB;QAEhB,QAAQ,OAAO,CAAC,WAAW,EAAE;YAC3B,KAAK,UAAU;gBACb,OAAO,IAAI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xD,IAAI,CAAC,YAAY,CAAC,6CAAmC,EAAE;wBACrD,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,WAAW;qBACpC,CAAC,CAAC;iBACJ;aACF;SACF;IACH,CAAC;CACF;AA3gBD,wEA2gBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Attributes,\n DiagLogger,\n Histogram,\n HrTime,\n Meter,\n Span,\n Tracer,\n ValueType,\n} from '@opentelemetry/api';\nimport { RequestMetadata, ServiceExtension } from './ServiceExtension';\nimport {\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_REQUEST_MAX_TOKENS,\n ATTR_GEN_AI_REQUEST_TEMPERATURE,\n ATTR_GEN_AI_REQUEST_TOP_P,\n ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n ATTR_GEN_AI_TOKEN_TYPE,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n GEN_AI_TOKEN_TYPE_VALUE_INPUT,\n GEN_AI_TOKEN_TYPE_VALUE_OUTPUT,\n} from '../semconv';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\nimport type {\n ConverseStreamOutput,\n TokenUsage,\n} from '@aws-sdk/client-bedrock-runtime';\nimport {\n hrTime,\n hrTimeDuration,\n hrTimeToMilliseconds,\n} from '@opentelemetry/core';\n\nexport class BedrockRuntimeServiceExtension implements ServiceExtension {\n private tokenUsage!: Histogram;\n private operationDuration!: Histogram;\n\n updateMetricInstruments(meter: Meter) {\n // https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/#metric-gen_aiclienttokenusage\n this.tokenUsage = meter.createHistogram('gen_ai.client.token.usage', {\n unit: '{token}',\n description: 'Measures number of input and output tokens used',\n valueType: ValueType.INT,\n advice: {\n explicitBucketBoundaries: [\n 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n 16777216, 67108864,\n ],\n },\n });\n\n // https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/#metric-gen_aiclientoperationduration\n this.operationDuration = meter.createHistogram(\n 'gen_ai.client.operation.duration',\n {\n unit: 's',\n description: 'GenAI operation duration',\n advice: {\n explicitBucketBoundaries: [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24,\n 20.48, 40.96, 81.92,\n ],\n },\n }\n );\n }\n\n requestPreSpanHook(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n switch (request.commandName) {\n case 'Converse':\n return this.requestPreSpanHookConverse(request, config, diag, false);\n case 'ConverseStream':\n return this.requestPreSpanHookConverse(request, config, diag, true);\n case 'InvokeModel':\n return this.requestPreSpanHookInvokeModel(request, config, diag);\n }\n\n return {\n isIncoming: false,\n };\n }\n\n private requestPreSpanHookConverse(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger,\n isStream: boolean\n ): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_CHAT;\n const spanAttributes: Attributes = {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n };\n\n const modelId = request.commandInput.modelId;\n if (modelId) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MODEL] = modelId;\n if (spanName) {\n spanName += ` ${modelId}`;\n }\n }\n\n const inferenceConfig = request.commandInput.inferenceConfig;\n if (inferenceConfig) {\n const { maxTokens, temperature, topP, stopSequences } = inferenceConfig;\n if (maxTokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] = maxTokens;\n }\n if (temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] = temperature;\n }\n if (topP !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = topP;\n }\n if (stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = stopSequences;\n }\n }\n\n return {\n spanName,\n isIncoming: false,\n isStream,\n spanAttributes,\n };\n }\n\n private requestPreSpanHookInvokeModel(\n request: NormalizedRequest,\n config: AwsSdkInstrumentationConfig,\n diag: DiagLogger\n ): RequestMetadata {\n let spanName: string | undefined;\n const spanAttributes: Attributes = {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n // add operation name for InvokeModel API\n };\n\n const modelId = request.commandInput?.modelId;\n if (modelId) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MODEL] = modelId;\n }\n\n if (request.commandInput?.body) {\n const requestBody = JSON.parse(request.commandInput.body);\n if (modelId.includes('amazon.titan')) {\n if (requestBody.textGenerationConfig?.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.textGenerationConfig.temperature;\n }\n if (requestBody.textGenerationConfig?.topP !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] =\n requestBody.textGenerationConfig.topP;\n }\n if (requestBody.textGenerationConfig?.maxTokenCount !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.textGenerationConfig.maxTokenCount;\n }\n if (requestBody.textGenerationConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.textGenerationConfig.stopSequences;\n }\n } else if (modelId.includes('amazon.nova')) {\n if (requestBody.inferenceConfig?.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.inferenceConfig.temperature;\n }\n if (requestBody.inferenceConfig?.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] =\n requestBody.inferenceConfig.top_p;\n }\n if (requestBody.inferenceConfig?.max_new_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.inferenceConfig.max_new_tokens;\n }\n if (requestBody.inferenceConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.inferenceConfig.stopSequences;\n }\n } else if (modelId.includes('anthropic.claude')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.stop_sequences;\n }\n } else if (modelId.includes('meta.llama')) {\n if (requestBody.max_gen_len !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_gen_len;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n // request for meta llama models does not contain stop_sequences field\n } else if (modelId.includes('cohere.command-r')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.message !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n spanAttributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(\n requestBody.message.length / 6\n );\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.stop_sequences;\n }\n } else if (modelId.includes('cohere.command')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.prompt !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n spanAttributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(\n requestBody.prompt.length / 6\n );\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] =\n requestBody.stop_sequences;\n }\n } else if (modelId.includes('mistral')) {\n if (requestBody.prompt !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n spanAttributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(\n requestBody.prompt.length / 6\n );\n }\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] =\n requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] =\n requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop;\n }\n }\n }\n\n return {\n spanName,\n isIncoming: false,\n spanAttributes,\n };\n }\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n if (!span.isRecording()) {\n return;\n }\n\n switch (response.request.commandName) {\n case 'Converse':\n return this.responseHookConverse(\n response,\n span,\n tracer,\n config,\n startTime\n );\n case 'ConverseStream':\n return this.responseHookConverseStream(\n response,\n span,\n tracer,\n config,\n startTime\n );\n case 'InvokeModel':\n return this.responseHookInvokeModel(response, span, tracer, config);\n }\n }\n\n private responseHookConverse(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n const { stopReason, usage } = response.data;\n\n BedrockRuntimeServiceExtension.setStopReason(span, stopReason);\n this.setUsage(response, span, usage, startTime);\n }\n\n private responseHookConverseStream(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig,\n startTime: HrTime\n ) {\n return {\n ...response.data,\n // Wrap and replace the response stream to allow processing events to telemetry\n // before yielding to the user.\n stream: this.wrapConverseStreamResponse(\n response,\n response.data.stream,\n span,\n startTime\n ),\n };\n }\n\n private async *wrapConverseStreamResponse(\n response: NormalizedResponse,\n stream: AsyncIterable<ConverseStreamOutput>,\n span: Span,\n startTime: HrTime\n ) {\n try {\n let usage: TokenUsage | undefined;\n for await (const item of stream) {\n BedrockRuntimeServiceExtension.setStopReason(\n span,\n item.messageStop?.stopReason\n );\n usage = item.metadata?.usage;\n yield item;\n }\n this.setUsage(response, span, usage, startTime);\n } finally {\n span.end();\n }\n }\n\n private static setStopReason(span: Span, stopReason: string | undefined) {\n if (stopReason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [stopReason]);\n }\n }\n\n private setUsage(\n response: NormalizedResponse,\n span: Span,\n usage: TokenUsage | undefined,\n startTime: HrTime\n ) {\n const sharedMetricAttrs: Attributes = {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n [ATTR_GEN_AI_REQUEST_MODEL]: response.request.commandInput.modelId,\n };\n\n const durationSecs =\n hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime())) / 1000;\n this.operationDuration.record(durationSecs, sharedMetricAttrs);\n\n if (usage) {\n const { inputTokens, outputTokens } = usage;\n if (inputTokens !== undefined) {\n span.setAttribute(ATTR_GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n\n this.tokenUsage.record(inputTokens, {\n ...sharedMetricAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: GEN_AI_TOKEN_TYPE_VALUE_INPUT,\n });\n }\n if (outputTokens !== undefined) {\n span.setAttribute(ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n\n this.tokenUsage.record(outputTokens, {\n ...sharedMetricAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: GEN_AI_TOKEN_TYPE_VALUE_OUTPUT,\n });\n }\n }\n }\n\n private responseHookInvokeModel(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig\n ) {\n const currentModelId = response.request.commandInput?.modelId;\n if (response.data?.body) {\n const decodedResponseBody = new TextDecoder().decode(response.data.body);\n const responseBody = JSON.parse(decodedResponseBody);\n if (currentModelId.includes('amazon.titan')) {\n if (responseBody.inputTextTokenCount !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.inputTextTokenCount\n );\n }\n if (responseBody.results?.[0]?.tokenCount !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.results[0].tokenCount\n );\n }\n if (responseBody.results?.[0]?.completionReason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.results[0].completionReason,\n ]);\n }\n } else if (currentModelId.includes('amazon.nova')) {\n if (responseBody.usage !== undefined) {\n if (responseBody.usage.inputTokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.usage.inputTokens\n );\n }\n if (responseBody.usage.outputTokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.usage.outputTokens\n );\n }\n }\n if (responseBody.stopReason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.stopReason,\n ]);\n }\n } else if (currentModelId.includes('anthropic.claude')) {\n if (responseBody.usage?.input_tokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.usage.input_tokens\n );\n }\n if (responseBody.usage?.output_tokens !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.usage.output_tokens\n );\n }\n if (responseBody.stop_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.stop_reason,\n ]);\n }\n } else if (currentModelId.includes('meta.llama')) {\n if (responseBody.prompt_token_count !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n responseBody.prompt_token_count\n );\n }\n if (responseBody.generation_token_count !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n responseBody.generation_token_count\n );\n }\n if (responseBody.stop_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.stop_reason,\n ]);\n }\n } else if (currentModelId.includes('cohere.command-r')) {\n if (responseBody.text !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n Math.ceil(responseBody.text.length / 6)\n );\n }\n if (responseBody.finish_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.finish_reason,\n ]);\n }\n } else if (currentModelId.includes('cohere.command')) {\n if (responseBody.generations?.[0]?.text !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n Math.ceil(responseBody.generations[0].text.length / 6)\n );\n }\n if (responseBody.generations?.[0]?.finish_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.generations[0].finish_reason,\n ]);\n }\n } else if (currentModelId.includes('mistral')) {\n if (responseBody.outputs?.[0]?.text !== undefined) {\n span.setAttribute(\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n // NOTE: We approximate the token count since this value is not directly available in the body\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n // https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-prepare.html\n Math.ceil(responseBody.outputs[0].text.length / 6)\n );\n }\n if (responseBody.outputs?.[0]?.stop_reason !== undefined) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [\n responseBody.outputs[0].stop_reason,\n ]);\n }\n }\n }\n }\n}\n"]}
@@ -80,8 +80,8 @@ const injectLambdaPropagationContext = (clientContext) => {
80
80
  : {};
81
81
  const updatedClientContext = {
82
82
  ...parsedClientContext,
83
- Custom: {
84
- ...parsedClientContext.Custom,
83
+ custom: {
84
+ ...parsedClientContext.custom,
85
85
  ...propagatedContext,
86
86
  },
87
87
  };
@@ -1 +1 @@
1
- {"version":3,"file":"lambda.js","sourceRoot":"","sources":["../../../src/services/lambda.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAA8E;AAC9E,8EAK6C;AAO7C,4CAA0D;AAE1D,MAAM,cAAc;IACX,MAAM,CAAU,MAAM,GAAW,QAAQ,CAAC;;AAGnD,MAAa,sBAAsB;IACjC,kBAAkB,CAChB,OAA0B,EAC1B,OAAoC;QAEpC,MAAM,YAAY,GAAG,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAEpE,IAAI,cAAc,GAAe,EAAE,CAAC;QACpC,IAAI,QAA4B,CAAC;QAEjC,QAAQ,OAAO,CAAC,WAAW,EAAE;YAC3B,KAAK,QAAQ;gBACX,cAAc,GAAG;oBACf,CAAC,iDAA0B,CAAC,EAAE,YAAY;oBAC1C,CAAC,qDAA8B,CAAC,EAAE,KAAK;iBACxC,CAAC;gBACF,IAAI,OAAO,CAAC,MAAM,EAAE;oBAClB,cAAc,CAAC,mDAA4B,CAAC,GAAG,OAAO,CAAC,MAAM,CAA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,CAAC;YACnE,CAAC,CAAC,EAAE,CAAC;QAEP,MAAM,oBAAoB,GAAG;YAC3B,GAAG,mBAAmB;YACtB,MAAM,EAAE;gBACN,GAAG,mBAAmB,CAAC,MAAM;gBAC7B,GAAG,iBAAiB;aACrB;SACF,CAAC;QAEF,MAAM,oBAAoB,GAAG,MAAM,CAAC,IAAI,CACtC,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,CACrC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAErB,8EAA8E;QAC9E,0FAA0F;QAC1F,IAAI,oBAAoB,CAAC,MAAM,GAAG,IAAI,EAAE;YACtC,UAAI,CAAC,IAAI,CACP,6HAA6H,CAC9H,CAAC;YACF,OAAO,aAAa,CAAC;SACtB;QAED,OAAO,oBAAoB,CAAC;KAC7B;IAAC,OAAO,CAAC,EAAE;QACV,UAAI,CAAC,KAAK,CACR,4EAA4E,EAC5E,CAAC,CACF,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;AACH,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Span, SpanKind, Tracer, diag, Attributes } from '@opentelemetry/api';\nimport {\n SEMATTRS_FAAS_EXECUTION,\n SEMATTRS_FAAS_INVOKED_NAME,\n SEMATTRS_FAAS_INVOKED_PROVIDER,\n SEMATTRS_FAAS_INVOKED_REGION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\nimport { RequestMetadata, ServiceExtension } from './ServiceExtension';\nimport { context, propagation } from '@opentelemetry/api';\n\nclass LambdaCommands {\n public static readonly Invoke: string = 'Invoke';\n}\n\nexport class LambdaServiceExtension implements ServiceExtension {\n requestPreSpanHook(\n request: NormalizedRequest,\n _config: AwsSdkInstrumentationConfig\n ): RequestMetadata {\n const functionName = this.extractFunctionName(request.commandInput);\n\n let spanAttributes: Attributes = {};\n let spanName: string | undefined;\n\n switch (request.commandName) {\n case 'Invoke':\n spanAttributes = {\n [SEMATTRS_FAAS_INVOKED_NAME]: functionName,\n [SEMATTRS_FAAS_INVOKED_PROVIDER]: 'aws',\n };\n if (request.region) {\n spanAttributes[SEMATTRS_FAAS_INVOKED_REGION] = request.region;\n }\n spanName = `${functionName} ${LambdaCommands.Invoke}`;\n break;\n }\n return {\n isIncoming: false,\n spanAttributes,\n spanKind: SpanKind.CLIENT,\n spanName,\n };\n }\n\n requestPostSpanHook = (request: NormalizedRequest) => {\n switch (request.commandName) {\n case LambdaCommands.Invoke:\n {\n if (request.commandInput) {\n request.commandInput.ClientContext = injectLambdaPropagationContext(\n request.commandInput.ClientContext\n );\n }\n }\n break;\n }\n };\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig\n ) {\n switch (response.request.commandName) {\n case LambdaCommands.Invoke:\n {\n span.setAttribute(SEMATTRS_FAAS_EXECUTION, response.requestId);\n }\n break;\n }\n }\n\n extractFunctionName = (commandInput: Record<string, any>): string => {\n return commandInput?.FunctionName;\n };\n}\n\nconst injectLambdaPropagationContext = (\n clientContext: string | undefined\n): string | undefined => {\n try {\n const propagatedContext = {};\n propagation.inject(context.active(), propagatedContext);\n\n const parsedClientContext = clientContext\n ? JSON.parse(Buffer.from(clientContext, 'base64').toString('utf8'))\n : {};\n\n const updatedClientContext = {\n ...parsedClientContext,\n Custom: {\n ...parsedClientContext.Custom,\n ...propagatedContext,\n },\n };\n\n const encodedClientContext = Buffer.from(\n JSON.stringify(updatedClientContext)\n ).toString('base64');\n\n // The length of client context is capped at 3583 bytes of base64 encoded data\n // (https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestSyntax)\n if (encodedClientContext.length > 3583) {\n diag.warn(\n 'lambda instrumentation: cannot set context propagation on lambda invoke parameters due to ClientContext length limitations.'\n );\n return clientContext;\n }\n\n return encodedClientContext;\n } catch (e) {\n diag.debug(\n 'lambda instrumentation: failed to set context propagation on ClientContext',\n e\n );\n return clientContext;\n }\n};\n"]}
1
+ {"version":3,"file":"lambda.js","sourceRoot":"","sources":["../../../src/services/lambda.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAA8E;AAC9E,8EAK6C;AAO7C,4CAA0D;AAE1D,MAAM,cAAc;IACX,MAAM,CAAU,MAAM,GAAW,QAAQ,CAAC;;AAGnD,MAAa,sBAAsB;IACjC,kBAAkB,CAChB,OAA0B,EAC1B,OAAoC;QAEpC,MAAM,YAAY,GAAG,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAEpE,IAAI,cAAc,GAAe,EAAE,CAAC;QACpC,IAAI,QAA4B,CAAC;QAEjC,QAAQ,OAAO,CAAC,WAAW,EAAE;YAC3B,KAAK,QAAQ;gBACX,cAAc,GAAG;oBACf,CAAC,iDAA0B,CAAC,EAAE,YAAY;oBAC1C,CAAC,qDAA8B,CAAC,EAAE,KAAK;iBACxC,CAAC;gBACF,IAAI,OAAO,CAAC,MAAM,EAAE;oBAClB,cAAc,CAAC,mDAA4B,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;iBAC/D;gBACD,QAAQ,GAAG,GAAG,YAAY,IAAI,cAAc,CAAC,MAAM,EAAE,CAAC;gBACtD,MAAM;SACT;QACD,OAAO;YACL,UAAU,EAAE,KAAK;YACjB,cAAc;YACd,QAAQ,EAAE,cAAQ,CAAC,MAAM;YACzB,QAAQ;SACT,CAAC;IACJ,CAAC;IAED,mBAAmB,GAAG,CAAC,OAA0B,EAAE,EA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B,CAAC,CACrC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAErB,8EAA8E;QAC9E,0FAA0F;QAC1F,IAAI,oBAAoB,CAAC,MAAM,GAAG,IAAI,EAAE;YACtC,UAAI,CAAC,IAAI,CACP,6HAA6H,CAC9H,CAAC;YACF,OAAO,aAAa,CAAC;SACtB;QAED,OAAO,oBAAoB,CAAC;KAC7B;IAAC,OAAO,CAAC,EAAE;QACV,UAAI,CAAC,KAAK,CACR,4EAA4E,EAC5E,CAAC,CACF,CAAC;QACF,OAAO,aAAa,CAAC;KACtB;AACH,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Span, SpanKind, Tracer, diag, Attributes } from '@opentelemetry/api';\nimport {\n SEMATTRS_FAAS_EXECUTION,\n SEMATTRS_FAAS_INVOKED_NAME,\n SEMATTRS_FAAS_INVOKED_PROVIDER,\n SEMATTRS_FAAS_INVOKED_REGION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n AwsSdkInstrumentationConfig,\n NormalizedRequest,\n NormalizedResponse,\n} from '../types';\nimport { RequestMetadata, ServiceExtension } from './ServiceExtension';\nimport { context, propagation } from '@opentelemetry/api';\n\nclass LambdaCommands {\n public static readonly Invoke: string = 'Invoke';\n}\n\nexport class LambdaServiceExtension implements ServiceExtension {\n requestPreSpanHook(\n request: NormalizedRequest,\n _config: AwsSdkInstrumentationConfig\n ): RequestMetadata {\n const functionName = this.extractFunctionName(request.commandInput);\n\n let spanAttributes: Attributes = {};\n let spanName: string | undefined;\n\n switch (request.commandName) {\n case 'Invoke':\n spanAttributes = {\n [SEMATTRS_FAAS_INVOKED_NAME]: functionName,\n [SEMATTRS_FAAS_INVOKED_PROVIDER]: 'aws',\n };\n if (request.region) {\n spanAttributes[SEMATTRS_FAAS_INVOKED_REGION] = request.region;\n }\n spanName = `${functionName} ${LambdaCommands.Invoke}`;\n break;\n }\n return {\n isIncoming: false,\n spanAttributes,\n spanKind: SpanKind.CLIENT,\n spanName,\n };\n }\n\n requestPostSpanHook = (request: NormalizedRequest) => {\n switch (request.commandName) {\n case LambdaCommands.Invoke:\n {\n if (request.commandInput) {\n request.commandInput.ClientContext = injectLambdaPropagationContext(\n request.commandInput.ClientContext\n );\n }\n }\n break;\n }\n };\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig\n ) {\n switch (response.request.commandName) {\n case LambdaCommands.Invoke:\n {\n span.setAttribute(SEMATTRS_FAAS_EXECUTION, response.requestId);\n }\n break;\n }\n }\n\n extractFunctionName = (commandInput: Record<string, any>): string => {\n return commandInput?.FunctionName;\n };\n}\n\nconst injectLambdaPropagationContext = (\n clientContext: string | undefined\n): string | undefined => {\n try {\n const propagatedContext = {};\n propagation.inject(context.active(), propagatedContext);\n\n const parsedClientContext = clientContext\n ? JSON.parse(Buffer.from(clientContext, 'base64').toString('utf8'))\n : {};\n\n const updatedClientContext = {\n ...parsedClientContext,\n custom: {\n ...parsedClientContext.custom,\n ...propagatedContext,\n },\n };\n\n const encodedClientContext = Buffer.from(\n JSON.stringify(updatedClientContext)\n ).toString('base64');\n\n // The length of client context is capped at 3583 bytes of base64 encoded data\n // (https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestSyntax)\n if (encodedClientContext.length > 3583) {\n diag.warn(\n 'lambda instrumentation: cannot set context propagation on lambda invoke parameters due to ClientContext length limitations.'\n );\n return clientContext;\n }\n\n return encodedClientContext;\n } catch (e) {\n diag.debug(\n 'lambda instrumentation: failed to set context propagation on ClientContext',\n e\n );\n return clientContext;\n }\n};\n"]}
@@ -18,6 +18,7 @@ exports.SnsServiceExtension = void 0;
18
18
  */
19
19
  const api_1 = require("@opentelemetry/api");
20
20
  const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
21
+ const semconv_1 = require("../semconv");
21
22
  const MessageAttributes_1 = require("./MessageAttributes");
22
23
  class SnsServiceExtension {
23
24
  requestPreSpanHook(request, _config) {
@@ -40,6 +41,10 @@ class SnsServiceExtension {
40
41
  ? 'phone_number'
41
42
  : spanAttributes[semantic_conventions_1.SEMATTRS_MESSAGING_DESTINATION]} send`;
42
43
  }
44
+ const topicArn = request.commandInput?.TopicArn;
45
+ if (topicArn) {
46
+ spanAttributes[semconv_1.ATTR_AWS_SNS_TOPIC_ARN] = topicArn;
47
+ }
43
48
  return {
44
49
  isIncoming: false,
45
50
  spanAttributes,
@@ -55,7 +60,12 @@ class SnsServiceExtension {
55
60
  }
56
61
  }
57
62
  }
58
- responseHook(response, span, tracer, config) { }
63
+ responseHook(response, span, tracer, config) {
64
+ const topicArn = response.data?.TopicArn;
65
+ if (topicArn) {
66
+ span.setAttribute(semconv_1.ATTR_AWS_SNS_TOPIC_ARN, topicArn);
67
+ }
68
+ }
59
69
  extractDestinationName(topicArn, targetArn, phoneNumber) {
60
70
  if (topicArn || targetArn) {
61
71
  const arn = topicArn ?? targetArn;
@@ -1 +1 @@
1
- {"version":3,"file":"sns.js","sourceRoot":"","sources":["../../../src/services/sns.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAAwE;AACxE,8EAK6C;AAM7C,2DAA+D;AAG/D,MAAa,mBAAmB;IAC9B,kBAAkB,CAChB,OAA0B,EAC1B,OAAoC;QAEpC,IAAI,QAAQ,GAAa,cAAQ,CAAC,MAAM,CAAC;QACzC,IAAI,QAAQ,GAAG,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;QAC5C,MAAM,cAAc,GAAe;YACjC,CAAC,gDAAyB,CAAC,EAA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AS,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;aAChD;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,GAAG,CAAC;aACZ;SACF;aAAM,IAAI,WAAW,EAAE;YACtB,OAAO,WAAW,CAAC;SACpB;aAAM;YACL,OAAO,SAAS,CAAC;SAClB;IACH,CAAC;CACF;AA3ED,kDA2EC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Span, Tracer, SpanKind, Attributes } from '@opentelemetry/api';\nimport {\n MESSAGINGDESTINATIONKINDVALUES_TOPIC,\n SEMATTRS_MESSAGING_DESTINATION,\n SEMATTRS_MESSAGING_DESTINATION_KIND,\n SEMATTRS_MESSAGING_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\nimport {\n NormalizedRequest,\n NormalizedResponse,\n AwsSdkInstrumentationConfig,\n} from '../types';\nimport { injectPropagationContext } from './MessageAttributes';\nimport { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class SnsServiceExtension implements ServiceExtension {\n requestPreSpanHook(\n request: NormalizedRequest,\n _config: AwsSdkInstrumentationConfig\n ): RequestMetadata {\n let spanKind: SpanKind = SpanKind.CLIENT;\n let spanName = `SNS ${request.commandName}`;\n const spanAttributes: Attributes = {\n [SEMATTRS_MESSAGING_SYSTEM]: 'aws.sns',\n };\n\n if (request.commandName === 'Publish') {\n spanKind = SpanKind.PRODUCER;\n\n spanAttributes[SEMATTRS_MESSAGING_DESTINATION_KIND] =\n MESSAGINGDESTINATIONKINDVALUES_TOPIC;\n const { TopicArn, TargetArn, PhoneNumber } = request.commandInput;\n spanAttributes[SEMATTRS_MESSAGING_DESTINATION] =\n this.extractDestinationName(TopicArn, TargetArn, PhoneNumber);\n // ToDO: Use SEMATTRS_MESSAGING_DESTINATION_NAME when implemented\n spanAttributes['messaging.destination.name'] =\n TopicArn || TargetArn || PhoneNumber || 'unknown';\n\n spanName = `${\n PhoneNumber\n ? 'phone_number'\n : spanAttributes[SEMATTRS_MESSAGING_DESTINATION]\n } send`;\n }\n\n return {\n isIncoming: false,\n spanAttributes,\n spanKind,\n spanName,\n };\n }\n\n requestPostSpanHook(request: NormalizedRequest): void {\n if (request.commandName === 'Publish') {\n const origMessageAttributes =\n request.commandInput['MessageAttributes'] ?? {};\n if (origMessageAttributes) {\n request.commandInput['MessageAttributes'] = injectPropagationContext(\n origMessageAttributes\n );\n }\n }\n }\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig\n ): void {}\n\n extractDestinationName(\n topicArn: string,\n targetArn: string,\n phoneNumber: string\n ): string {\n if (topicArn || targetArn) {\n const arn = topicArn ?? targetArn;\n try {\n return arn.substring(arn.lastIndexOf(':') + 1);\n } catch (err) {\n return arn;\n }\n } else if (phoneNumber) {\n return phoneNumber;\n } else {\n return 'unknown';\n }\n }\n}\n"]}
1
+ {"version":3,"file":"sns.js","sourceRoot":"","sources":["../../../src/services/sns.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAAwE;AACxE,8EAK6C;AAC7C,wCAAoD;AAMpD,2DAA+D;AAG/D,MAAa,mBAAmB;IAC9B,kBAAkB,CAChB,OAA0B,EAC1B,OAAoC;QAEpC,IAAI,QAAQ,GAAa,cAAQ,CAAC,MAAM,CAAC;QACzC,IAAI,QAAQ,GAAG,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;QAC5C,MAAM,cAAc,GAAe;YACjC,CAAC,gDAAyB,CAAC,EAAE,SAAS;SACvC,C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QACzC,IAAI,QAAQ,EAAE;YACZ,IAAI,CAAC,YAAY,CAAC,gCAAsB,EAAE,QAAQ,CAAC,CAAC;SACrD;IACH,CAAC;IAED,sBAAsB,CACpB,QAAgB,EAChB,SAAiB,EACjB,WAAmB;QAEnB,IAAI,QAAQ,IAAI,SAAS,EAAE;YACzB,MAAM,GAAG,GAAG,QAAQ,IAAI,SAAS,CAAC;YAClC,IAAI;gBACF,OAAO,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;aAChD;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,GAAG,CAAC;aACZ;SACF;aAAM,IAAI,WAAW,EAAE;YACtB,OAAO,WAAW,CAAC;SACpB;aAAM;YACL,OAAO,SAAS,CAAC;SAClB;IACH,CAAC;CACF;AArFD,kDAqFC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Span, Tracer, SpanKind, Attributes } from '@opentelemetry/api';\nimport {\n MESSAGINGDESTINATIONKINDVALUES_TOPIC,\n SEMATTRS_MESSAGING_DESTINATION,\n SEMATTRS_MESSAGING_DESTINATION_KIND,\n SEMATTRS_MESSAGING_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_AWS_SNS_TOPIC_ARN } from '../semconv';\nimport {\n NormalizedRequest,\n NormalizedResponse,\n AwsSdkInstrumentationConfig,\n} from '../types';\nimport { injectPropagationContext } from './MessageAttributes';\nimport { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class SnsServiceExtension implements ServiceExtension {\n requestPreSpanHook(\n request: NormalizedRequest,\n _config: AwsSdkInstrumentationConfig\n ): RequestMetadata {\n let spanKind: SpanKind = SpanKind.CLIENT;\n let spanName = `SNS ${request.commandName}`;\n const spanAttributes: Attributes = {\n [SEMATTRS_MESSAGING_SYSTEM]: 'aws.sns',\n };\n\n if (request.commandName === 'Publish') {\n spanKind = SpanKind.PRODUCER;\n\n spanAttributes[SEMATTRS_MESSAGING_DESTINATION_KIND] =\n MESSAGINGDESTINATIONKINDVALUES_TOPIC;\n const { TopicArn, TargetArn, PhoneNumber } = request.commandInput;\n spanAttributes[SEMATTRS_MESSAGING_DESTINATION] =\n this.extractDestinationName(TopicArn, TargetArn, PhoneNumber);\n // ToDO: Use SEMATTRS_MESSAGING_DESTINATION_NAME when implemented\n spanAttributes['messaging.destination.name'] =\n TopicArn || TargetArn || PhoneNumber || 'unknown';\n\n spanName = `${\n PhoneNumber\n ? 'phone_number'\n : spanAttributes[SEMATTRS_MESSAGING_DESTINATION]\n } send`;\n }\n\n const topicArn = request.commandInput?.TopicArn;\n if (topicArn) {\n spanAttributes[ATTR_AWS_SNS_TOPIC_ARN] = topicArn;\n }\n\n return {\n isIncoming: false,\n spanAttributes,\n spanKind,\n spanName,\n };\n }\n\n requestPostSpanHook(request: NormalizedRequest): void {\n if (request.commandName === 'Publish') {\n const origMessageAttributes =\n request.commandInput['MessageAttributes'] ?? {};\n if (origMessageAttributes) {\n request.commandInput['MessageAttributes'] = injectPropagationContext(\n origMessageAttributes\n );\n }\n }\n }\n\n responseHook(\n response: NormalizedResponse,\n span: Span,\n tracer: Tracer,\n config: AwsSdkInstrumentationConfig\n ): void {\n const topicArn = response.data?.TopicArn;\n if (topicArn) {\n span.setAttribute(ATTR_AWS_SNS_TOPIC_ARN, topicArn);\n }\n }\n\n extractDestinationName(\n topicArn: string,\n targetArn: string,\n phoneNumber: string\n ): string {\n if (topicArn || targetArn) {\n const arn = topicArn ?? targetArn;\n try {\n return arn.substring(arn.lastIndexOf(':') + 1);\n } catch (err) {\n return arn;\n }\n } else if (phoneNumber) {\n return phoneNumber;\n } else {\n return 'unknown';\n }\n }\n}\n"]}
@@ -40,7 +40,7 @@ const extractAttributesFromNormalizedRequest = (normalizedRequest) => {
40
40
  [semantic_conventions_1.SEMATTRS_RPC_SYSTEM]: 'aws-api',
41
41
  [semantic_conventions_1.SEMATTRS_RPC_METHOD]: normalizedRequest.commandName,
42
42
  [semantic_conventions_1.SEMATTRS_RPC_SERVICE]: normalizedRequest.serviceName,
43
- [enums_1.AttributeNames.AWS_REGION]: normalizedRequest.region,
43
+ [enums_1.AttributeNames.CLOUD_REGION]: normalizedRequest.region,
44
44
  };
45
45
  };
46
46
  exports.extractAttributesFromNormalizedRequest = extractAttributesFromNormalizedRequest;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAAkE;AAClE,8EAI6C;AAC7C,mCAAyC;AAGlC,MAAM,8BAA8B,GAAG,CAC5C,GAAW,EACX,cAAsB,EACd,EAAE;IACV,MAAM,YAAY,GAAG,cAAc,CAAC,MAAM,CAAC;IAC3C,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC,YAAY,CAAC,KAAK,cAAc;QACjD,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,GAAG,YAAY,CAAC;QACzC,CAAC,CAAC,GAAG,CAAC;AACV,CAAC,CAAC;AARW,QAAA,8BAA8B,kCAQzC;AAEK,MAAM,kBAAkB,GAAG,CAChC,WAAmB,EACnB,qBAA6B,EAC7B,YAAiC,EACjC,MAA0B,EACP,EAAE;IACrB,OAAO;QACL,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QAC7C,WAAW,EAAE,IAAA,sCAA8B,EACzC,qBAAqB,EACrB,SAAS,CACV;QACD,YAAY;QACZ,MAAM;KACP,CAAC;AACJ,CAAC,CAAC;AAfW,QAAA,kBAAkB,sBAe7B;AAEK,MAAM,sCAAsC,GAAG,CACpD,iBAAoC,EACxB,EAAE;IACd,OAAO;QACL,CAAC,0CAAmB,CAAC,EAAE,SAAS;QAChC,CAAC,0CAAmB,CAAC,EAAE,iBAAiB,CAAC,WAAW;QACpD,CAAC,2CAAoB,CAAC,EAAE,iBAAiB,CAAC,WAAW;QACrD,CAAC,sBAAc,CAAC,UAAU,CAAC,EAAE,iBAAiB,CAAC,MAAM;KACtD,CAAC;AACJ,CAAC,CAAC;AATW,QAAA,sCAAsC,0CASjD;AAEK,MAAM,WAAW,GAAG,CACzB,MAAkB,EAClB,mBAA4B,EAC5B,WAAW,GAAG,CAAC,EACH,EAAE;IACd,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC;IAE7B,MAAM,CAAC,IAAI,GAAG,UACZ,WAAqC,EACrC,UAAoC;QAEpC,MAAM,cAAc,GAAG,aAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,CAAC,CAAC;QACtE,MAAM,aAAa,GAAG,aAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;QACpE,MAAM,cAAc,GAAG,QAAQ,CAAC,IAAI,CAIlC,IAAI,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC;QACvC,OAAO,WAAW,GAAG,CAAC;YACpB,CAAC,CAAC,IAAA,mBAAW,EAAC,cAAc,EAAE,mBAAmB,EAAE,WAAW,GAAG,CAAC,CAAC;YACnE,CAAC,CAAC,cAAc,CAAC;IACrB,CAAC,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAvBW,QAAA,WAAW,eAuBtB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Attributes, Context, context } from '@opentelemetry/api';\nimport {\n SEMATTRS_RPC_METHOD,\n SEMATTRS_RPC_SERVICE,\n SEMATTRS_RPC_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\nimport { AttributeNames } from './enums';\nimport { NormalizedRequest } from './types';\n\nexport const removeSuffixFromStringIfExists = (\n str: string,\n suffixToRemove: string\n): string => {\n const suffixLength = suffixToRemove.length;\n return str?.slice(-suffixLength) === suffixToRemove\n ? str.slice(0, str.length - suffixLength)\n : str;\n};\n\nexport const normalizeV3Request = (\n serviceName: string,\n commandNameWithSuffix: string,\n commandInput: Record<string, any>,\n region: string | undefined\n): NormalizedRequest => {\n return {\n serviceName: serviceName?.replace(/\\s+/g, ''),\n commandName: removeSuffixFromStringIfExists(\n commandNameWithSuffix,\n 'Command'\n ),\n commandInput,\n region,\n };\n};\n\nexport const extractAttributesFromNormalizedRequest = (\n normalizedRequest: NormalizedRequest\n): Attributes => {\n return {\n [SEMATTRS_RPC_SYSTEM]: 'aws-api',\n [SEMATTRS_RPC_METHOD]: normalizedRequest.commandName,\n [SEMATTRS_RPC_SERVICE]: normalizedRequest.serviceName,\n [AttributeNames.AWS_REGION]: normalizedRequest.region,\n };\n};\n\nexport const bindPromise = <T = unknown>(\n target: Promise<T>,\n contextForCallbacks: Context,\n rebindCount = 1\n): Promise<T> => {\n const origThen = target.then;\n type PromiseThenParameters = Parameters<Promise<T>['then']>;\n target.then = function <TResult1 = T, TResult2 = never>(\n onFulfilled: PromiseThenParameters[0],\n onRejected: PromiseThenParameters[1]\n ): Promise<TResult1 | TResult2> {\n const newOnFulfilled = context.bind(contextForCallbacks, onFulfilled);\n const newOnRejected = context.bind(contextForCallbacks, onRejected);\n const patchedPromise = origThen.call<\n Promise<T>,\n any[],\n Promise<TResult1 | TResult2>\n >(this, newOnFulfilled, newOnRejected);\n return rebindCount > 1\n ? bindPromise(patchedPromise, contextForCallbacks, rebindCount - 1)\n : patchedPromise;\n };\n return target;\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAAkE;AAClE,8EAI6C;AAC7C,mCAAyC;AAGlC,MAAM,8BAA8B,GAAG,CAC5C,GAAW,EACX,cAAsB,EACd,EAAE;IACV,MAAM,YAAY,GAAG,cAAc,CAAC,MAAM,CAAC;IAC3C,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC,YAAY,CAAC,KAAK,cAAc;QACjD,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,GAAG,YAAY,CAAC;QACzC,CAAC,CAAC,GAAG,CAAC;AACV,CAAC,CAAC;AARW,QAAA,8BAA8B,kCAQzC;AAEK,MAAM,kBAAkB,GAAG,CAChC,WAAmB,EACnB,qBAA6B,EAC7B,YAAiC,EACjC,MAA0B,EACP,EAAE;IACrB,OAAO;QACL,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QAC7C,WAAW,EAAE,IAAA,sCAA8B,EACzC,qBAAqB,EACrB,SAAS,CACV;QACD,YAAY;QACZ,MAAM;KACP,CAAC;AACJ,CAAC,CAAC;AAfW,QAAA,kBAAkB,sBAe7B;AAEK,MAAM,sCAAsC,GAAG,CACpD,iBAAoC,EACxB,EAAE;IACd,OAAO;QACL,CAAC,0CAAmB,CAAC,EAAE,SAAS;QAChC,CAAC,0CAAmB,CAAC,EAAE,iBAAiB,CAAC,WAAW;QACpD,CAAC,2CAAoB,CAAC,EAAE,iBAAiB,CAAC,WAAW;QACrD,CAAC,sBAAc,CAAC,YAAY,CAAC,EAAE,iBAAiB,CAAC,MAAM;KACxD,CAAC;AACJ,CAAC,CAAC;AATW,QAAA,sCAAsC,0CASjD;AAEK,MAAM,WAAW,GAAG,CACzB,MAAkB,EAClB,mBAA4B,EAC5B,WAAW,GAAG,CAAC,EACH,EAAE;IACd,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC;IAE7B,MAAM,CAAC,IAAI,GAAG,UACZ,WAAqC,EACrC,UAAoC;QAEpC,MAAM,cAAc,GAAG,aAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,CAAC,CAAC;QACtE,MAAM,aAAa,GAAG,aAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;QACpE,MAAM,cAAc,GAAG,QAAQ,CAAC,IAAI,CAIlC,IAAI,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC;QACvC,OAAO,WAAW,GAAG,CAAC;YACpB,CAAC,CAAC,IAAA,mBAAW,EAAC,cAAc,EAAE,mBAAmB,EAAE,WAAW,GAAG,CAAC,CAAC;YACnE,CAAC,CAAC,cAAc,CAAC;IACrB,CAAC,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAvBW,QAAA,WAAW,eAuBtB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Attributes, Context, context } from '@opentelemetry/api';\nimport {\n SEMATTRS_RPC_METHOD,\n SEMATTRS_RPC_SERVICE,\n SEMATTRS_RPC_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\nimport { AttributeNames } from './enums';\nimport { NormalizedRequest } from './types';\n\nexport const removeSuffixFromStringIfExists = (\n str: string,\n suffixToRemove: string\n): string => {\n const suffixLength = suffixToRemove.length;\n return str?.slice(-suffixLength) === suffixToRemove\n ? str.slice(0, str.length - suffixLength)\n : str;\n};\n\nexport const normalizeV3Request = (\n serviceName: string,\n commandNameWithSuffix: string,\n commandInput: Record<string, any>,\n region: string | undefined\n): NormalizedRequest => {\n return {\n serviceName: serviceName?.replace(/\\s+/g, ''),\n commandName: removeSuffixFromStringIfExists(\n commandNameWithSuffix,\n 'Command'\n ),\n commandInput,\n region,\n };\n};\n\nexport const extractAttributesFromNormalizedRequest = (\n normalizedRequest: NormalizedRequest\n): Attributes => {\n return {\n [SEMATTRS_RPC_SYSTEM]: 'aws-api',\n [SEMATTRS_RPC_METHOD]: normalizedRequest.commandName,\n [SEMATTRS_RPC_SERVICE]: normalizedRequest.serviceName,\n [AttributeNames.CLOUD_REGION]: normalizedRequest.region,\n };\n};\n\nexport const bindPromise = <T = unknown>(\n target: Promise<T>,\n contextForCallbacks: Context,\n rebindCount = 1\n): Promise<T> => {\n const origThen = target.then;\n type PromiseThenParameters = Parameters<Promise<T>['then']>;\n target.then = function <TResult1 = T, TResult2 = never>(\n onFulfilled: PromiseThenParameters[0],\n onRejected: PromiseThenParameters[1]\n ): Promise<TResult1 | TResult2> {\n const newOnFulfilled = context.bind(contextForCallbacks, onFulfilled);\n const newOnRejected = context.bind(contextForCallbacks, onRejected);\n const patchedPromise = origThen.call<\n Promise<T>,\n any[],\n Promise<TResult1 | TResult2>\n >(this, newOnFulfilled, newOnRejected);\n return rebindCount > 1\n ? bindPromise(patchedPromise, contextForCallbacks, rebindCount - 1)\n : patchedPromise;\n };\n return target;\n};\n"]}
@@ -1,3 +1,3 @@
1
- export declare const PACKAGE_VERSION = "0.53.0";
1
+ export declare const PACKAGE_VERSION = "0.55.0";
2
2
  export declare const PACKAGE_NAME = "@opentelemetry/instrumentation-aws-sdk";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -17,6 +17,6 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.PACKAGE_NAME = exports.PACKAGE_VERSION = void 0;
19
19
  // this is autogenerated file, see scripts/version-update.js
20
- exports.PACKAGE_VERSION = '0.53.0';
20
+ exports.PACKAGE_VERSION = '0.55.0';
21
21
  exports.PACKAGE_NAME = '@opentelemetry/instrumentation-aws-sdk';
22
22
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,eAAe,GAAG,QAAQ,CAAC;AAC3B,QAAA,YAAY,GAAG,wCAAwC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.53.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-aws-sdk';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,eAAe,GAAG,QAAQ,CAAC;AAC3B,QAAA,YAAY,GAAG,wCAAwC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.55.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-aws-sdk';\n"]}
package/doc/lambda.md CHANGED
@@ -9,4 +9,4 @@ The following methods are automatically enhanced:
9
9
  ### Invoke
10
10
 
11
11
  - Attributes are added by this instrumentation according to the [spec for Outgoing Invocations of a FaaS from a client](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/faas.md#outgoing-invocations) .
12
- - OpenTelemetry trace context is injected into the `ClientContext` parameter, allowing functions to extract this using the `Custom` property within the function.
12
+ - OpenTelemetry trace context is injected into the `ClientContext` parameter, allowing functions to extract this using the `custom` property within the function.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/instrumentation-aws-sdk",
3
- "version": "0.53.0",
3
+ "version": "0.55.0",
4
4
  "description": "OpenTelemetry instrumentation for `aws-sdk` and `@aws-sdk/client-*` clients for various AWS services",
5
5
  "keywords": [
6
6
  "aws",
@@ -28,11 +28,11 @@
28
28
  "repository": "open-telemetry/opentelemetry-js-contrib",
29
29
  "scripts": {
30
30
  "clean": "rimraf build/*",
31
+ "setup:dev": "nx run-many -t compile -p @opentelemetry/instrumentation-aws-sdk",
31
32
  "compile": "tsc -p .",
32
33
  "lint": "eslint . --ext .ts",
33
34
  "lint:fix": "eslint . --ext .ts --fix",
34
35
  "lint:readme": "node ../../../scripts/lint-readme.js",
35
- "prewatch": "npm run precompile",
36
36
  "prepublishOnly": "npm run compile",
37
37
  "tdd": "npm run test -- --watch-extensions ts --watch",
38
38
  "test": "nyc mocha --require '@opentelemetry/contrib-test-utils' 'test/**/*.test.ts'",
@@ -45,9 +45,9 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@opentelemetry/core": "^2.0.0",
48
- "@opentelemetry/instrumentation": "^0.201.0",
49
- "@opentelemetry/propagation-utils": "^0.31.1",
50
- "@opentelemetry/semantic-conventions": "^1.31.0"
48
+ "@opentelemetry/instrumentation": "^0.202.0",
49
+ "@opentelemetry/propagation-utils": "^0.31.2",
50
+ "@opentelemetry/semantic-conventions": "^1.34.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@aws-sdk/client-bedrock-runtime": "^3.587.0",
@@ -59,7 +59,7 @@
59
59
  "@aws-sdk/client-sqs": "^3.85.0",
60
60
  "@aws-sdk/types": "^3.370.0",
61
61
  "@opentelemetry/api": "^1.3.0",
62
- "@opentelemetry/contrib-test-utils": "^0.47.0",
62
+ "@opentelemetry/contrib-test-utils": "^0.48.0",
63
63
  "@opentelemetry/sdk-trace-base": "^2.0.0",
64
64
  "@smithy/node-http-handler": "2.4.0",
65
65
  "@types/mocha": "10.0.10",
@@ -77,5 +77,5 @@
77
77
  "engines": {
78
78
  "node": "^18.19.0 || >=20.6.0"
79
79
  },
80
- "gitHead": "393b51596dc869983a03ce8857658029ca122a15"
80
+ "gitHead": "52dd28deae0ebfbec43bdaed82f4749fc9803797"
81
81
  }