Skip to content

Commit

Permalink
feat: Improve http hook (#132)
Browse files Browse the repository at this point in the history
feat: Improve http hook (#132)
  • Loading branch information
doriaviram authored Jun 30, 2020
1 parent 069bc36 commit 3670fd4
Show file tree
Hide file tree
Showing 37 changed files with 963 additions and 1,369 deletions.
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"printWidth": 80,
"printWidth": 100,
"tabWidth": 2,
"semi": true,
"singleQuote": true,
Expand Down
4 changes: 1 addition & 3 deletions auto-instrument-handler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ const ORIGINAL_HANDLER_KEY = 'LUMIGO_ORIGINAL_HANDLER';

const parseOriginalHandler = originalHandler => {
if (!originalHandler) {
throw Error(
'Could not load the original handler. Are you sure that the handler is correct?'
);
throw Error('Could not load the original handler. Are you sure that the handler is correct?');
}
// The handler's format is `file_path.function`, where the `file_path` is inside `/var/task`
if (!originalHandler.includes('.')) {
Expand Down
16 changes: 11 additions & 5 deletions auto-instrument-handler/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,30 @@ describe('tracer', () => {
process.env[index.LUMIGO_SWITCH_OFF] = 'TRUE';

process.env[index.ORIGINAL_HANDLER_KEY] = '';
expect(() => index.handler({}, {})).toThrowError("Could not load the original handler. Are you sure that the handler is correct?");
expect(() => index.handler({}, {})).toThrowError(
'Could not load the original handler. Are you sure that the handler is correct?'
);

process.env[index.ORIGINAL_HANDLER_KEY] = 'bad/handler/format';
expect(() => index.handler({}, {})).toThrowError("Could not parse the original handler - invalid format");
expect(() => index.handler({}, {})).toThrowError(
'Could not parse the original handler - invalid format'
);

process.env[index.ORIGINAL_HANDLER_KEY] = 'not/Existing.handler';
try {
index.handler({}, {});
fail("should raise");
fail('should raise');
} catch (e) {
expect(e.message).toEqual("Cannot find module '/var/task/not/Existing' from 'index.js'");
expect(e.stack).not.toContain("auto-instrument");
expect(e.stack).not.toContain('auto-instrument');
}

process.env[
index.ORIGINAL_HANDLER_KEY
] = `../../${__dirname}/testdata/example_handler.not_existing`;
expect(() => index.handler({}, {})).toThrowError(`Could not find the handler's function (not_existing) inside the handler's file (/var/task/../../${__dirname}/testdata/example_handler)`);
expect(() => index.handler({}, {})).toThrowError(
`Could not find the handler's function (not_existing) inside the handler's file (/var/task/../../${__dirname}/testdata/example_handler)`
);

process.env[
index.ORIGINAL_HANDLER_KEY
Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module.exports = {
silent: true,
testEnvironment: 'node',
coverageDirectory: './coverage/',
collectCoverage: true,
Expand Down
15 changes: 0 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"@semantic-release/git": "^7.0.16",
"aws-sdk": "^2.465.0",
"babel-eslint": "^10.0.1",
"clone-response": "^1.0.2",
"codecov": "^3.5.0",
"eslint": "^5.16.0",
"eslint-config-prettier": "^4.3.0",
Expand Down
18 changes: 4 additions & 14 deletions src/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ export const getTriggeredBy = event => {
}
}

if (
(event && event['httpMethod']) ||
(event && event['headers'] && event['version'] === '2.0')
) {
if ((event && event['httpMethod']) || (event && event['headers'] && event['version'] === '2.0')) {
return 'apigw';
}

Expand Down Expand Up @@ -76,8 +73,7 @@ export const getKinesisData = event => {

export const getDynamodbData = event => {
const arn = event.Records[0].eventSourceARN;
const approxEventCreationTime =
event.Records[0].dynamodb.ApproximateCreationDateTime * 1000;
const approxEventCreationTime = event.Records[0].dynamodb.ApproximateCreationDateTime * 1000;
const messageIds = (event.Records || [])
.map(record => {
if (
Expand All @@ -86,11 +82,7 @@ export const getDynamodbData = event => {
record.dynamodb.Keys
) {
return md5Hash(record.dynamodb.Keys);
} else if (
record.eventName === 'INSERT' &&
record.dynamodb &&
record.dynamodb.NewImage
) {
} else if (record.eventName === 'INSERT' && record.dynamodb && record.dynamodb.NewImage) {
return md5Hash(record.dynamodb.NewImage);
}
})
Expand All @@ -114,9 +106,7 @@ export const getRelevantEventData = (triggeredBy, event) => {
return getApiGatewayData(event);
case 'stepFunction':
return {
messageId: recursiveGetKey(event, LUMIGO_EVENT_KEY)[
STEP_FUNCTION_UID_KEY
],
messageId: recursiveGetKey(event, LUMIGO_EVENT_KEY)[STEP_FUNCTION_UID_KEY],
};
case 'invocation':
default:
Expand Down
64 changes: 22 additions & 42 deletions src/events.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,8 @@ describe('events', () => {
expect(events.getTriggeredBy(exampleSesEvent)).toEqual('ses');
expect(events.getTriggeredBy(exampleKinesisEvent)).toEqual('kinesis');
expect(events.getTriggeredBy(exampleApiGatewayEvent)).toEqual('apigw');
expect(events.getTriggeredBy(exampleDynamoDBInsertEvent)).toEqual(
'dynamodb'
);
expect(events.getTriggeredBy(exampleUnsupportedEvent)).toEqual(
'invocation'
);
expect(events.getTriggeredBy(exampleDynamoDBInsertEvent)).toEqual('dynamodb');
expect(events.getTriggeredBy(exampleUnsupportedEvent)).toEqual('invocation');
});

test('getApiGatewayData', () => {
Expand All @@ -40,14 +36,12 @@ describe('events', () => {
stage: 'testStage',
});

expect(events.getApiGatewayData(exampleApiGatewayEventWithoutHost)).toEqual(
{
api: null,
httpMethod: undefined,
resource: undefined,
stage: null,
}
);
expect(events.getApiGatewayData(exampleApiGatewayEventWithoutHost)).toEqual({
api: null,
httpMethod: undefined,
resource: undefined,
stage: null,
});
});

test('getApiGatewayData => API gw v2', () => {
Expand All @@ -72,19 +66,15 @@ describe('events', () => {
arn: 'arn:aws:sqs:us-west-2:123456789012:SQSQueue',
});

expect(events.getRelevantEventData('kinesis', exampleKinesisEvent)).toEqual(
{
arn: 'arn:aws:kinesis:us-east-1:123456789012:stream/simple-stream',
messageIds: [
'49568167373333333333333333333333333333333333333333333333',
'49568167373333333334444444444444444444444444444444444444',
],
}
);
expect(events.getRelevantEventData('kinesis', exampleKinesisEvent)).toEqual({
arn: 'arn:aws:kinesis:us-east-1:123456789012:stream/simple-stream',
messageIds: [
'49568167373333333333333333333333333333333333333333333333',
'49568167373333333334444444444444444444444444444444444444',
],
});

expect(
events.getRelevantEventData('dynamodb', exampleDynamoDBInsertEvent)
).toEqual({
expect(events.getRelevantEventData('dynamodb', exampleDynamoDBInsertEvent)).toEqual({
arn:
'arn:aws:dynamodb:us-east-1:123456789012:table/Example-Table/stream/2016-12-01T00:00:00.000',
messageIds: [
Expand All @@ -99,20 +89,14 @@ describe('events', () => {
approxEventCreationTime: 1480642020000,
});

expect(
events.getRelevantEventData('dynamodb', exampleDynamoDBModifyEvent)
).toEqual({
arn:
'arn:aws:dynamodb:us-west-2:723663554526:table/abbbbb/stream/2020-05-25T12:04:49.788',
expect(events.getRelevantEventData('dynamodb', exampleDynamoDBModifyEvent)).toEqual({
arn: 'arn:aws:dynamodb:us-west-2:723663554526:table/abbbbb/stream/2020-05-25T12:04:49.788',
messageIds: [md5Hash({ key: { N: '8' } })],
approxEventCreationTime: 1590509701000,
});

expect(
events.getRelevantEventData('dynamodb', exampleDynamoDBRemoveEvent)
).toEqual({
arn:
'arn:aws:dynamodb:us-west-2:723663554526:table/abbbbb/stream/2020-05-25T12:04:49.788',
expect(events.getRelevantEventData('dynamodb', exampleDynamoDBRemoveEvent)).toEqual({
arn: 'arn:aws:dynamodb:us-west-2:723663554526:table/abbbbb/stream/2020-05-25T12:04:49.788',
messageIds: [md5Hash({ key: { N: '123' } })],
approxEventCreationTime: 1590509672000,
});
Expand All @@ -125,9 +109,7 @@ describe('events', () => {
expect(events.getRelevantEventData('s3', exampleS3Event)).toEqual({
arn: 'arn:aws:s3:::mybucket',
});
expect(
events.getRelevantEventData('apigw', exampleApiGatewayEvent)
).toEqual({
expect(events.getRelevantEventData('apigw', exampleApiGatewayEvent)).toEqual({
api: 'gy415nuibc.execute-api.us-east-1.amazonaws.com',
httpMethod: 'POST',
messageId: 'deef4878-7910-11e6-8f14-25afc3e9ae33',
Expand All @@ -136,9 +118,7 @@ describe('events', () => {
});

expect(events.getRelevantEventData('ses', exampleSesEvent)).toEqual({});
expect(
events.getRelevantEventData('invocation', exampleUnsupportedEvent)
).toEqual({});
expect(events.getRelevantEventData('invocation', exampleUnsupportedEvent)).toEqual({});
});

test('getEventInfo', () => {
Expand Down
28 changes: 28 additions & 0 deletions src/extender.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import shimmer from 'shimmer';
import * as logger from './logger';
import { safeExecute } from './utils';

const noop = () => {};

const isFunctionAlreadyWrapped = fn => fn && fn.__wrapped;

export const hook = (module, funcName, options = {}) => {
const { beforeHook = noop, afterHook = noop } = options;
const safeBeforeHook = safeExecute(beforeHook, `before hook of ${funcName} fail`);
const safeAfterHook = safeExecute(afterHook, `after hook of ${funcName} fail`);
const extenderContext = {};
try {
const wrapper = originalFn => {
if (isFunctionAlreadyWrapped(originalFn)) return originalFn;
return function(...args) {
safeBeforeHook.call(this, args, extenderContext);
const originalFnResult = originalFn.apply(this, args);
safeAfterHook.call(this, args, originalFnResult, extenderContext);
return originalFnResult;
};
};
shimmer.wrap(module, funcName, wrapper);
} catch (e) {
logger.warn(`Wrapping of function ${funcName} failed`, options);
}
};
Loading

0 comments on commit 3670fd4

Please sign in to comment.