-
Notifications
You must be signed in to change notification settings - Fork 36
/
requireHook.js
204 lines (178 loc) · 6.72 KB
/
requireHook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
* (c) Copyright IBM Corp. 2021
* (c) Copyright Instana Inc. and contributors 2016
*/
'use strict';
const Module = require('module');
const path = require('path');
/**
* @typedef {Object} FileNamePatternTransformer
* @property {Function} fn
* @property {RegExp} pattern
*/
/**
* @typedef {Object} ExecutedHook
* @property {*} originalModuleExports
* @property {*} moduleExports
* @property {Array<string>} appliedByModuleNameTransformers
* @property {boolean} byFileNamePatternTransformersApplied
*/
/**
* @typedef {Object.<string, ExecutedHook>} ExecutedHooks
*/
/** @type {ExecutedHooks} */
let executedHooks = {};
/** @type {Object.<string, *>} */
let byModuleNameTransformers = {};
/** @type {Array<FileNamePatternTransformer>} */
let byFileNamePatternTransformers = [];
const origLoad = /** @type {*} */ (Module)._load;
/** @type {import('../logger').GenericLogger} */
let logger;
logger = require('../logger').getLogger('util/requireHook', newLogger => {
logger = newLogger;
});
/**
* @param {import('./normalizeConfig').InstanaConfig} [config]
*/
// eslint-disable-next-line no-unused-vars
exports.init = function (config) {
/** @type {*} */ (Module)._load = patchedModuleLoad;
};
/**
* @param {string} moduleName
*/
function patchedModuleLoad(moduleName) {
// CASE: when using ESM, the Node runtime passes a full path to Module._load
// we try to grab the module name to being able to patch the target module
// with our instrumentation
// CASE: we ignore all file endings, which we are not interested in. Any module can load any file.
if (path.isAbsolute(moduleName) && ['.node', '.json', '.ts'].indexOf(path.extname(moduleName)) === -1) {
// EDGE CASE for ESM: mysql2/promise.js
if (moduleName.indexOf('node_modules/mysql2/promise.js') !== -1) {
moduleName = 'mysql2/promise';
} else {
// e.g. path is node_modules/@elastic/elasicsearch/index.js
let match = moduleName.match(/node_modules\/(@.*?(?=\/)\/.*?(?=\/))/);
if (match && match.length > 1) {
moduleName = match[1];
} else {
// e.g. path is node_modules/mysql/lib/index.js
match = moduleName.match(/node_modules\/(.*?(?=\/))/);
if (match && match.length > 1) {
moduleName = match[1];
}
}
}
}
// First attempt to always get the module via the original implementation
// as this action may fail. The original function populates the module cache.
const moduleExports = origLoad.apply(Module, arguments);
/** @type {string} */
const filename = /** @type {*} */ (Module)._resolveFilename.apply(Module, arguments);
// We are not directly manipulating the global module cache because there might be other tools fiddling with
// Module._load. We don't want to break any of them.
const cacheEntry = (executedHooks[filename] = executedHooks[filename] || {
originalModuleExports: moduleExports,
moduleExports,
// We might have already seen and processed, i.e. manipulated, this require statement. This is something we
// are checking using these fields.
appliedByModuleNameTransformers: [],
byFileNamePatternTransformersApplied: false
});
// Some non-APM modules are fiddling with the require cache in some very unexpected ways.
// For example the request-promise* modules use stealthy-require to always get a fresh copy
// of the request module. Instead of adding a mechanism to get a copy the request function,
// they temporarily force clear the require cache and require the request module again
// to get a copy.
//
// In order to ensure that any such (weird) use cases are supported by us, we are making sure
// that we only return our patched variant when Module._load returned the same object based
// on which we applied our patches.
if (cacheEntry.originalModuleExports !== moduleExports) {
return moduleExports;
}
const applicableByModuleNameTransformers = byModuleNameTransformers[moduleName];
if (applicableByModuleNameTransformers && cacheEntry.appliedByModuleNameTransformers.indexOf(moduleName) === -1) {
for (let i = 0; i < applicableByModuleNameTransformers.length; i++) {
const transformerFn = applicableByModuleNameTransformers[i];
if (typeof transformerFn === 'function') {
try {
cacheEntry.moduleExports = transformerFn(cacheEntry.moduleExports, filename) || cacheEntry.moduleExports;
} catch (e) {
logger.error(`Cannot instrument ${moduleName} due to an error in instrumentation: ${e}`);
if (e.message) {
logger.error(e.message);
}
if (e.stack) {
logger.error(e.stack);
}
}
} else {
logger.error(
'A requireHook invariant has been violated for module name %s, index %s. The transformer is not a function ' +
'but of type "%s" (details: %s). The most likely cause is that something has messed with Node.js\' ' +
'module cache. This can result in limited tracing and health check functionality (for example, missing ' +
'calls in Instana).',
moduleName,
i,
typeof transformerFn,
transformerFn == null ? 'null/undefined' : transformerFn
);
}
}
cacheEntry.appliedByModuleNameTransformers.push(moduleName);
}
if (!cacheEntry.byFileNamePatternTransformersApplied) {
for (let i = 0; i < byFileNamePatternTransformers.length; i++) {
if (byFileNamePatternTransformers[i].pattern.test(filename)) {
cacheEntry.moduleExports =
byFileNamePatternTransformers[i].fn(cacheEntry.moduleExports, filename) || cacheEntry.moduleExports;
}
}
cacheEntry.byFileNamePatternTransformersApplied = true;
}
return cacheEntry.moduleExports;
}
exports.teardownForTestPurposes = function () {
/** @type {*} */ (Module)._load = origLoad;
executedHooks = {};
byModuleNameTransformers = {};
byFileNamePatternTransformers = [];
};
/**
* @param {string} moduleName
* @param {Function} fn
*/
exports.onModuleLoad = function on(moduleName, fn) {
byModuleNameTransformers[moduleName] = byModuleNameTransformers[moduleName] || [];
byModuleNameTransformers[moduleName].push(fn);
};
/**
* @param {RegExp} pattern
* @param {Function} fn
*/
exports.onFileLoad = function onFileLoad(pattern, fn) {
byFileNamePatternTransformers.push({
pattern,
fn
});
};
/**
* @param {Array<string>} arr
*/
exports.buildFileNamePattern = function buildFileNamePattern(arr) {
return new RegExp(`${arr.reduce(buildFileNamePatternReducer, '')}$`);
};
/**
* @param {string} agg
* @param {string} pathSegment
* @returns {string}
*/
function buildFileNamePatternReducer(agg, pathSegment) {
if (agg.length > 0) {
agg += `\\${path.sep}`;
}
agg += pathSegment;
return agg;
}