Skip to content

Commit

Permalink
Feature/ngstn 726 sst support (#12)
Browse files Browse the repository at this point in the history
This PR extends the logic of applying lambda handler instrumentation in two ways.
* Supporting handler defined in *.mjs files
* Adding additinal InstrumentationNodeModuleDefinition matching by filename, which turns out to be what is needed in a module environment with the import-in-the-middle-hook
  • Loading branch information
RafalSumislawski authored Apr 23, 2024
1 parent 4d908e6 commit 8bdf2ed
Showing 1 changed file with 31 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,23 @@ export class AwsLambdaInstrumentation extends InstrumentationBase {

// Lambda loads user function using an absolute path.
let filename = path.resolve(taskRoot, moduleRoot, module);
if (!filename.endsWith('.js')) {
// its impossible to know in advance if the user has a cjs or js file.
// check that the .js file exists otherwise fallback to next known possibility
if (!filename.includes('.')) {
// The filename has no extension, we need to check if there is a .js, .cjs or .mjs file
try {
fs.statSync(`${filename}.js`);
filename += '.js';
} catch (e) {
// fallback to .cjs
filename += '.cjs';
try {
fs.statSync(`${filename}.cjs`);
filename += '.cjs';
} catch (e) {
try {
fs.statSync(`${filename}.mjs`);
filename += '.mjs';
} catch (e) {
diag.warn(`AwsLambdaInstrumentation couldn't find the handler file: ${filename}`);
}
}
}
}

Expand Down Expand Up @@ -192,6 +200,24 @@ export class AwsLambdaInstrumentation extends InstrumentationBase {
this._unwrap(moduleExports, functionName);
}
),
// This approach works when the handler is an .mjs file in the function source code
new InstrumentationNodeModuleDefinition(
filename,
['*'],
(moduleExports: LambdaModule) => {
diag.debug('Applying patch for lambda handler');
if (isWrapped(moduleExports[functionName])) {
this._unwrap(moduleExports, functionName);
}
this._wrap(moduleExports, functionName, this._getHandler());
return moduleExports;
},
(moduleExports?: LambdaModule) => {
if (moduleExports === undefined) return;
diag.debug('Removing patch for lambda handler');
this._unwrap(moduleExports, functionName);
}
),
];
}

Expand Down

0 comments on commit 8bdf2ed

Please sign in to comment.