/
base_span.ts
102 lines (83 loc) · 2.49 KB
/
base_span.ts
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { Serializable } from '../serializable';
import { Span } from './span';
import { Transaction } from './transaction';
import { generateLongId } from '../utils/generate_id';
import { ApmFields } from './apm_fields';
export class BaseSpan extends Serializable<ApmFields> {
private readonly _children: BaseSpan[] = [];
constructor(fields: ApmFields) {
super({
...fields,
'event.outcome': 'unknown',
'trace.id': generateLongId(),
'processor.name': 'transaction',
});
}
parent(span: BaseSpan): this {
this.fields['trace.id'] = span.fields['trace.id'];
this.fields['parent.id'] = span.isSpan()
? span.fields['span.id']
: span.fields['transaction.id'];
if (this.isSpan()) {
this.fields['transaction.id'] = span.fields['transaction.id'];
}
this._children.forEach((child) => {
child.parent(this);
});
return this;
}
getChildren() {
return this._children;
}
children(...children: BaseSpan[]): this {
children.forEach((child) => {
child.parent(this);
});
this._children.push(...children);
return this;
}
success(): this {
this.fields['event.outcome'] = 'success';
return this;
}
failure(): this {
this.fields['event.outcome'] = 'failure';
return this;
}
outcome(outcome: 'success' | 'failure' | 'unknown'): this {
this.fields['event.outcome'] = outcome;
return this;
}
crash(): this {
this.fields['event.name'] = 'crash';
return this;
}
serialize(): ApmFields[] {
return [this.fields, ...this._children.flatMap((child) => child.serialize())];
}
isSpan(): this is Span {
return this.fields['processor.event'] === 'span';
}
isTransaction(): this is Transaction {
return this.fields['processor.event'] === 'transaction';
}
labels(labels: Record<string, string>) {
Object.entries(labels).forEach(([key, value]) => {
// @ts-expect-error
this.fields[`labels.${key}`] = value;
});
return this;
}
override timestamp(timestamp: number) {
const ret = super.timestamp(timestamp);
this.fields['timestamp.us'] = timestamp * 1000;
return ret;
}
}