Skip to content

Commit

Permalink
feat(all): moved EnvService to commons + exposed getXrayTraceId in tr…
Browse files Browse the repository at this point in the history
…acer (#1123)

* feat: moved EnvService to commons + exposed getXrayTraceId in tracer

* docs: added docs section for getRootXrayTraceId

* Update docs/core/tracer.md

Co-authored-by: Josh Kellendonk <misterjoshua@users.noreply.github.com>

* fix: remove reduntant methods

* chore: updated unit test case

Co-authored-by: Josh Kellendonk <misterjoshua@users.noreply.github.com>
  • Loading branch information
dreamorosi and misterjoshua authored Oct 27, 2022
1 parent 6dc2bef commit c8e3c15
Show file tree
Hide file tree
Showing 25 changed files with 332 additions and 342 deletions.
32 changes: 32 additions & 0 deletions docs/core/tracer.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,38 @@ Use **`POWERTOOLS_TRACER_CAPTURE_ERROR=false`** environment variable to instruct

1. You might **return sensitive** information from errors, stack traces you might not control

### Access AWS X-Ray Root Trace ID

Tracer exposes a `getRootXrayTraceId()` method that allows you to retrieve the [AWS X-Ray Root Trace ID](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces) corresponds to the current function execution.

!!! info "This is commonly useful in two scenarios"

1. By including the root trace id in your response, consumers can use it to correlate requests
2. You might want to surface the root trace id to your end users so that they can reference it while contacting customer service

=== "index.ts"

```typescript hl_lines="9"
import { Tracer } from '@aws-lambda-powertools/tracer';

const tracer = new Tracer({ serviceName: 'serverlessAirline' });

export const handler = async (event: unknown, context: Context): Promise<void> => {
try {
...
} catch (err) {
const rootTraceId = tracer.getRootXrayTraceId();

// Example of returning an error response
return {
statusCode: 500,
body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`,
headers: { "_X_AMZN_TRACE_ID": rootTraceId },
};
}
};
```

### Escape hatch mechanism

You can use `tracer.provider` attribute to access all methods provided by the [AWS X-Ray SDK](https://docs.aws.amazon.com/xray-sdk-for-nodejs/latest/reference/AWSXRay.html).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Object {
"S3Bucket": Object {
"Fn::Sub": "cdk-hnb659fds-assets-\${AWS::AccountId}-\${AWS::Region}",
},
"S3Key": "c2f621503b147cecccf2e6cc6df420a8f11ee29ae042d2c1f523cf5db3f47ca2.zip",
"S3Key": "dbdb3f66eaeed03649521bf73dbcdd95a713086afccbac3f57fa407ffb76bdaa.zip",
},
"Description": "Lambda Powertools for TypeScript version 1.0.1",
"LayerName": "AWSLambdaPowertoolsTypeScript",
Expand Down
31 changes: 31 additions & 0 deletions packages/commons/src/config/ConfigService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Abstract class ConfigService
*
* This class defines common methods and variables that can be set by the developer
* in the runtime.
*
* @class
* @abstract
*/
abstract class ConfigService {

/**
* It returns the value of an environment variable that has given name.
*
* @param {string} name
* @returns {string}
*/
public abstract get(name: string): string;

/**
* It returns the value of the POWERTOOLS_SERVICE_NAME environment variable.
*
* @returns {string}
*/
public abstract getServiceName(): string;

}

export {
ConfigService,
};
67 changes: 67 additions & 0 deletions packages/commons/src/config/EnvironmentVariablesService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { ConfigService } from '.';

/**
* Class EnvironmentVariablesService
*
* This class is used to return environment variables that are available in the runtime of
* the current Lambda invocation.
* These variables can be a mix of runtime environment variables set by AWS and
* variables that can be set by the developer additionally.
*
* @class
* @extends {ConfigService}
* @see https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
* @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables
*/
class EnvironmentVariablesService extends ConfigService {

/**
* @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables
* @protected
*/
protected serviceNameVariable = 'POWERTOOLS_SERVICE_NAME';
// Reserved environment variables
private xRayTraceIdVariable = '_X_AMZN_TRACE_ID';

/**
* It returns the value of an environment variable that has given name.
*
* @param {string} name
* @returns {string}
*/
public get(name: string): string {
return process.env[name]?.trim() || '';
}

/**
* It returns the value of the POWERTOOLS_SERVICE_NAME environment variable.
*
* @returns {string}
*/
public getServiceName(): string {
return this.get(this.serviceNameVariable);
}

/**
* It returns the value of the _X_AMZN_TRACE_ID environment variable.
*
* The AWS X-Ray Trace data available in the environment variable has this format:
* `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
*
* The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`.
*
* @returns {string}
*/
public getXrayTraceId(): string | undefined {
const xRayTraceId = this.get(this.xRayTraceIdVariable);

if (xRayTraceId === '') return undefined;

return xRayTraceId.split(';')[0].replace('Root=', '');
}

}

export {
EnvironmentVariablesService,
};
2 changes: 2 additions & 0 deletions packages/commons/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './ConfigService';
export * from './EnvironmentVariablesService';
1 change: 1 addition & 0 deletions packages/commons/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './utils/lambda';
export * from './Utility';
export * from './config';
export * as ContextExamples from './samples/resources/contexts';
export * as Events from './samples/resources/events';
113 changes: 113 additions & 0 deletions packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* Test EnvironmentVariablesService class
*
* @group unit/commons/all
*/

import { EnvironmentVariablesService } from '../../../src/config';

describe('Class: EnvironmentVariablesService', () => {

const ENVIRONMENT_VARIABLES = process.env;

beforeEach(() => {
jest.resetModules();
process.env = { ...ENVIRONMENT_VARIABLES };
});

afterAll(() => {
process.env = ENVIRONMENT_VARIABLES;
});

describe('Method: get', () => {

test('When the variable IS present, it returns the value of a runtime variable', () => {

// Prepare
process.env.CUSTOM_VARIABLE = 'my custom value';
const service = new EnvironmentVariablesService();

// Act
const value = service.get('CUSTOM_VARIABLE');

// Assess
expect(value).toEqual('my custom value');

});

test('When the variable IS NOT present, it returns an empty string', () => {

// Prepare
delete process.env.CUSTOM_VARIABLE;
const service = new EnvironmentVariablesService();

// Act
const value = service.get('CUSTOM_VARIABLE');

// Assess
expect(value).toEqual('');

});

});

describe('Method: getServiceName', () => {

test('It returns the value of the environment variable POWERTOOLS_SERVICE_NAME', () => {

// Prepare
process.env.POWERTOOLS_SERVICE_NAME = 'shopping-cart-api';
const service = new EnvironmentVariablesService();

// Act
const value = service.getServiceName();

// Assess
expect(value).toEqual('shopping-cart-api');
});

});

describe('Method: getXrayTraceId', () => {

test('It returns the value of the environment variable _X_AMZN_TRACE_ID', () => {

// Prepare
process.env._X_AMZN_TRACE_ID = 'abcd123456789';
const service = new EnvironmentVariablesService();

// Act
const value = service.getXrayTraceId();

// Assess
expect(value).toEqual('abcd123456789');
});
test('It returns the value of the Root X-Ray segment ID properly formatted', () => {

// Prepare
process.env._X_AMZN_TRACE_ID = 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1';
const service = new EnvironmentVariablesService();

// Act
const value = service.getXrayTraceId();

// Assess
expect(value).toEqual('1-5759e988-bd862e3fe1be46a994272793');
});

test('It returns the value of the Root X-Ray segment ID properly formatted', () => {

// Prepare
delete process.env._X_AMZN_TRACE_ID;
const service = new EnvironmentVariablesService();

// Act
const value = service.getXrayTraceId();

// Assess
expect(value).toEqual(undefined);
});

});

});
22 changes: 3 additions & 19 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ class Logger extends Utility implements ClassThatLogs {

private static readonly defaultServiceName: string = 'service_undefined';

private envVarsService?: EnvironmentVariablesService;
// envVarsService is always initialized in the constructor in setOptions()
private envVarsService!: EnvironmentVariablesService;

private logEvent: boolean = false;

Expand Down Expand Up @@ -455,7 +456,7 @@ class Logger extends Utility implements ClassThatLogs {
logLevel,
timestamp: new Date(),
message: typeof input === 'string' ? input : input.message,
xRayTraceId: this.getXrayTraceId(),
xRayTraceId: this.envVarsService.getXrayTraceId(),
}, this.getPowertoolLogData());

const logItem = new LogItem({
Expand Down Expand Up @@ -545,23 +546,6 @@ class Logger extends Utility implements ClassThatLogs {
return <number> this.powertoolLogData.sampleRateValue;
}

/**
* It returns the current X-Ray Trace ID parsing the content of the `_X_AMZN_TRACE_ID` env variable.
*
* The X-Ray Trace data available in the environment variable has this format:
* `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
*
* The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`.
*
* @private
* @returns {string}
*/
private getXrayTraceId(): string {
const xRayTraceId = this.getEnvVarsService().getXrayTraceId();

return xRayTraceId.length > 0 ? xRayTraceId.split(';')[0].replace('Root=', '') : xRayTraceId;
}

/**
* It returns true if the provided log level is valid.
*
Expand Down
Loading

0 comments on commit c8e3c15

Please sign in to comment.