@nestjs/observe 0.0.1 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.js +98 -1
- package/dist/agent/observe-agent.shared-buffer.d.ts +82 -0
- package/dist/agent/observe-agent.shared-buffer.js +94 -3
- package/dist/agent/observe-agent.worker.d.ts +28 -0
- package/dist/agent/observe-agent.worker.js +59 -5
- package/dist/custom-metrics/counter.d.ts +124 -0
- package/dist/custom-metrics/counter.js +93 -0
- package/dist/custom-metrics/gauge.d.ts +116 -0
- package/dist/custom-metrics/gauge.js +55 -0
- package/dist/custom-metrics/summary.d.ts +102 -0
- package/dist/custom-metrics/summary.js +100 -0
- package/dist/encoders/custom-metrics.encoder.js +18 -0
- package/dist/encoders/remap-keys.util.d.ts +11 -0
- package/dist/encoders/remap-keys.util.js +15 -0
- package/dist/encoders/trace.encoder.d.ts +7 -0
- package/dist/encoders/trace.encoder.js +12 -0
- package/dist/instrument/create-instance-decorator.instrument.d.ts +8 -0
- package/dist/instrument/create-instance-decorator.instrument.js +67 -0
- package/dist/interfaces/custom-metric.interface.d.ts +74 -0
- package/dist/interfaces/graphql.interfaces.d.ts +16 -0
- package/dist/interfaces/job-snapshot.interface.d.ts +70 -0
- package/dist/interfaces/node-runtime-metrics.interface.d.ts +5 -0
- package/dist/interfaces/observe-options.interface.d.ts +358 -0
- package/dist/interfaces/request-snapshot.interface.d.ts +62 -0
- package/dist/interfaces/trace-events.interfaces.d.ts +51 -0
- package/dist/interfaces/trace-span.interface.d.ts +29 -0
- package/dist/observe.module.js +29 -0
- package/dist/profiling/cpu-profiler.service.d.ts +65 -0
- package/dist/profiling/cpu-profiler.service.js +80 -0
- package/dist/profiling/fold-profile.util.d.ts +20 -0
- package/dist/profiling/fold-profile.util.js +0 -0
- package/dist/profiling/profile-uploader.d.ts +26 -0
- package/dist/profiling/profile-uploader.js +52 -0
- package/dist/profiling/span-slice-recorder.d.ts +51 -0
- package/dist/profiling/span-slice-recorder.js +77 -0
- package/dist/protocols/graphql-observe-agent.service.d.ts +128 -0
- package/dist/protocols/graphql-observe-agent.service.js +166 -0
- package/dist/protocols/graphql-operation-parser.d.ts +26 -0
- package/dist/protocols/graphql-operation-parser.js +66 -0
- package/dist/protocols/http-observe-agent.service.d.ts +19 -0
- package/dist/protocols/http-observe-agent.service.js +34 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +8 -0
- package/dist/protocols/queue-observe-agent.service.js +32 -0
- package/dist/protocols/rpc-observe-agent.service.d.ts +7 -0
- package/dist/protocols/rpc-observe-agent.service.js +12 -0
- package/dist/services/logger-patcher.service.d.ts +4 -0
- package/dist/services/logger-patcher.service.js +13 -1
- package/dist/services/node-runtime-metrics.service.js +24 -8
- package/dist/services/operation-trace.registry.d.ts +56 -1
- package/dist/services/operation-trace.registry.js +145 -6
- package/dist/services/stdout-forwarder.service.d.ts +19 -0
- package/dist/services/stdout-forwarder.service.js +62 -0
- package/dist/services/trace-sampler.service.d.ts +6 -0
- package/dist/services/trace-sampler.service.js +3 -3
- package/dist/services/tracer.service.d.ts +91 -0
- package/dist/services/tracer.service.js +56 -1
- package/dist/trace-span.delegate.d.ts +11 -0
- package/dist/trace-span.delegate.js +11 -0
- package/dist/types/path-value.type.d.ts +4 -0
- package/dist/utils/default-trace-id-generator.util.js +11 -0
- package/dist/utils/log-line.parser.d.ts +14 -0
- package/dist/utils/log-line.parser.js +37 -0
- package/dist/utils/log-redactor.js +65 -0
- package/dist/utils/redact-url-query.d.ts +17 -0
- package/dist/utils/redact-url-query.js +38 -0
- package/dist/utils/source-context.util.d.ts +22 -0
- package/dist/utils/source-context.util.js +60 -0
- package/dist/utils/source-map-resolver.util.d.ts +13 -0
- package/dist/utils/source-map-resolver.util.js +26 -28
- package/package.json +1 -1
|
@@ -1,27 +1,102 @@
|
|
|
1
1
|
import { CustomMetric } from "../interfaces/custom-metric.interface.js";
|
|
2
2
|
declare const DEFAULT_LABEL: "default";
|
|
3
|
+
/**
|
|
4
|
+
* A distribution of observations - request latency being the usual case.
|
|
5
|
+
*
|
|
6
|
+
* Quantiles are computed here, in-process, over the observations seen since the
|
|
7
|
+
* last flush; the backend only ever receives finished numbers. That keeps the
|
|
8
|
+
* payload flat and small, at the cost of quantiles that cannot be merged exactly
|
|
9
|
+
* across instances - the backend averages them, which estimates rather than
|
|
10
|
+
* derives the true percentile. `observations`, `total` and `maximum` carry no
|
|
11
|
+
* such caveat: they merge exactly, so a mean and a worst case built from them
|
|
12
|
+
* stay truthful across any number of reporters.
|
|
13
|
+
*/
|
|
3
14
|
export declare class Summary<TLabel extends string = typeof DEFAULT_LABEL> implements CustomMetric<TLabel> {
|
|
15
|
+
/**
|
|
16
|
+
* The name of the summary.
|
|
17
|
+
* This should be a descriptive name that identifies the distribution.
|
|
18
|
+
* For example, "http_request_duration_ms" or "db_query_duration_ms".
|
|
19
|
+
*/
|
|
4
20
|
readonly name: string;
|
|
21
|
+
/**
|
|
22
|
+
* The type of the custom metric.
|
|
23
|
+
* This is always 'summary' for this class.
|
|
24
|
+
*/
|
|
5
25
|
readonly type: "summary";
|
|
26
|
+
/**
|
|
27
|
+
* A brief description of the summary's purpose.
|
|
28
|
+
* For example, "Request latency in milliseconds".
|
|
29
|
+
*/
|
|
6
30
|
readonly description?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Optional labels for the summary.
|
|
33
|
+
* Each label accumulates its own independent distribution.
|
|
34
|
+
*/
|
|
7
35
|
readonly labels?: TLabel[];
|
|
8
36
|
private _tags?;
|
|
9
37
|
private _onChange?;
|
|
10
38
|
private _lastUpdated;
|
|
11
39
|
private readonly _sampleSize;
|
|
40
|
+
/**
|
|
41
|
+
* Exact per-label aggregates for the current window. Tracked apart from the
|
|
42
|
+
* sample below so they describe every observation, not just the retained ones.
|
|
43
|
+
*/
|
|
12
44
|
private _count;
|
|
13
45
|
private _sum;
|
|
14
46
|
private _max;
|
|
47
|
+
/**
|
|
48
|
+
* Bounded per-label sample the quantiles are read off.
|
|
49
|
+
*/
|
|
15
50
|
private _samples;
|
|
51
|
+
/**
|
|
52
|
+
* The medians, doubling as the metric's headline reading.
|
|
53
|
+
*
|
|
54
|
+
* A distribution has no single value, so this is what stands in wherever one
|
|
55
|
+
* number is needed. It is a getter, which means `for...in` cannot see it and
|
|
56
|
+
* the encoder leaves it off the wire - the backend derives the same figure
|
|
57
|
+
* from the reported median instead of carrying it twice.
|
|
58
|
+
*/
|
|
16
59
|
get value(): Record<string, number>;
|
|
60
|
+
/**
|
|
61
|
+
* Median per label over the observations since the last flush.
|
|
62
|
+
*/
|
|
17
63
|
get p50(): Record<string, number>;
|
|
64
|
+
/**
|
|
65
|
+
* 95th percentile per label over the observations since the last flush.
|
|
66
|
+
*/
|
|
18
67
|
get p95(): Record<string, number>;
|
|
68
|
+
/**
|
|
69
|
+
* 99th percentile per label over the observations since the last flush.
|
|
70
|
+
*/
|
|
19
71
|
get p99(): Record<string, number>;
|
|
72
|
+
/**
|
|
73
|
+
* How many observations each label saw since the last flush. Exact - this
|
|
74
|
+
* counts every observation, including those the sample dropped.
|
|
75
|
+
*/
|
|
20
76
|
get observations(): Record<string, number>;
|
|
77
|
+
/**
|
|
78
|
+
* Sum of every observation per label since the last flush. Exact. Paired with
|
|
79
|
+
* `observations` it gives the backend a true mean across all reporters, which
|
|
80
|
+
* the quantiles cannot provide.
|
|
81
|
+
*/
|
|
21
82
|
get total(): Record<string, number>;
|
|
83
|
+
/**
|
|
84
|
+
* Largest single observation per label since the last flush. Exact, and it
|
|
85
|
+
* merges exactly, so the worst case survives being combined across instances.
|
|
86
|
+
*/
|
|
22
87
|
get maximum(): Record<string, number>;
|
|
88
|
+
/**
|
|
89
|
+
* Gets the timestamp of when the summary was last updated.
|
|
90
|
+
* This is a Unix timestamp in milliseconds.
|
|
91
|
+
*/
|
|
23
92
|
get lastUpdated(): number;
|
|
93
|
+
/**
|
|
94
|
+
* Gets tags associated with the summary.
|
|
95
|
+
*/
|
|
24
96
|
get tags(): Record<string, string> | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* Sets tags for the summary.
|
|
99
|
+
*/
|
|
25
100
|
set tags(tags: Record<string, string> | undefined);
|
|
26
101
|
constructor(name: string);
|
|
27
102
|
constructor(name: string, attributes: {
|
|
@@ -29,10 +104,37 @@ export declare class Summary<TLabel extends string = typeof DEFAULT_LABEL> imple
|
|
|
29
104
|
labels?: TLabel[];
|
|
30
105
|
sampleSize?: number;
|
|
31
106
|
});
|
|
107
|
+
/**
|
|
108
|
+
* Records an observation against the default label.
|
|
109
|
+
* @param value The observed value, for example a duration in milliseconds.
|
|
110
|
+
*/
|
|
32
111
|
observe(value: number): void;
|
|
112
|
+
/**
|
|
113
|
+
* Records an observation against a specific label.
|
|
114
|
+
* @param value The observed value, for example a duration in milliseconds.
|
|
115
|
+
* @param label One of the labels the summary was declared with.
|
|
116
|
+
*/
|
|
33
117
|
observe(value: number, label: TLabel): void;
|
|
118
|
+
/**
|
|
119
|
+
* Starts a fresh window.
|
|
120
|
+
*
|
|
121
|
+
* Called by the agent only once a flush has actually been written, so a failed
|
|
122
|
+
* flush leaves the window intact and its observations roll into the next one
|
|
123
|
+
* rather than being thrown away.
|
|
124
|
+
*/
|
|
34
125
|
markFlushed(): void;
|
|
126
|
+
/**
|
|
127
|
+
* Keeps the retained sample uniform over the whole window (Algorithm R).
|
|
128
|
+
*
|
|
129
|
+
* Once the reservoir is full each further observation replaces a random slot
|
|
130
|
+
* with probability sampleSize/count, which leaves every observation equally
|
|
131
|
+
* likely to be present - so quantiles read off the sample stay representative
|
|
132
|
+
* however far throughput outruns the reservoir.
|
|
133
|
+
*/
|
|
35
134
|
private sample;
|
|
135
|
+
/**
|
|
136
|
+
* Nearest-rank quantile per label, read off a sorted copy of the sample.
|
|
137
|
+
*/
|
|
36
138
|
private quantile;
|
|
37
139
|
}
|
|
38
140
|
export {};
|
|
@@ -1,45 +1,127 @@
|
|
|
1
1
|
const DEFAULT_LABEL = "default";
|
|
2
|
+
/**
|
|
3
|
+
* How many observations per label are kept to compute quantiles from.
|
|
4
|
+
*
|
|
5
|
+
* A summary must not grow with throughput, so observations past this are
|
|
6
|
+
* reservoir-sampled rather than appended. The count, sum and maximum are tracked
|
|
7
|
+
* separately and stay exact however many observations arrive.
|
|
8
|
+
*/
|
|
2
9
|
const DEFAULT_SAMPLE_SIZE = 2048;
|
|
10
|
+
/**
|
|
11
|
+
* A distribution of observations - request latency being the usual case.
|
|
12
|
+
*
|
|
13
|
+
* Quantiles are computed here, in-process, over the observations seen since the
|
|
14
|
+
* last flush; the backend only ever receives finished numbers. That keeps the
|
|
15
|
+
* payload flat and small, at the cost of quantiles that cannot be merged exactly
|
|
16
|
+
* across instances - the backend averages them, which estimates rather than
|
|
17
|
+
* derives the true percentile. `observations`, `total` and `maximum` carry no
|
|
18
|
+
* such caveat: they merge exactly, so a mean and a worst case built from them
|
|
19
|
+
* stay truthful across any number of reporters.
|
|
20
|
+
*/
|
|
3
21
|
export class Summary {
|
|
22
|
+
/**
|
|
23
|
+
* The name of the summary.
|
|
24
|
+
* This should be a descriptive name that identifies the distribution.
|
|
25
|
+
* For example, "http_request_duration_ms" or "db_query_duration_ms".
|
|
26
|
+
*/
|
|
4
27
|
name;
|
|
28
|
+
/**
|
|
29
|
+
* The type of the custom metric.
|
|
30
|
+
* This is always 'summary' for this class.
|
|
31
|
+
*/
|
|
5
32
|
type;
|
|
33
|
+
/**
|
|
34
|
+
* A brief description of the summary's purpose.
|
|
35
|
+
* For example, "Request latency in milliseconds".
|
|
36
|
+
*/
|
|
6
37
|
description;
|
|
38
|
+
/**
|
|
39
|
+
* Optional labels for the summary.
|
|
40
|
+
* Each label accumulates its own independent distribution.
|
|
41
|
+
*/
|
|
7
42
|
labels;
|
|
8
43
|
_tags;
|
|
9
44
|
_onChange;
|
|
10
45
|
_lastUpdated = Date.now();
|
|
11
46
|
_sampleSize;
|
|
47
|
+
/**
|
|
48
|
+
* Exact per-label aggregates for the current window. Tracked apart from the
|
|
49
|
+
* sample below so they describe every observation, not just the retained ones.
|
|
50
|
+
*/
|
|
12
51
|
_count = {};
|
|
13
52
|
_sum = {};
|
|
14
53
|
_max = {};
|
|
54
|
+
/**
|
|
55
|
+
* Bounded per-label sample the quantiles are read off.
|
|
56
|
+
*/
|
|
15
57
|
_samples = {};
|
|
58
|
+
/**
|
|
59
|
+
* The medians, doubling as the metric's headline reading.
|
|
60
|
+
*
|
|
61
|
+
* A distribution has no single value, so this is what stands in wherever one
|
|
62
|
+
* number is needed. It is a getter, which means `for...in` cannot see it and
|
|
63
|
+
* the encoder leaves it off the wire - the backend derives the same figure
|
|
64
|
+
* from the reported median instead of carrying it twice.
|
|
65
|
+
*/
|
|
16
66
|
get value() {
|
|
17
67
|
return this.quantile(0.5);
|
|
18
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Median per label over the observations since the last flush.
|
|
71
|
+
*/
|
|
19
72
|
get p50() {
|
|
20
73
|
return this.quantile(0.5);
|
|
21
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* 95th percentile per label over the observations since the last flush.
|
|
77
|
+
*/
|
|
22
78
|
get p95() {
|
|
23
79
|
return this.quantile(0.95);
|
|
24
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* 99th percentile per label over the observations since the last flush.
|
|
83
|
+
*/
|
|
25
84
|
get p99() {
|
|
26
85
|
return this.quantile(0.99);
|
|
27
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* How many observations each label saw since the last flush. Exact - this
|
|
89
|
+
* counts every observation, including those the sample dropped.
|
|
90
|
+
*/
|
|
28
91
|
get observations() {
|
|
29
92
|
return { ...this._count };
|
|
30
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Sum of every observation per label since the last flush. Exact. Paired with
|
|
96
|
+
* `observations` it gives the backend a true mean across all reporters, which
|
|
97
|
+
* the quantiles cannot provide.
|
|
98
|
+
*/
|
|
31
99
|
get total() {
|
|
32
100
|
return { ...this._sum };
|
|
33
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Largest single observation per label since the last flush. Exact, and it
|
|
104
|
+
* merges exactly, so the worst case survives being combined across instances.
|
|
105
|
+
*/
|
|
34
106
|
get maximum() {
|
|
35
107
|
return { ...this._max };
|
|
36
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* Gets the timestamp of when the summary was last updated.
|
|
111
|
+
* This is a Unix timestamp in milliseconds.
|
|
112
|
+
*/
|
|
37
113
|
get lastUpdated() {
|
|
38
114
|
return this._lastUpdated;
|
|
39
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Gets tags associated with the summary.
|
|
118
|
+
*/
|
|
40
119
|
get tags() {
|
|
41
120
|
return this._tags;
|
|
42
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* Sets tags for the summary.
|
|
124
|
+
*/
|
|
43
125
|
set tags(tags) {
|
|
44
126
|
if (tags && typeof tags !== "object") {
|
|
45
127
|
throw new Error("Tags must be an object with key-value pairs.");
|
|
@@ -74,12 +156,27 @@ export class Summary {
|
|
|
74
156
|
this._onChange(this);
|
|
75
157
|
}
|
|
76
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Starts a fresh window.
|
|
161
|
+
*
|
|
162
|
+
* Called by the agent only once a flush has actually been written, so a failed
|
|
163
|
+
* flush leaves the window intact and its observations roll into the next one
|
|
164
|
+
* rather than being thrown away.
|
|
165
|
+
*/
|
|
77
166
|
markFlushed() {
|
|
78
167
|
this._count = {};
|
|
79
168
|
this._sum = {};
|
|
80
169
|
this._max = {};
|
|
81
170
|
this._samples = {};
|
|
82
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Keeps the retained sample uniform over the whole window (Algorithm R).
|
|
174
|
+
*
|
|
175
|
+
* Once the reservoir is full each further observation replaces a random slot
|
|
176
|
+
* with probability sampleSize/count, which leaves every observation equally
|
|
177
|
+
* likely to be present - so quantiles read off the sample stay representative
|
|
178
|
+
* however far throughput outruns the reservoir.
|
|
179
|
+
*/
|
|
83
180
|
sample(key, value, count) {
|
|
84
181
|
const samples = (this._samples[key] ??= []);
|
|
85
182
|
if (samples.length < this._sampleSize) {
|
|
@@ -91,6 +188,9 @@ export class Summary {
|
|
|
91
188
|
samples[slot] = value;
|
|
92
189
|
}
|
|
93
190
|
}
|
|
191
|
+
/**
|
|
192
|
+
* Nearest-rank quantile per label, read off a sorted copy of the sample.
|
|
193
|
+
*/
|
|
94
194
|
quantile(percentile) {
|
|
95
195
|
const quantiles = {};
|
|
96
196
|
for (const [key, samples] of Object.entries(this._samples)) {
|
|
@@ -16,6 +16,11 @@ const CUSTOM_METRICS_KEY_MAP = {
|
|
|
16
16
|
total: "sm",
|
|
17
17
|
maximum: "mx",
|
|
18
18
|
};
|
|
19
|
+
/**
|
|
20
|
+
* Summary fields that live on the prototype as getters, in the order they are
|
|
21
|
+
* copied across. `value` is deliberately absent: it is the median again, which
|
|
22
|
+
* the backend derives from `q50` rather than carrying twice.
|
|
23
|
+
*/
|
|
19
24
|
const SUMMARY_KEYS = [
|
|
20
25
|
"p50",
|
|
21
26
|
"p95",
|
|
@@ -27,6 +32,11 @@ const SUMMARY_KEYS = [
|
|
|
27
32
|
export class CustomMetricsEncoder {
|
|
28
33
|
static encode(metric) {
|
|
29
34
|
const encoded = remapKeys(metric, CUSTOM_METRICS_KEY_MAP);
|
|
35
|
+
// `tags` and `lastUpdated` are class getters on every metric class, and
|
|
36
|
+
// getters live on the prototype where for...in cannot see them, so they
|
|
37
|
+
// have to be copied across explicitly - same for the per-type getters
|
|
38
|
+
// below. (Plain-object metrics carry them as own properties and are
|
|
39
|
+
// already handled by the loop above; the assignments repeat harmlessly.)
|
|
30
40
|
if (metric.tags) {
|
|
31
41
|
encoded.tg = metric.tags;
|
|
32
42
|
}
|
|
@@ -36,10 +46,18 @@ export class CustomMetricsEncoder {
|
|
|
36
46
|
if (metric.type === "counter" && metric.increase) {
|
|
37
47
|
encoded.iv = metric.increase;
|
|
38
48
|
}
|
|
49
|
+
// A summary's whole payload is getters, for the same reason. An empty map
|
|
50
|
+
// means the window was flushed and nothing has been observed since, which is
|
|
51
|
+
// not worth a row - leave the key off entirely rather than reporting a
|
|
52
|
+
// distribution that does not exist.
|
|
39
53
|
if (metric.type === "summary") {
|
|
40
54
|
for (const key of SUMMARY_KEYS) {
|
|
41
55
|
const value = metric[key];
|
|
42
56
|
if (value && Object.keys(value).length > 0) {
|
|
57
|
+
// One cast for the whole loop: `SUMMARY_KEYS` and the key map are
|
|
58
|
+
// both keyed by `CustomMetric`, so the target property is known to
|
|
59
|
+
// exist, but the pairing is not something the compiler can follow
|
|
60
|
+
// through the indirection.
|
|
43
61
|
encoded[CUSTOM_METRICS_KEY_MAP[key]] =
|
|
44
62
|
value;
|
|
45
63
|
}
|
|
@@ -1 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copies the properties a key map names onto a new object under their shortened
|
|
3
|
+
* wire names, skipping anything the map does not mention.
|
|
4
|
+
*
|
|
5
|
+
* Every encoder does this, at every level of its payload. Written out inline it
|
|
6
|
+
* indexes a precisely-typed result with a `string`, which needs an implicit
|
|
7
|
+
* `any` at each assignment - twenty-nine of them across the four encoders under
|
|
8
|
+
* `strict`. Centralising it puts the one unavoidable cast in a single place:
|
|
9
|
+
* callers name the encoded type, and the key maps' `satisfies` clauses are what
|
|
10
|
+
* prove the mapping covers every field of the source.
|
|
11
|
+
*/
|
|
1
12
|
export declare function remapKeys<TSource extends object, TEncoded>(source: TSource, keyMap: Partial<Record<keyof TSource, string>>): TEncoded;
|
|
@@ -1,5 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copies the properties a key map names onto a new object under their shortened
|
|
3
|
+
* wire names, skipping anything the map does not mention.
|
|
4
|
+
*
|
|
5
|
+
* Every encoder does this, at every level of its payload. Written out inline it
|
|
6
|
+
* indexes a precisely-typed result with a `string`, which needs an implicit
|
|
7
|
+
* `any` at each assignment - twenty-nine of them across the four encoders under
|
|
8
|
+
* `strict`. Centralising it puts the one unavoidable cast in a single place:
|
|
9
|
+
* callers name the encoded type, and the key maps' `satisfies` clauses are what
|
|
10
|
+
* prove the mapping covers every field of the source.
|
|
11
|
+
*/
|
|
1
12
|
export function remapKeys(source, keyMap) {
|
|
2
13
|
const encoded = {};
|
|
14
|
+
// `for...in` rather than `Object.keys`, matching what the encoders did before:
|
|
15
|
+
// the sources are plain payload objects, and metric classes keep their getters
|
|
16
|
+
// on the prototype where neither form can see them - those are copied across
|
|
17
|
+
// explicitly by `CustomMetricsEncoder`.
|
|
3
18
|
for (const key in source) {
|
|
4
19
|
const mapped = keyMap[key];
|
|
5
20
|
if (mapped) {
|
|
@@ -16,4 +16,11 @@ export type RecursiveEncodedTrace = Omit<{
|
|
|
16
16
|
}, "ch"> & {
|
|
17
17
|
ch?: Array<RecursiveEncodedTrace>;
|
|
18
18
|
};
|
|
19
|
+
/**
|
|
20
|
+
* Encodes one span and everything below it.
|
|
21
|
+
*
|
|
22
|
+
* Shared by the request and job encoders rather than duplicated in each: both
|
|
23
|
+
* kinds of operation produce the same span shape, so a reader sees one format
|
|
24
|
+
* whichever produced it, and `encoders.spec.ts` asserts exactly that.
|
|
25
|
+
*/
|
|
19
26
|
export declare function encodeTrace(trace: CompleteTraceEventNode): RecursiveEncodedTrace;
|
|
@@ -11,8 +11,20 @@ export const TRACE_KEY_MAP = {
|
|
|
11
11
|
spanId: "s",
|
|
12
12
|
startOffset: "so",
|
|
13
13
|
};
|
|
14
|
+
/**
|
|
15
|
+
* Encodes one span and everything below it.
|
|
16
|
+
*
|
|
17
|
+
* Shared by the request and job encoders rather than duplicated in each: both
|
|
18
|
+
* kinds of operation produce the same span shape, so a reader sees one format
|
|
19
|
+
* whichever produced it, and `encoders.spec.ts` asserts exactly that.
|
|
20
|
+
*/
|
|
14
21
|
export function encodeTrace(trace) {
|
|
15
22
|
const encoded = remapKeys(trace, TRACE_KEY_MAP);
|
|
23
|
+
// Outside the key remapping above, deliberately. Done inside that loop, every
|
|
24
|
+
// own key of a node re-encoded that node's whole subtree, so the work was
|
|
25
|
+
// keys^depth rather than one visit per node - a trace a few levels deeper
|
|
26
|
+
// than a plain HTTP request (a queued job that authenticates, submits and
|
|
27
|
+
// polls) pinned the event loop and never came back.
|
|
16
28
|
if (trace.children && trace.children.length > 0) {
|
|
17
29
|
encoded.ch = trace.children.map((child) => encodeTrace(child));
|
|
18
30
|
}
|
|
@@ -2,6 +2,14 @@ import { AsyncLocalStorage } from "async_hooks";
|
|
|
2
2
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
3
3
|
import { KeyOf } from "../types/key-of.type.js";
|
|
4
4
|
export declare function createInstanceDecorator<T extends Record<string, unknown>>(als: AsyncLocalStorage<Map<KeyOf<T>, any>>, operationTraceRegistry: OperationTraceRegistry, options: {
|
|
5
|
+
/**
|
|
6
|
+
* The trace ID key used to identify the trace in the context.
|
|
7
|
+
* This key is used to store the trace ID in the context for later retrieval.
|
|
8
|
+
*/
|
|
5
9
|
traceIdKey: string;
|
|
10
|
+
/**
|
|
11
|
+
* A function to determine whether to skip instrumentation for a given instance.
|
|
12
|
+
* This function should return true if the instance should not be instrumented.
|
|
13
|
+
*/
|
|
6
14
|
skipInstrumentation: (instance: unknown) => boolean;
|
|
7
15
|
}): (instance: unknown) => any;
|
|
@@ -1,12 +1,30 @@
|
|
|
1
1
|
import { CALLER_METADATA_KEY } from "../observe.constants.js";
|
|
2
|
+
/**
|
|
3
|
+
* Stand-in "class name" for instrumented standalone functions. Unlike methods,
|
|
4
|
+
* they have no enclosing class to borrow a name from, so every span they emit
|
|
5
|
+
* is grouped under this label.
|
|
6
|
+
*/
|
|
2
7
|
const STANDALONE_FUNCTION_LABEL = "Function";
|
|
3
8
|
export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
9
|
+
/**
|
|
10
|
+
* Builds the tracing wrapper shared by methods and standalone functions.
|
|
11
|
+
*
|
|
12
|
+
* Every function this creates is named `<className>.<methodName>`, so the
|
|
13
|
+
* frames instrumentation contributes to a stack trace read like the call the
|
|
14
|
+
* user actually made instead of `Proxy.proxyFn`.
|
|
15
|
+
*/
|
|
4
16
|
const createTracedWrapper = (spec) => {
|
|
5
17
|
const { className, methodName, spanId } = spec;
|
|
6
18
|
const frameName = `${className}.${methodName}`;
|
|
19
|
+
// Pulled out of `spec` so they are invoked as plain functions: calling them
|
|
20
|
+
// as `spec.call(...)` would make `spec` the frame's receiver and print
|
|
21
|
+
// "Object.<name>".
|
|
7
22
|
const call = spec.call;
|
|
8
23
|
const callUntraced = spec.callUntraced;
|
|
24
|
+
// A function expression, not an arrow: the wrapper has to forward whatever
|
|
25
|
+
// `this` the caller invoked it with. Nested arrows below inherit it.
|
|
9
26
|
return named(frameName, function (...args) {
|
|
27
|
+
// Already tracing this callable, invoke it as-is
|
|
10
28
|
if (spec.isActive()) {
|
|
11
29
|
return callUntraced(this, args);
|
|
12
30
|
}
|
|
@@ -23,8 +41,13 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
23
41
|
return res;
|
|
24
42
|
};
|
|
25
43
|
const onError = (err) => {
|
|
44
|
+
// Before the registry records the step: `internalEndTraceStep` copies
|
|
45
|
+
// `err.stack` into the span payload (and, on a root span, into the
|
|
46
|
+
// snapshot that becomes the error group's sample), so relabelling
|
|
47
|
+
// afterwards would leave that copy carrying this frame's `Proxy.`.
|
|
26
48
|
relabelProxyFrame(err, className, methodName);
|
|
27
49
|
operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId, err);
|
|
50
|
+
// Re-throw the error to maintain original behavior
|
|
28
51
|
throw err;
|
|
29
52
|
};
|
|
30
53
|
return als.run(new Map([
|
|
@@ -48,12 +71,16 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
48
71
|
});
|
|
49
72
|
};
|
|
50
73
|
const instrumentFunction = (fn) => {
|
|
74
|
+
// Classes are functions too, but calling one is a construction, not the
|
|
75
|
+
// kind of call this decorator traces.
|
|
51
76
|
if (isClass(fn) || options.skipInstrumentation(fn)) {
|
|
52
77
|
return fn;
|
|
53
78
|
}
|
|
54
79
|
const methodName = fn.name || "anonymous";
|
|
55
80
|
const className = STANDALONE_FUNCTION_LABEL;
|
|
56
81
|
const frameName = `${className}.${methodName}`;
|
|
82
|
+
// A standalone function has no owner object to hang per-instance state off,
|
|
83
|
+
// so the re-entrancy flag lives in this closure instead.
|
|
57
84
|
let active = false;
|
|
58
85
|
const invoke = named(frameName, (thisArg, args) => Reflect.apply(fn, thisArg, args));
|
|
59
86
|
const tracedFn = createTracedWrapper({
|
|
@@ -65,6 +92,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
65
92
|
call: invoke,
|
|
66
93
|
callUntraced: invoke,
|
|
67
94
|
});
|
|
95
|
+
// Proxying the function (rather than handing back the wrapper itself) keeps
|
|
96
|
+
// everything else about it intact for free: `name`, `length`, `prototype`,
|
|
97
|
+
// static properties, `instanceof` and reflect-metadata lookups. Only
|
|
98
|
+
// `apply` is trapped, so `new fn()` still constructs the original.
|
|
68
99
|
return new Proxy(fn, {
|
|
69
100
|
apply: named(frameName, (_target, thisArg, args) => Reflect.apply(tracedFn, thisArg, args)),
|
|
70
101
|
});
|
|
@@ -73,6 +104,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
73
104
|
if (options.skipInstrumentation(instance)) {
|
|
74
105
|
return instance;
|
|
75
106
|
}
|
|
107
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
76
108
|
const methodRefsCache = new WeakMap();
|
|
77
109
|
const currentlyTracing = new WeakMap();
|
|
78
110
|
return new Proxy(instance, {
|
|
@@ -80,6 +112,8 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
80
112
|
const attributeValue = Reflect.get(target, prop);
|
|
81
113
|
const isFunction = typeof attributeValue === "function" && prop !== "constructor";
|
|
82
114
|
const shouldProxy = isFunction && !isClass(attributeValue);
|
|
115
|
+
// For Axios instance, do not proxy its methods
|
|
116
|
+
// its an exception case
|
|
83
117
|
const isAxios = attributeValue?.Axios;
|
|
84
118
|
if (!shouldProxy || isAxios) {
|
|
85
119
|
return Reflect.get(target, prop);
|
|
@@ -87,6 +121,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
87
121
|
const className = target.constructor.name;
|
|
88
122
|
const methodName = String(prop);
|
|
89
123
|
const frameName = `${className}.${methodName}`;
|
|
124
|
+
// When "originalMethod" is already proxied, return the cached version
|
|
90
125
|
if (methodRefsCache.has(attributeValue)) {
|
|
91
126
|
return methodRefsCache.get(attributeValue);
|
|
92
127
|
}
|
|
@@ -108,10 +143,20 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
108
143
|
activeMethods.delete(methodName);
|
|
109
144
|
}
|
|
110
145
|
},
|
|
146
|
+
// Traced calls run against the proxy so that a method calling into
|
|
147
|
+
// itself (`this.other()`) is instrumented as a nested step.
|
|
111
148
|
call: named(frameName, (_thisArg, args) => originalMethod.apply(receiver, args)),
|
|
112
149
|
callUntraced: named(frameName, (_thisArg, args) => originalMethod.apply(target, args)),
|
|
113
150
|
});
|
|
151
|
+
// V8 hard-codes the type name of a stack frame to "Proxy" whenever the
|
|
152
|
+
// frame's receiver is a proxy, and no trap can override that. The
|
|
153
|
+
// wrapper never reads `this`, so handing it out with the receiver
|
|
154
|
+
// detached costs nothing and makes V8 treat its frame as top-level -
|
|
155
|
+
// printing the "<Class>.<method>" name above on its own.
|
|
114
156
|
const boundFn = proxyFn.bind(undefined);
|
|
157
|
+
// `bind` renames the function to "bound <name>" and drops metadata;
|
|
158
|
+
// restore both so the wrapper stays indistinguishable from the original
|
|
159
|
+
// to anything reflecting over it (DI, decorators, arity checks).
|
|
115
160
|
Object.defineProperty(boundFn, "name", {
|
|
116
161
|
value: originalMethod.name,
|
|
117
162
|
configurable: true,
|
|
@@ -136,14 +181,34 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
136
181
|
return instance;
|
|
137
182
|
};
|
|
138
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* Renames a function so that V8 prints `name` for the stack frames it appears
|
|
186
|
+
* in. The `name` property is what the stack serializer reads, so redefining it
|
|
187
|
+
* is enough - the function keeps its identity and behavior.
|
|
188
|
+
*/
|
|
139
189
|
function named(name, fn) {
|
|
140
190
|
Object.defineProperty(fn, "name", { value: name, configurable: true });
|
|
141
191
|
return fn;
|
|
142
192
|
}
|
|
193
|
+
/**
|
|
194
|
+
* Rewrites the `Proxy.<method>` frame an instrumented call leaves behind into
|
|
195
|
+
* `<Class>.<method>`.
|
|
196
|
+
*
|
|
197
|
+
* V8 stamps "Proxy" as the type name of any frame whose receiver is a proxy and
|
|
198
|
+
* no trap can override that. Traced calls run against the proxy on purpose (so
|
|
199
|
+
* `this.other()` is picked up as a nested step), which means the *original*
|
|
200
|
+
* method's own frame is the one that prints as `Proxy.<method>` - the wrapper
|
|
201
|
+
* frames around it are already named after the class.
|
|
202
|
+
*
|
|
203
|
+
* Only the topmost match is rewritten. Every wrapper on the way out relabels
|
|
204
|
+
* its own frame, and inner calls unwind before outer ones, so two classes that
|
|
205
|
+
* happen to share a method name each end up with the right label.
|
|
206
|
+
*/
|
|
143
207
|
function relabelProxyFrame(err, className, methodName) {
|
|
144
208
|
if (!(err instanceof Error) || typeof err.stack !== "string") {
|
|
145
209
|
return;
|
|
146
210
|
}
|
|
211
|
+
// `async` prefixes the type name on frames resumed from an await.
|
|
147
212
|
const frame = new RegExp(`(\\n\\s*at (?:async )?)Proxy\\.${escapeRegExp(methodName)}\\b`);
|
|
148
213
|
if (!frame.test(err.stack)) {
|
|
149
214
|
return;
|
|
@@ -152,6 +217,8 @@ function relabelProxyFrame(err, className, methodName) {
|
|
|
152
217
|
err.stack = err.stack.replace(frame, `$1${className}.${methodName}`);
|
|
153
218
|
}
|
|
154
219
|
catch {
|
|
220
|
+
// Some errors ship a read-only `stack`; the label is cosmetic, so leaving
|
|
221
|
+
// it as-is beats masking the original failure.
|
|
155
222
|
}
|
|
156
223
|
}
|
|
157
224
|
function escapeRegExp(value) {
|