-
Notifications
You must be signed in to change notification settings - Fork 323
/
Copy pathfs.js
357 lines (319 loc) · 10.6 KB
/
fs.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
'use strict'
const {
channel,
addHook,
AsyncResource
} = require('./helpers/instrument')
const shimmer = require('../../datadog-shimmer')
const startChannel = channel('apm:fs:operation:start')
const finishChannel = channel('apm:fs:operation:finish')
const errorChannel = channel('apm:fs:operation:error')
const ddFhSym = Symbol('ddFileHandle')
let kHandle, kDirReadPromisified, kDirClosePromisified
const paramsByMethod = {
access: ['path', 'mode'],
appendFile: ['path', 'data', 'options'],
chmod: ['path', 'mode'],
chown: ['path', 'uid', 'gid'],
close: ['fd'],
copyFile: ['src', 'dest', 'mode'],
cp: ['src', 'dest', 'options'],
exists: ['path'],
fchmod: ['fd', 'mode'],
fchown: ['fd', 'uid', 'gid'],
fdatasync: ['fd'],
fstat: ['fd', 'options'],
fsync: ['fd'],
ftruncate: ['fd', 'len'],
futimes: ['fd', 'atime', 'mtime'],
lchmod: ['path', 'mode'],
lchown: ['path', 'uid', 'gid'],
link: ['existingPath', 'newPath'],
lstat: ['path', 'options'],
lutimes: ['path', 'atime', 'mtime'],
mkdir: ['path', 'options'],
mkdtemp: ['prefix', 'options'],
open: ['path', 'flag', 'mode'],
opendir: ['path', 'options'],
read: ['fd'],
readdir: ['path', 'options'],
readFile: ['path', 'options'],
readlink: ['path', 'options'],
readv: ['fd'],
realpath: ['path', 'options'],
rename: ['oldPath', 'newPath'],
rmdir: ['path', 'options'],
rm: ['path', 'options'],
stat: ['path', 'options'],
symlink: ['target', 'path', 'type'],
truncate: ['path', 'len'],
unlink: ['path'],
utimes: ['path', 'atime', 'mtime'],
write: ['fd'],
writeFile: ['file', 'data', 'options'],
writev: ['fd']
}
const watchMethods = {
unwatchFile: ['path', 'listener'],
watch: ['path', 'options', 'listener'],
watchFile: ['path', 'options', 'listener']
}
const paramsByFileHandleMethods = {
appendFile: ['data', 'options'],
chmod: ['mode'],
chown: ['uid', 'gid'],
close: [],
createReadStream: ['options'],
createWriteStream: ['options'],
datasync: [],
read: ['buffer', 'offset', 'length', 'position'],
readableWebStream: [],
readFile: ['options'],
readLines: ['options'],
readv: ['buffers', 'position'],
stat: ['options'],
sync: [],
truncate: ['len'],
utimes: ['atime', 'mtime'],
write: ['buffer', 'offset', 'length', 'position'],
writeFile: ['data', 'options'],
writev: ['buffers', 'position']
}
const names = ['fs', 'node:fs']
names.forEach(name => {
addHook({ name }, fs => {
const asyncMethods = Object.keys(paramsByMethod)
const syncMethods = asyncMethods.map(name => `${name}Sync`)
massWrap(fs, asyncMethods, createWrapFunction())
massWrap(fs, syncMethods, createWrapFunction())
massWrap(fs.promises, asyncMethods, createWrapFunction('promises.'))
wrap(fs.realpath, 'native', createWrapFunction('', 'realpath.native'))
wrap(fs.realpathSync, 'native', createWrapFunction('', 'realpath.native'))
wrap(fs.promises.realpath, 'native', createWrapFunction('', 'realpath.native'))
wrap(fs, 'createReadStream', wrapCreateStream)
wrap(fs, 'createWriteStream', wrapCreateStream)
if (fs.Dir) {
wrap(fs.Dir.prototype, 'close', createWrapFunction('dir.'))
wrap(fs.Dir.prototype, 'closeSync', createWrapFunction('dir.'))
wrap(fs.Dir.prototype, 'read', createWrapFunction('dir.'))
wrap(fs.Dir.prototype, 'readSync', createWrapFunction('dir.'))
wrap(fs.Dir.prototype, Symbol.asyncIterator, createWrapDirAsyncIterator())
}
wrap(fs, 'unwatchFile', createWatchWrapFunction())
wrap(fs, 'watch', createWatchWrapFunction())
wrap(fs, 'watchFile', createWatchWrapFunction())
return fs
})
})
function isFirstMethodReturningFileHandle (original) {
return !kHandle && original.name === 'open'
}
function wrapFileHandle (fh) {
const fileHandlePrototype = getFileHandlePrototype(fh)
const desc = Reflect.getOwnPropertyDescriptor(fileHandlePrototype, kHandle)
if (!desc || !desc.get) {
Reflect.defineProperty(fileHandlePrototype, kHandle, {
get () {
return this[ddFhSym]
},
set (h) {
this[ddFhSym] = h
wrap(this, 'close', createWrapFunction('filehandle.'))
},
configurable: true
})
}
for (const name of Reflect.ownKeys(fileHandlePrototype)) {
if (typeof name !== 'string' || name === 'constructor' || name === 'fd' || name === 'getAsyncId') {
continue
}
wrap(fileHandlePrototype, name, createWrapFunction('filehandle.'))
}
}
function getFileHandlePrototype (fh) {
if (!kHandle) {
kHandle = Reflect.ownKeys(fh).find(key => typeof key === 'symbol' && key.toString().includes('kHandle'))
}
return Object.getPrototypeOf(fh)
}
function getSymbolName (sym) {
return sym.description || sym.toString()
}
function initDirAsyncIteratorProperties (iterator) {
const keys = Reflect.ownKeys(iterator)
for (const key of keys) {
if (kDirReadPromisified && kDirClosePromisified) break
if (typeof key !== 'symbol') continue
if (!kDirReadPromisified && getSymbolName(key).includes('kDirReadPromisified')) {
kDirReadPromisified = key
}
if (!kDirClosePromisified && getSymbolName(key).includes('kDirClosePromisified')) {
kDirClosePromisified = key
}
}
}
function createWrapDirAsyncIterator () {
return function wrapDirAsyncIterator (asyncIterator) {
return function wrappedAsyncIterator () {
if (!kDirReadPromisified || !kDirClosePromisified) {
initDirAsyncIteratorProperties(this)
}
wrap(this, kDirReadPromisified, createWrapFunction('dir.', 'read'))
wrap(this, kDirClosePromisified, createWrapFunction('dir.', 'close'))
return asyncIterator.apply(this, arguments)
}
}
}
function wrapCreateStream (original) {
const classes = {
createReadStream: 'ReadStream',
createWriteStream: 'WriteStream'
}
const name = classes[original.name]
return function (path, options) {
if (!startChannel.hasSubscribers) return original.apply(this, arguments)
const innerResource = new AsyncResource('bound-anonymous-fn')
const message = getMessage(name, ['path', 'options'], arguments)
return innerResource.runInAsyncScope(() => {
startChannel.publish(message)
try {
const stream = original.apply(this, arguments)
const onError = innerResource.bind(error => {
errorChannel.publish(error)
onFinish()
})
const onFinish = innerResource.bind(() => {
finishChannel.publish()
stream.off('close', onFinish)
stream.off('end', onFinish)
stream.off('finish', onFinish)
stream.off('error', onError)
})
stream.once('close', onFinish)
stream.once('end', onFinish)
stream.once('finish', onFinish)
stream.once('error', onError)
return stream
} catch (error) {
errorChannel.publish(error)
finishChannel.publish()
}
})
}
}
function getMethodParamsRelationByPrefix (prefix) {
if (prefix === 'filehandle.') {
return paramsByFileHandleMethods
}
return paramsByMethod
}
function createWatchWrapFunction (override = '') {
return function wrapFunction (original) {
const name = override || original.name
const method = name
const operation = name
return function () {
if (!startChannel.hasSubscribers) return original.apply(this, arguments)
const message = getMessage(method, watchMethods[operation], arguments, this)
const innerResource = new AsyncResource('bound-anonymous-fn')
return innerResource.runInAsyncScope(() => {
startChannel.publish(message)
try {
const result = original.apply(this, arguments)
finishChannel.publish()
return result
} catch (error) {
errorChannel.publish(error)
finishChannel.publish()
throw error
}
})
}
}
}
function createWrapFunction (prefix = '', override = '') {
return function wrapFunction (original) {
const name = override || original.name
const method = `${prefix}${name}`
const operation = name.match(/^(.+?)(Sync)?(\.native)?$/)[1]
return function () {
if (!startChannel.hasSubscribers) return original.apply(this, arguments)
const lastIndex = arguments.length - 1
const cb = typeof arguments[lastIndex] === 'function' && arguments[lastIndex]
const innerResource = new AsyncResource('bound-anonymous-fn')
const message = getMessage(method, getMethodParamsRelationByPrefix(prefix)[operation], arguments, this)
if (cb) {
const outerResource = new AsyncResource('bound-anonymous-fn')
arguments[lastIndex] = innerResource.bind(function (e) {
if (typeof e === 'object') { // fs.exists receives a boolean
errorChannel.publish(e)
}
finishChannel.publish()
return outerResource.runInAsyncScope(() => cb.apply(this, arguments))
})
}
return innerResource.runInAsyncScope(() => {
startChannel.publish(message)
try {
const result = original.apply(this, arguments)
if (cb) return result
if (result && typeof result.then === 'function') {
// TODO method open returning promise and filehandle prototype not initialized, initialize it
return result.then(
value => {
if (isFirstMethodReturningFileHandle(original)) {
wrapFileHandle(value)
}
finishChannel.publish()
return value
},
error => {
errorChannel.publish(error)
finishChannel.publish()
throw error
}
)
}
finishChannel.publish()
return result
} catch (error) {
errorChannel.publish(error)
finishChannel.publish()
throw error
}
})
}
}
}
function getMessage (operation, params, args, self) {
const metadata = {}
if (params) {
for (let i = 0; i < params.length; i++) {
if (!params[i] || typeof args[i] === 'function') continue
metadata[params[i]] = args[i]
}
}
if (self) {
// For `Dir` the path is available on `this.path`
if (self.path) {
metadata.path = self.path
}
// For FileHandle fs is available on `this.fd`
if (self.fd) {
metadata.fd = self.fd
}
}
return { operation, ...metadata }
}
function massWrap (target, methods, wrapper) {
for (const method of methods) {
wrap(target, method, wrapper)
}
}
function wrap (target, method, wrapper) {
try {
shimmer.wrap(target, method, wrapper)
} catch (e) {
// skip unavailable method
}
}