-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubmodule.module-proxy-builder.js
569 lines (460 loc) · 15.9 KB
/
submodule.module-proxy-builder.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/**
* @Module class and raw function proxy builder
*/
const _ = require('lodash')
const { isClass, isFunction } = require('./utils.check-obj-type')
const { getClassFunctionKeys } = require('./utils.obj-keys-parser')
const { DEBUG, debugLog } = require('./config')
const EVENT = {
CLASS_CONSTRUCTOR_FUNCTION_CALL_START: 'CLASS_CONSTRUCTOR_FUNCTION_CALL_START',
CLASS_CONSTRUCTOR_FUNCTION_CALL_RETURN: 'CLASS_CONSTRUCTOR_FUNCTION_CALL_RETURN',
CLASS_CONSTRUCTOR_FUNCTION_CALL_ERROR: 'CLASS_CONSTRUCTOR_FUNCTION_CALL_ERROR',
CLASS_INSTANCE_FUNCTION_CALL_START: 'CLASS_INSTANCE_FUNCTION_CALL_START',
CLASS_INSTANCE_FUNCTION_CALL_ERROR: 'CLASS_INSTANCE_FUNCTION_CALL_ERROR',
CLASS_INSTANCE_FUNCTION_CALL_SYNC_RETURN: 'CLASS_INSTANCE_FUNCTION_CALL_SYNC_RETURN',
CLASS_INSTANCE_FUNCTION_CALL_ASYNC_RETURN: 'CLASS_INSTANCE_FUNCTION_CALL_ASYNC_RETURN',
CLASS_STATIC_FUNCTION_CALL_START: 'CLASS_STATIC_FUNCTION_CALL_START',
CLASS_STATIC_FUNCTION_CALL_ERROR: 'CLASS_STATIC_FUNCTION_CALL_ERROR',
CLASS_STATIC_FUNCTION_CALL_SYNC_RETURN: 'CLASS_STATIC_FUNCTION_CALL_SYNC_RETURN',
CLASS_STATIC_FUNCTION_CALL_ASYNC_RETURN: 'CLASS_STATIC_FUNCTION_CALL_ASYNC_RETURN',
RAW_FUNCTION_CALL_START: 'RAW_FUNCTION_CALL_START',
RAW_FUNCTION_CALL_ERROR: 'RAW_FUNCTION_CALL_ERROR',
RAW_FUNCTION_CALL_SYNC_RETURN: 'RAW_FUNCTION_CALL_SYNC_RETURN',
RAW_FUNCTION_CALL_ASYNC_RETURN: 'RAW_FUNCTION_CALL_ASYNC_RETURN',
FRAMEWORK_ERROR: 'FRAMEWORK_ERROR',
}
// for generating unique id
const idCounter = {
idSet: new Set([0]),
genId() {
return Math.round(Math.random() * Number.MAX_SAFE_INTEGER)
},
getNextId: function () {
let id = 0
while (idCounter.idSet.has(id)) {
id = idCounter.genId()
}
idCounter.idSet.add(id)
return id
},
}
// get locale time string
function getLocaleTimeString() {
return new Date().toString()
}
// extends class by function
function extendsClass(baseClass, parentClass) {
baseClass.__proto__ = parentClass
}
// inherit static properties
function inheritClassStaticProperties(classA, classB) {
Object.keys(classB).forEach(key => {
const value = classB[key]
// assign name to function
if (isFunction(value)) {
const func = value
func.name = func.name ? func.name : key
}
classA[key] = value
})
}
// execute function, intercept error and re-throw
function executeFunctionAndInterceptError(func, errorCallback) {
try {
const result = func()
return result instanceof Promise
? result.catch(err => {
errorCallback && errorCallback(err)
throw err
})
: result
} catch (err) {
errorCallback && errorCallback(err)
throw err
}
}
/**
* @param {object} object
* @param {function} frameworkEventCallback: ({ eventType, className, functionName, functionArguments }) => {}
*/
function buildObjectProxyWithCallback(object, frameworkEventCallback) {
if (!object) return void 'AUTO_LOGGER_2020'
if (!frameworkEventCallback) return object
// only proxy first layer
getClassFunctionKeys(object).forEach(key => {
debugLog('buildObjectProxyWithCallback', `@key: ${key}`)
// proxy function only
object[key] = buildFunctionProxyWithCallback({
functionKey: key,
func: object[key],
frameworkEventCallback,
})
})
return object
}
/**
* @param {class} _class
* @param {function} frameworkEventCallback: ({ eventType, className, functionName, functionArguments, error }) => {}
*/
function buildClassProxyWithCallback({ modulePath, _class, frameworkEventCallback }) {
if (!_class) return void 'AUTO_LOGGER_2020'
if (!frameworkEventCallback) return _class
const parentClass = Object.getPrototypeOf(_class)
const className = _class.name
// override the class constructor
let ProxyClass = class {
constructor(...args) {
const classInstanceId = 'classInstanceId@' + idCounter.getNextId()
const functionStartTime = new Date()
debugLog('buildClassProxyWithCallback', 'ProxyClass#constructor', { args })
frameworkEventCallback({
eventType: EVENT.CLASS_CONSTRUCTOR_FUNCTION_CALL_START,
eventTime: getLocaleTimeString(),
className: _class.name,
classInstanceId,
functionName: 'constructor',
functionArguments: args,
modulePath,
})
let instance = executeFunctionAndInterceptError(
() => new _class(...args),
error => {
debugLog('buildClassProxyWithCallback', 'instance#executeFunctionAndInterceptError', { error })
frameworkEventCallback({
eventType: EVENT.CLASS_CONSTRUCTOR_FUNCTION_CALL_ERROR,
eventTime: getLocaleTimeString(),
className: _class.name,
classInstanceId,
functionName: 'constructor',
functionError: error,
modulePath,
})
}
)
instance = buildObjectProxyWithCallback(instance, objectProxyCallbackEvent =>
frameworkEventCallback({
...objectProxyCallbackEvent,
className: _class.name,
classInstanceId,
// map to class proxy event
eventType: {
[EVENT.RAW_FUNCTION_CALL_START]: EVENT.CLASS_INSTANCE_FUNCTION_CALL_START,
[EVENT.RAW_FUNCTION_CALL_SYNC_RETURN]:
EVENT.CLASS_INSTANCE_FUNCTION_CALL_SYNC_RETURN,
[EVENT.RAW_FUNCTION_CALL_ASYNC_RETURN]:
EVENT.CLASS_INSTANCE_FUNCTION_CALL_ASYNC_RETURN,
[EVENT.RAW_FUNCTION_CALL_ERROR]: EVENT.CLASS_INSTANCE_FUNCTION_CALL_ERROR,
}[objectProxyCallbackEvent.eventType],
modulePath,
})
)
frameworkEventCallback({
eventType: EVENT.CLASS_CONSTRUCTOR_FUNCTION_CALL_RETURN,
className: _class.name,
eventTime: getLocaleTimeString(),
classInstanceId,
functionName: 'constructor',
functionReturn: instance,
functionExecutionTime: (Date.now() - functionStartTime) / 1000 + ' seconds',
modulePath,
})
return instance
}
}
// assign back the class name
Object.defineProperty(ProxyClass, 'name', {
value: className,
})
// extend parent class
if (parentClass) extendsClass(ProxyClass, parentClass)
// inherit back all static properties
inheritClassStaticProperties(ProxyClass, _class)
// proxy static properties
ProxyClass = buildObjectProxyWithCallback(ProxyClass, objectProxyCallbackEvent =>
frameworkEventCallback({
...objectProxyCallbackEvent,
className: _class.name,
// map to class proxy event
eventType: {
[EVENT.RAW_FUNCTION_CALL_START]: EVENT.CLASS_STATIC_FUNCTION_CALL_START,
[EVENT.RAW_FUNCTION_CALL_SYNC_RETURN]:
EVENT.CLASS_STATIC_FUNCTION_CALL_SYNC_RETURN,
[EVENT.RAW_FUNCTION_CALL_ERROR]: EVENT.CLASS_STATIC_FUNCTION_CALL_ERROR,
}[objectProxyCallbackEvent.eventType],
modulePath,
})
)
return ProxyClass
}
/**
* @param {string} functionName - name of the function
* @param {function} func - the function
* @param {function} frameworkEventCallback - ({ eventType, functionName, functionArguments }) => {...}
*/
function buildFunctionProxyWithCallback({
modulePath,
functionName,
functionKey,
func,
frameworkEventCallback,
}) {
if (!func) return void 'AUTO_LOGGER_2020'
if (!frameworkEventCallback) return func
func.name = func.name || functionName || functionKey || 'function'
functionName = func.name
debugLog('buildFunctionProxyWithCallback', `#${functionName}: start proxy`)
const proxyFunction = new Proxy(func, {
apply: (func, thisArg, argArray) => {
const functionCallId = 'functionCallId@' + idCounter.getNextId()
const functionStartTime = new Date()
frameworkEventCallback({
eventType: EVENT.RAW_FUNCTION_CALL_START,
eventTime: getLocaleTimeString(),
functionArguments: argArray,
functionKey,
functionName,
functionCallId,
functionStartTime: functionStartTime.toString(),
modulePath,
})
debugLog('buildFunctionProxyWithCallback', `#${functionName}: start call`, argArray)
const result = executeFunctionAndInterceptError(
() => {
func = thisArg ? func.bind(thisArg) : func
return func(...argArray)
},
error => {
debugLog('buildFunctionProxyWithCallback', `#${functionName}: error`, error)
frameworkEventCallback({
eventType: EVENT.RAW_FUNCTION_CALL_ERROR,
eventTime: getLocaleTimeString(),
functionName,
functionKey,
functionCallId,
functionError: error,
functionExecutionTime: (Date.now() - functionStartTime) / 1000 + ' seconds',
modulePath,
})
}
)
debugLog('buildFunctionProxyWithCallback', `#${functionName}: return`, result)
function processResult(result, sync) {
frameworkEventCallback({
eventType: sync
? EVENT.RAW_FUNCTION_CALL_SYNC_RETURN
: EVENT.RAW_FUNCTION_CALL_ASYNC_RETURN,
eventTime: getLocaleTimeString(),
functionName,
functionKey,
functionCallId,
functionExecutionTime: (Date.now() - functionStartTime) / 1000 + ' seconds',
functionReturn: result,
modulePath,
})
return result
}
return result instanceof Promise
? result.then(result => processResult(result, false))
: processResult(result, true)
},
})
debugLog('buildFunctionProxyWithCallback', `#${functionName}: finish proxy`)
return proxyFunction
}
const __AUTO_LOGGER_PROXY_PROCESSED_MARK___ = '__AUTO_LOGGER_PROXY_PROCESSED___'
const processedPool = new Set()
function markTargetBeingProcessed(target) {
processedPool.add(target)
// @depreciated: as Object.defineProperties may not work in all cases
// Object.defineProperties(target, {
// [__AUTO_LOGGER_PROXY_PROCESSED_MARK___]: {
// value: true,
// enumerable: false,
// },
// })
}
function isTargetAlreadyProcessed(target) {
return processedPool.has(target)
// @depreciated: as Object.defineProperties may not work in all cases
// return target[__AUTO_LOGGER_PROXY_PROCESSED_MARK___]
}
/**
* build a proxy on the module
* @param {object} module - node module
* @param {function} classTargetProxy - (target: class) => class
* @param {function} functionTargetProxy - (target: function) => function
*/
function buildModuleProxy(module, { buildFunctionProxy, buildClassProxy }) {
debugLog('buildModuleProxy', '#start')
// check if it is primitive types
if (!_.isObject(module)) return module
const proxySetter = ({ key, target }) => {
debugLog('buildModuleProxy', '#proxySetter', { key })
// avoid to re-proxy
if (isTargetAlreadyProcessed(target)) return target
let proxyObj
if (isFunction(target)) {
proxyObj = buildFunctionProxy({ key, target })
}
if (isClass(target)) {
proxyObj = buildClassProxy({ target })
}
markTargetBeingProcessed(proxyObj)
return proxyObj
}
return traverseObjectAndProxyTarget({
obj: module,
})
function traverseObjectAndProxyTarget({ key, obj, callback }) {
debugLog('buildModuleProxy', '#traverseObjectAndProxyTarget', { key })
// check if class or function
if (_.isFunction(obj)) {
if (isTargetAlreadyProcessed(obj)) return obj
const proxyObj = proxySetter({ key, target: obj })
return callback ? callback(proxyObj) : proxyObj
}
// avoid circular reference
markTargetBeingProcessed(obj)
_.forOwn(obj, (val, key) => {
// avoid circular reference
if (isTargetAlreadyProcessed(val)) return
if (_.isArray(val)) {
const arr = val
function attachProxyTargetOnArray(index) {
return proxyTarget => (arr[index] = proxyTarget)
}
arr.forEach((i, e) => {
traverseObjectAndProxyTarget({ obj: e, callback: attachProxyTargetOnArray(i) })
})
} else if (_.isObject(val)) {
function attachProxyTargetOnObject(key) {
return proxyTarget => (obj[key] = proxyTarget)
}
traverseObjectAndProxyTarget({
key,
obj: val,
callback: attachProxyTargetOnObject(key),
})
}
})
return obj
}
}
/**
* - iterate the internal module seems throwing unexpected errors
*
* @usage mark target's functions being visited to avoid them to be revisited
*
* @param {object} module - node module
*/
function markModuleVisited(module) {
debugLog('markModuleVisited', '#start')
// check if it is primitive types
if (!_.isObject(module)) return module
const markTarget = ({ target }) => {
if (isTargetAlreadyProcessed(target)) return target
markTargetBeingProcessed(target)
return target
}
return traverseObjectAndMarkTarget({
obj: module,
})
function traverseObjectAndMarkTarget({ obj, callback }) {
debugLog('markModuleVisited', '#traverseObjectAndMarkTarget')
// check if class or function
if (_.isFunction(obj)) {
if (isTargetAlreadyProcessed(obj)) return obj
const markedTarget = markTarget({ target: obj })
return callback ? callback(markedTarget) : markedTarget
}
// avoid circular reference
markTargetBeingProcessed(obj)
// TODO: here iterates the obj will throw unexpected error
_.forOwn(obj, (val, key) => {
// avoid circular reference
if (isTargetAlreadyProcessed(val)) return
if (_.isArray(val)) {
const arr = val
function attachMarkedTargetOnArray(index) {
return targetMarked => (arr[index] = targetMarked)
}
arr.forEach((i, e) => {
traverseObjectAndMarkTarget({ obj: e, callback: attachMarkedTargetOnArray(i) })
})
} else if (_.isObject(val)) {
function attachMarkedTargetOnObject(key) {
return targetMarked => (obj[key] = targetMarked)
}
traverseObjectAndMarkTarget({
obj: val,
callback: attachMarkedTargetOnObject(key),
})
}
})
return obj
}
}
function markTargetDisabledByDynamicProxy(target, frameworkEventCallback) {
// not handling primitive types
if (!_.isObject(target)) return target
{
// avoid repeatable works
if (isTargetAlreadyProcessed(target)) return target
markTargetBeingProcessed(target)
}
{
// only proxy proxiable target, temp. work around using try{..}catch{...}
try {
// TODO: handling unproxiable frozen object
if (Object.isFrozen(target)) {
return target
}
const proxy = new Proxy(target, {
// get: function (target, prop, receiver) {
// if (descriptor && descriptor.writeable) {
// return markTargetDisabledByDynamicProxy(target[prop])
// }else{
// return target[prop]
// }
// },
})
return proxy
} catch (err) {
frameworkEventCallback({
eventType: EVENT.FRAMEWORK_ERROR,
error: err,
eventTime: getLocaleTimeString(),
target: target,
functionName: 'markTargetDisabledByDynamicProxy',
})
return target
}
}
}
/**
* mark the proxy actions of the module proxy are disabled
*/
function disableModuleProxyActions(module) {
return markTargetDisabledByDynamicProxy(module)
}
module.exports = {
EVENT,
markModuleVisited: module => markModuleVisited(module), // not used yet
buildModuleProxy: (module, modulePath, frameworkEventCallback) =>
buildModuleProxy(module, {
buildFunctionProxy: ({ key, target }) =>
buildFunctionProxyWithCallback({
modulePath,
functionKey: key,
func: target,
frameworkEventCallback,
}),
buildClassProxy: ({ target }) =>
buildClassProxyWithCallback({
modulePath,
_class: target,
frameworkEventCallback,
}),
}),
disableModuleProxyActions: module => disableModuleProxyActions(module), // not used yet
}