Skip to content

chore(maintenance): add powertools to user-agent in SDK clients #1567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/commons/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"test:unit": "jest --group=unit --detectOpenHandles --coverage --verbose",
"test:e2e": "echo 'Not Applicable'",
"watch": "jest --watch",
"generateVersionFile": "echo \"// this file is auto generated, do not modify\nmodule.exports = { version: '$(jq -r '.version' package.json)' };\" > src/version.ts",
"build": "tsc",
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint-fix": "eslint --fix --ext .ts,.js --no-error-on-unmatched-pattern .",
Expand Down
1 change: 1 addition & 0 deletions packages/commons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * as ContextExamples from './samples/resources/contexts';
export * as Events from './samples/resources/events';
export * from './types/middy';
export * from './types/utils';
export * from './middleware';
1 change: 1 addition & 0 deletions packages/commons/src/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './cleanupMiddlewares';
export * from './constants';
export * from './userAgentMiddleware';
38 changes: 38 additions & 0 deletions packages/commons/src/middleware/userAgentMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
/**
* @internal
*/
import { version as PT_VERSION } from '../version';

const EXEC_ENV = process.env.AWS_EXECUTION_ENV || 'NA';
const middlewareOptions = {
step: 'finalizeRequest',
name: 'addPowertoolsToUserAgent',
tags: ['POWERTOOLS', 'USER_AGENT'],
};

/**
* @internal
* returns a middleware function for the MiddlewareStack, that can be used for the SDK clients
* @param feature
*/
const customUserAgentMiddleware = (feature: string) => {
return (next, _context) => async (args) => {
const powertoolsUserAgent = `PT/${feature}/${PT_VERSION} PTEnv/${EXEC_ENV}`;
args.request.headers[
'user-agent'
] = `${args.request.headers['user-agent']} ${powertoolsUserAgent}`;

return await next(args);
};
};

const addUserAgentMiddleware = (client, feature): void => {
client.middlewareStack.add(
customUserAgentMiddleware(feature),
middlewareOptions
);
};

export { addUserAgentMiddleware };
2 changes: 2 additions & 0 deletions packages/commons/src/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// this file is auto generated, do not modify
module.exports = { version: '1.10.0' };
56 changes: 56 additions & 0 deletions packages/commons/tests/unit/userAgentMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { addUserAgentMiddleware } from '../../src/middleware/userAgentMiddleware';
import { InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda';

/**
* Logs request headers
*
* This is a middleware we use to test
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const logHeadersMiddleware = (next, _context) => async (args) => {
console.log(args.request.headers);

return await next(args);
};

describe('Function: addUserAgentMiddleware', () => {
it('adds powertools user agent to request header at the end', async () => {
const lambdaClient = new LambdaClient({
logger: console,
region: 'us-east-1',
endpoint: 'http://localhost:9001',
});

// Set a spy on the console.log method, so we can check the headers
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();

addUserAgentMiddleware(lambdaClient, 'my-feature');

expect(lambdaClient.middlewareStack.identify()).toContain(
'addPowertoolsToUserAgent: POWERTOOLS,USER_AGENT'
);

lambdaClient.middlewareStack.addRelativeTo(logHeadersMiddleware, {
relation: 'after',
toMiddleware: 'addPowertoolsToUserAgent',
name: 'logHeadersMiddleware',
tags: ['TEST'],
});

await expect(() =>
lambdaClient.send(
new InvokeCommand({
FunctionName: 'test',
Payload: new TextEncoder().encode(JSON.stringify('foo')),
})
)
).rejects.toThrow();

expect(consoleSpy).toHaveBeenCalledWith(
expect.objectContaining({
'user-agent': expect.stringContaining('PT/my-feature/1.10.0 PTEnv/NA'),
})
);
});
});
35 changes: 10 additions & 25 deletions packages/idempotency/src/persistence/DynamoDBPersistenceLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import {
IdempotencyItemAlreadyExistsError,
IdempotencyItemNotFoundError,
} from '../errors';
import { IdempotencyRecordStatus } from '../types';
import type { DynamoPersistenceOptions } from '../types';
import { IdempotencyRecordStatus } from '../types';
import {
AttributeValue,
DeleteItemCommand,
DynamoDBClient,
DynamoDBClientConfig,
DynamoDBServiceException,
DeleteItemCommand,
GetItemCommand,
PutItemCommand,
UpdateItemCommand,
AttributeValue,
} from '@aws-sdk/client-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
import { IdempotencyRecord } from './IdempotencyRecord';
Expand All @@ -28,7 +28,7 @@ import { BasePersistenceLayer } from './BasePersistenceLayer';
* @implements {BasePersistenceLayer}
*/
class DynamoDBPersistenceLayer extends BasePersistenceLayer {
private client?: DynamoDBClient;
private client!: DynamoDBClient;
private clientConfig: DynamoDBClientConfig = {};
private dataAttr: string;
private expiryAttr: string;
Expand Down Expand Up @@ -64,18 +64,16 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
if (config?.awsSdkV3Client instanceof DynamoDBClient) {
this.client = config.awsSdkV3Client;
} else {
console.warn(
'Invalid AWS SDK V3 client passed to DynamoDBPersistenceLayer. Using default client.'
);
throw Error('Not valid DynamoDBClient provided.');
}
} else {
this.clientConfig = config?.clientConfig ?? {};
this.client = new DynamoDBClient(this.clientConfig);
}
}

protected async _deleteRecord(record: IdempotencyRecord): Promise<void> {
const client = this.getClient();
await client.send(
await this.client.send(
new DeleteItemCommand({
TableName: this.tableName,
Key: this.getKey(record.idempotencyKey),
Expand All @@ -86,8 +84,7 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
protected async _getRecord(
idempotencyKey: string
): Promise<IdempotencyRecord> {
const client = this.getClient();
const result = await client.send(
const result = await this.client.send(
new GetItemCommand({
TableName: this.tableName,
Key: this.getKey(idempotencyKey),
Expand All @@ -111,8 +108,6 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
}

protected async _putRecord(record: IdempotencyRecord): Promise<void> {
const client = this.getClient();

const item = {
...this.getKey(record.idempotencyKey),
...marshall({
Expand Down Expand Up @@ -163,7 +158,7 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
].join(' OR ');

const now = Date.now();
await client.send(
await this.client.send(
new PutItemCommand({
TableName: this.tableName,
Item: item,
Expand Down Expand Up @@ -195,8 +190,6 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
}

protected async _updateRecord(record: IdempotencyRecord): Promise<void> {
const client = this.getClient();

const updateExpressionFields: string[] = [
'#response_data = :response_data',
'#expiry = :expiry',
Expand All @@ -219,7 +212,7 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
expressionAttributeValues[':validation_key'] = record.payloadHash;
}

await client.send(
await this.client.send(
new UpdateItemCommand({
TableName: this.tableName,
Key: this.getKey(record.idempotencyKey),
Expand All @@ -230,14 +223,6 @@ class DynamoDBPersistenceLayer extends BasePersistenceLayer {
);
}

private getClient(): DynamoDBClient {
if (!this.client) {
this.client = new DynamoDBClient(this.clientConfig);
}

return this.client;
}

/**
* Build primary key attribute simple or composite based on params.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,20 +163,14 @@ describe('Class: DynamoDBPersistenceLayer', () => {
);
});

test('when passed an invalid AWS SDK client it logs a warning', () => {
// Prepare
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();

// Act
new TestDynamoDBPersistenceLayer({
tableName: dummyTableName,
awsSdkV3Client: {} as DynamoDBClient,
});

// Assess
expect(consoleWarnSpy).toHaveBeenCalledWith(
'Invalid AWS SDK V3 client passed to DynamoDBPersistenceLayer. Using default client.'
);
test('when passed an invalid AWS SDK client, it throws an error', () => {
// Act & Assess
expect(() => {
new TestDynamoDBPersistenceLayer({
tableName: dummyTableName,
awsSdkV3Client: {} as DynamoDBClient,
});
}).toThrow();
});

test('when passed a client config it stores it for later use', () => {
Expand Down