-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathevent.js
572 lines (465 loc) · 13.8 KB
/
event.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
570
571
572
import { addHiddenProperty, hasProp, transformToJSON } from './util';
import analyzeSQL, { abstractSqlAstJSON } from './sql/analyze';
import normalizeSQL from './sql/normalize';
import HashBuilder from './hashBuilder';
function alias(obj, prop, alias) {
if (!obj || typeof obj[prop] === 'undefined' || typeof obj[alias] !== 'undefined') {
return;
}
Object.defineProperty(obj, alias, {
get() {
return this[prop];
},
enumerable: false,
});
}
// This class supercedes `CallTree` and `CallNode`. Events are stored in a flat
// array and can also be traversed like a tree via `parent` and `children`.
export default class Event {
static contentType(...messages) {
const msg = messages.find((message) => (message?.headers || {})['Content-Type']);
if (!msg) {
return null;
}
return msg.headers['Content-Type'];
}
constructor(obj) {
let data = obj;
if (obj instanceof Event) {
data = { ...obj };
if (obj.$hidden.parameters) {
data.parameters = obj.$hidden.parameters.map((p) => ({ ...p }));
}
if (Array.isArray(obj.$hidden.message)) {
data.message = obj.$hidden.message.map((m) => ({ ...m }));
}
if (obj.$hidden.labels) {
data.labels = [...obj.$hidden.labels];
}
if (obj.$hidden.exceptions) {
data.exceptions = [...obj.$hidden.exceptions];
}
}
this.dataKeys = Object.keys(data);
// Cyclic references shall not be enumerable
if (data.event === 'call') {
addHiddenProperty(this, 'parent');
addHiddenProperty(this, 'children', { writable: false, value: [] });
addHiddenProperty(this, 'dataReferences', { writable: false, value: [] });
addHiddenProperty(this, 'codeObject');
addHiddenProperty(this, 'parameters');
addHiddenProperty(this, 'message');
}
addHiddenProperty(this, 'linkedEvent');
addHiddenProperty(this, 'labels');
addHiddenProperty(this, 'exceptions');
addHiddenProperty(this, 'next');
addHiddenProperty(this, 'previous');
addHiddenProperty(this, 'hash');
addHiddenProperty(this, 'identityHash');
addHiddenProperty(this, 'depth');
addHiddenProperty(this, 'sqlQuery');
// Backward compatibility
// `status_code` used to be normalized to `status` during normalization. They can now be used
// interchangeably.
alias(data.http_server_response, 'status_code', 'status');
alias(data.http_server_response, 'status', 'status_code');
alias(data.http_client_response, 'status_code', 'status');
alias(data.http_client_response, 'status', 'status_code');
// Data must be written last, after our properties are configured.
Object.assign(this, data);
}
get depth() {
if (this.$hidden.depth === undefined) {
let result = 0;
let { parent } = this;
while (parent) {
result += 1;
parent = parent.parent;
}
this.$hidden.depth = result;
}
return this.$hidden.depth;
}
get methodId() {
return this.method_id;
}
get isFunction() {
return this.definedClass && this.methodId;
}
get isStatic() {
return this.static;
}
get sql() {
return this.callEvent.sql_query;
}
get returnValue() {
return this.returnEvent ? this.returnEvent.return_value : undefined;
}
get elapsedTime() {
return this.returnEvent ? this.returnEvent.elapsed : undefined;
}
get elapsedInstrumentationTime() {
return this.returnEvent ? this.returnEvent.elapsed_instrumentation : undefined;
}
get linkedEvent() {
return this.$hidden.linkedEvent;
}
get next() {
return this.$hidden.next;
}
get previous() {
return this.$hidden.previous;
}
get parent() {
return this.$hidden.parent;
}
get children() {
return this.$hidden.children || [];
}
get codeObject() {
return this.callEvent.$hidden.codeObject;
}
get parameters() {
return this.callEvent.$hidden.parameters;
}
get labels() {
const eventLabels = this.callEvent.$hidden.labels || [];
return new Set([...eventLabels, ...this.callEvent.codeObject.labels]);
}
get exceptions() {
return this.returnEvent ? this.returnEvent.$hidden.exceptions || [] : [];
}
get message() {
return this.callEvent.$hidden.message;
}
get httpServerRequest() {
return this.callEvent.http_server_request;
}
get httpServerResponse() {
return this.returnEvent ? this.returnEvent.http_server_response : undefined;
}
get httpClientRequest() {
return this.callEvent.http_client_request;
}
get httpClientResponse() {
return this.returnEvent ? this.returnEvent.http_client_response : undefined;
}
get definedClass() {
return this.defined_class ? this.defined_class.replace(/\./g, '/') : null;
}
get requestPath() {
if (this.httpServerRequest) {
return this.httpServerRequest.normalized_path_info || this.httpServerRequest.path_info;
}
if (this.httpClientRequest) {
return this.httpClientRequest.url;
}
return null;
}
get requestMethod() {
if (this.httpServerRequest) {
return this.httpServerRequest.request_method;
}
if (this.httpClientRequest) {
return this.httpClientRequest.request_method;
}
return null;
}
get requestContentType() {
return Event.contentType(this.httpServerRequest, this.httpClientRequest);
}
get responseContentType() {
return Event.contentType(this.httpServerResponse, this.httpClientResponse);
}
get route() {
const { requestMethod, requestPath } = this;
if (!requestMethod || !requestPath) {
return null;
}
return `${requestMethod} ${requestPath}`;
}
get sqlQuery() {
if (!this.$hidden.sqlQuery) {
const { sql } = this;
this.$hidden.sqlQuery = sql ? sql.normalized_sql || sql.sql : null;
}
return this.$hidden.sqlQuery;
}
get fqid() {
return `event:${this.id}`;
}
get previousSibling() {
const { parent } = this;
if (!parent) {
return null;
}
const myIndex = parent.children.findIndex((e) => e === this);
console.assert(myIndex !== -1, 'attempted to locate index of an orphaned event');
if (myIndex === 0) {
return null;
}
return parent.children[myIndex - 1];
}
get nextSibling() {
const { parent } = this;
if (!parent) {
let event = this.next;
// Get the next root level event
while (event) {
if (event.isCall() && !event.parent) {
return event;
}
event = event.next;
}
return null;
}
const myIndex = this.parent.children.findIndex((e) => e === this);
console.assert(myIndex !== -1, 'attempted to locate index of an orphaned event');
if (myIndex === parent.children.length - 1) {
return null;
}
return parent.children[myIndex + 1];
}
set codeObject(value) {
if (hasProp(this.$hidden, 'codeObject')) {
this.$hidden.codeObject = value;
}
}
set parameters(value) {
if (hasProp(this.$hidden, 'parameters')) {
this.$hidden.parameters = value;
}
}
set labels(value) {
if (hasProp(this.$hidden, 'labels')) {
this.$hidden.labels = value;
}
}
set exceptions(value) {
if (hasProp(this.$hidden, 'exceptions')) {
this.$hidden.exceptions = value;
}
}
set message(value) {
if (hasProp(this.$hidden, 'message')) {
this.$hidden.message = value;
}
}
set linkedEvent(value) {
this.$hidden.linkedEvent = value;
}
set next(value) {
this.$hidden.next = value;
}
set previous(value) {
this.$hidden.previous = value;
}
set parent(value) {
this.$hidden.parent = value;
}
link(event) {
/* eslint-disable no-param-reassign */
if (event.linkedEvent || this.linkedEvent) {
return;
}
event.linkedEvent = this;
this.linkedEvent = event;
/* eslint-enable no-param-reassign */
}
isCall() {
return this.event === 'call';
}
isReturn() {
return this.event === 'return';
}
get threadId() {
return this.thread_id;
}
get parentId() {
return this.returnEvent ? this.returnEvent.parent_id : undefined;
}
get callEvent() {
return this.isCall() ? this : this.$hidden.linkedEvent;
}
get returnEvent() {
return this.isReturn() ? this : this.$hidden.linkedEvent;
}
get identityHash() {
if (!this.$hidden.identityHash) {
this.$hidden.identityHash = this.buildIdentityHash().digest();
}
return this.$hidden.identityHash;
}
get hash() {
if (!this.$hidden.hash) {
this.$hidden.hash = this.buildStableHash().digest();
}
return this.$hidden.hash;
}
get stableProperties() {
if (!this.$hidden.stableProperties) {
this.$hidden.stableProperties = this.gatherStableProperties();
}
return this.$hidden.stableProperties;
}
callStack() {
const stack = this.ancestors().reverse();
stack.push(this.callEvent);
return stack;
}
ancestors() {
const ancestorArray = [];
let event = this.callEvent.parent;
while (event) {
ancestorArray.push(event);
event = event.parent;
}
return ancestorArray;
}
descendants() {
const descendantArray = [];
const queue = [...this.children];
while (queue.length) {
const event = queue.pop();
event.children.forEach((child) => queue.push(child));
descendantArray.push(event);
}
return descendantArray;
}
traverse(fn) {
let event = this;
const boundaryEvent = this.nextSibling;
let { onEnter } = fn;
let { onExit } = fn;
if (typeof fn === 'function') {
onEnter = fn;
onExit = fn;
}
while (event) {
if (event.isCall() && onEnter) {
onEnter(event);
} else if (event.isReturn() && onExit) {
onExit(event);
}
event = event.next;
if (!event || event === boundaryEvent) {
break;
}
}
}
dataObjects() {
return [this.parameters, this.message, this.returnValue].flat().filter(Boolean);
}
get qualifiedMethodId() {
const { definedClass, isStatic, methodId } = this;
if (!definedClass) return undefined;
return `${definedClass}${isStatic ? '.' : '#'}${methodId}`;
}
toJSON() {
return transformToJSON(this.dataKeys, this);
}
toString() {
const { sqlQuery } = this;
if (sqlQuery) {
return sqlQuery;
}
const { route } = this;
if (route) {
return route;
}
return this.qualifiedMethodId;
}
// Returns canonical properties tied to the event's core identity: SQL, HTTP, or a
// specific method on a specific class. Identity properties are used to identify events that are
// added/removed between two AppMaps, as opposed to changes. If two events share the same
// identity properties, they won't be reported as an add/remove, but may be reported as a change.
gatherIdentityProperties() {
if (this.httpServerRequest) {
return { event_type: 'http_server_request', route: this.route };
}
if (this.httpClientRequest) {
return { event_type: 'http_client_request', route: this.route };
}
const { sqlQuery } = this;
if (sqlQuery) {
const queryOps = analyzeSQL(sqlQuery);
if (!queryOps)
return {
event_type: 'sql',
sql_normalized: normalizeSQL(sqlQuery, this.sql.database_type),
}; // Best we can do
return {
event_type: 'sql',
actions: [...new Set(queryOps.actions)].sort(),
tables: [...new Set(queryOps.tables)].sort(),
};
}
return {
event_type: 'function',
id: this.codeObject.id,
};
}
// Collects properties of an event which are not dependent on the specifics
// of invocation.
gatherStableProperties(parsedSqlCache) {
const { sqlQuery } = this;
// Convert null and undefined values to empty strings
const normalizeProperties = (/** @type{Record<string,string>} */ properties) =>
Object.fromEntries(
Object.entries(properties).map(([key, value]) => [
key,
value === undefined || value === null ? '' : value,
])
);
// Augment a set of base properties with HTTP client/server request properties.
const requestProperties = (/** @type{Record<string,string>} */ baseProperties) =>
Object.assign(baseProperties, {
route: this.route,
status_code:
this.httpServerResponse?.status ||
this.httpServerResponse?.status_code ||
this.httpClientResponse?.status ||
this.httpServerResponse?.status_code,
});
let properties;
if (sqlQuery) {
let sqlNormalized;
const cacheKey = `${this.sql.database_type}:${sqlQuery}`;
if (parsedSqlCache) sqlNormalized = parsedSqlCache.get(cacheKey);
if (!sqlNormalized) {
sqlNormalized = abstractSqlAstJSON(sqlQuery, this.sql.database_type)
// Collapse repeated variable literals and parameter tokens (e.g. '?, ?' in an IN clause)
.split(/{"type":"variable"}(?:,{"type":"variable"})*/g)
.join(`{"type":"variable"}`);
if (parsedSqlCache) parsedSqlCache.set(cacheKey, sqlNormalized);
}
properties = {
event_type: 'sql',
sql_normalized: sqlNormalized,
};
} else if (this.httpServerRequest) {
properties = requestProperties({ event_type: 'http_server_request' });
} else if (this.httpClientRequest) {
properties = requestProperties({
event_type: 'http_client_request',
});
} else {
properties = {
event_type: 'function',
id: this.codeObject.id,
raises_exception: this.exceptions.length > 0,
};
}
return normalizeProperties(properties);
}
buildIdentityHash() {
return HashBuilder.buildHash('event-identity-v2', this.gatherIdentityProperties());
}
buildStableHash(parsedSqlCache) {
return HashBuilder.buildHash(
'event-stable-properties-v2',
this.gatherStableProperties(parsedSqlCache)
);
}
}