Skip to content
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

fix: resolve instrumented modules correctly when distro is loaded via NODE_PATH #548

Merged
merged 8 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
150 changes: 12 additions & 138 deletions package-lock.json

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

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
"@opentelemetry/sdk-trace-base": "1.9.1",
"@opentelemetry/sdk-trace-node": "1.9.1",
"@opentelemetry/semantic-conventions": "1.17.1",
"@opentelemetry/winston-transport": "0.2.0",
"@prisma/instrumentation": "^4.14.0",
"deasync": "^0.1.30",
"opentelemetry-instrumentation-express": "0.39.1",
Expand Down Expand Up @@ -118,7 +117,7 @@
"semantic-release": "^19.0.2",
"semver": "^7.3.7",
"testcontainers": "^8.16.0",
"tmp": "^0.2.1",
"tmp": "^0.2.3",
"ts-node": "^9.1.1",
"typescript": "^4.3.4",
"utf-8-validate": "^5.0.2",
Expand Down
3 changes: 2 additions & 1 deletion src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ import {
LumigoKubernetesDetector,
LumigoTagDetector,
} from './resources/detectors';
import { getLogAttributeMaxLength, getSpanAttributeMaxLength, safeRequire } from './utils';
import { getLogAttributeMaxLength, getSpanAttributeMaxLength } from './utils';
import { safeRequire } from './requireUtils';

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
Expand Down
2 changes: 1 addition & 1 deletion src/instrumentations/instrumentor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Instrumentation } from '@opentelemetry/instrumentation';
import { canRequireModule } from '../utils';
import { canRequireModule } from '../requireUtils';
import { LOGGING_ENABLED, TRACING_ENABLED } from '../constants';

abstract class Instrumentor<T extends Instrumentation> {
Expand Down
33 changes: 33 additions & 0 deletions src/requireUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import path from 'path';
import { safeRequire } from './requireUtils';
import { version } from '../package.json';

describe('safeRequire', () => {
afterEach(() => {
jest.clearAllMocks();
});

test('requires an existing module with the given path', () => {
const packageJsonPath = path.join(__dirname, '..', 'package.json');

const result = safeRequire(packageJsonPath);

expect(result.version).toEqual(version);
});

test('does not fail but returns undefined for a non-existing module', () => {
const result = safeRequire('BlaBlaBlaBla');

expect(result).toBeUndefined();
});

test('does not fail but returns undefined when an errors occurs when loading the module', () => {
jest.doMock('fs', () => {
throw Error('RandomError');
});

const result = safeRequire('fs');

expect(result).toBeUndefined();
});
});
67 changes: 67 additions & 0 deletions src/requireUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import path from 'path';
import { logger } from './logging';

const getRequireFunction = (): NodeRequire =>
// @ts-ignore __non_webpack_require__ not available at compile time
typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : require;

export const safeRequire = (moduleSpecifier) => {
try {
const customRequire = getRequireFunction();
const resolvedPath = safeResolvePath(moduleSpecifier);
return resolvedPath ? customRequire(resolvedPath) : undefined;
} catch (e) {
logger.warn('Unable to load module', {
error: e,
libId: moduleSpecifier,
});

return undefined;
}
};

const tryResolveFromPathGroup = (
customRequire: NodeRequire,
moduleSpecifier: string,
paths: string[]
): string => {
try {
const resolvedPath = customRequire.resolve(moduleSpecifier, { paths });
if (resolvedPath) {
logger.debug(
`${moduleSpecifier} successfully loaded from ${resolvedPath}. Paths searched: `,
paths
);
} else {
logger.debug(
`${moduleSpecifier} could not be loaded from any of the following paths: `,
paths
);
}
return resolvedPath;
} catch (error) {
if (error.code !== 'MODULE_NOT_FOUND') {
logger.warn('Unable to resolve module', { error, moduleSpecifier });
return undefined;
}
}
};

const safeResolvePath = (moduleSpecifier: string): string | undefined => {
const customReq = getRequireFunction();

const pathGroups = [
// default paths - same as not specifying paths to require.resolve()
customReq.resolve?.paths?.(moduleSpecifier) || [],
// paths specified in NODE_PATH, in case the user has set it for some reason
(process.env.NODE_PATH || '').split(':'),
// process CWD - i.e. the node_nodules folder of the process require()-ed the distro
[path.resolve(process.cwd(), 'node_modules')],
];

return pathGroups
.map((pathGroup) => tryResolveFromPathGroup(customReq, moduleSpecifier, pathGroup))
.find(Boolean);
};

export const canRequireModule = (moduleSpecifier) => !!safeResolvePath(moduleSpecifier);
Loading
Loading