1+ import { InvokeStore } from '@aws/lambda-invoke-store' ;
12import {
23 POWERTOOLS_DEV_ENV_VAR ,
34 POWERTOOLS_SERVICE_NAME_ENV_VAR ,
@@ -249,15 +250,19 @@ const getServiceName = (): string => {
249250} ;
250251
251252/**
252- * Get the AWS X-Ray Trace data from the environment variable.
253+ * Get the AWS X-Ray Trace data from the lambda RIC async context or the `_X_AMZN_TRACE_ID` environment variable.
253254 *
254- * The method parses the environment variable `_X_AMZN_TRACE_ID` and returns an object with the key-value pairs.
255+ * Checks the async context first and if that returns undefined, falls back to the environment variable
256+ *
257+ * The method parses the value and returns an object with the key-value pairs.
255258 */
256259const getXrayTraceDataFromEnv = ( ) : Record < string , string > | undefined => {
257- const xRayTraceEnv = getStringFromEnv ( {
258- key : XRAY_TRACE_ID_ENV_VAR ,
259- defaultValue : '' ,
260- } ) ;
260+ const xRayTraceEnv =
261+ InvokeStore . getXRayTraceId ( ) ??
262+ getStringFromEnv ( {
263+ key : XRAY_TRACE_ID_ENV_VAR ,
264+ defaultValue : '' ,
265+ } ) ;
261266 if ( xRayTraceEnv === '' ) {
262267 return undefined ;
263268 }
@@ -280,18 +285,22 @@ const getXrayTraceDataFromEnv = (): Record<string, string> | undefined => {
280285/**
281286 * Determine if the current invocation is part of a sampled X-Ray trace.
282287 *
283- * The AWS X-Ray Trace data available in the environment variable has this format:
288+ * The AWS X-Ray Trace data is available in either the RIC async context or the `_X_AMZN_TRACE_ID` environment variable has this format:
284289 * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
290+ *
291+ * Checks the async context first and if that returns undefined, falls back to the environment variable
285292 */
286293const isRequestXRaySampled = ( ) : boolean => {
287294 const xRayTraceData = getXrayTraceDataFromEnv ( ) ;
288295 return xRayTraceData ?. Sampled === '1' ;
289296} ;
290297
291298/**
292- * Get the value of the `_X_AMZN_TRACE_ID` environment variable.
299+ * AWS X-Ray Trace id from the lambda RIC async context or the `_X_AMZN_TRACE_ID` environment variable.
300+ *
301+ * Checks the async context first and if that returns undefined, falls back to the environment variable
293302 *
294- * The AWS X-Ray Trace data available in the environment variable has this format:
303+ * The AWS X-Ray Trace data has this format:
295304 * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
296305 *
297306 * The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`.
0 commit comments