-
Notifications
You must be signed in to change notification settings - Fork 574
/
Copy pathspans.ts
332 lines (281 loc) · 10.6 KB
/
spans.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
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
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import globals from '../extensionGlobals'
import type { AsyncLocalStorage as AsyncLocalStorageClass } from 'async_hooks'
import {
definitions,
Metric,
MetricBase,
MetricDefinition,
MetricName,
MetricShapes,
TelemetryBase,
} from './telemetry.gen'
import { getTelemetryReason, getTelemetryResult } from '../errors'
import { entries, NumericKeys } from '../utilities/tsUtils'
const AsyncLocalStorage: typeof AsyncLocalStorageClass =
require('async_hooks').AsyncLocalStorage ??
class<T> {
readonly #store: T[] = []
#disabled = false
public disable() {
this.#disabled = true
}
public getStore() {
return this.#disabled ? undefined : this.#store[0]
}
public run<R>(store: T, callback: (...args: any[]) => R, ...args: any[]): R {
this.#disabled = false
this.#store.unshift(store)
try {
const result = callback(...args)
if (result instanceof Promise) {
return result.finally(() => this.#store.shift()) as unknown as R
}
this.#store.shift()
return result
} catch (err) {
this.#store.shift()
throw err
}
}
public exit<R>(callback: (...args: any[]) => R, ...args: any[]): R {
const saved = this.#store.shift()
try {
const result = callback(...args)
if (result instanceof Promise) {
return result.finally(() => saved !== undefined && this.#store.unshift(saved)) as unknown as R
}
saved !== undefined && this.#store.unshift(saved)
return result
} catch (err) {
saved !== undefined && this.#store.unshift(saved)
throw err
}
}
public enterWith(store: T): void {
// XXX: you need hooks into async resource lifecycles to implement this correctly
this.#store.shift()
this.#store.unshift(store)
}
}
function getValidatedState(state: Partial<MetricBase>, definition: MetricDefinition) {
const missingFields: string[] = []
for (const key of definition.requiredMetadata) {
if (state[key as keyof typeof state] === undefined) {
missingFields.push(key)
}
}
return missingFields.length !== 0 ? Object.assign({ missingFields }, state) : state
}
/**
* A span represents a "unit of work" captured for logging/telemetry.
* It can contain other spans recursively, then it's called a "trace" or "flow".
* https://opentelemetry.io/docs/concepts/signals/traces/
*
* See also: docs/telemetry.md
*/
export class TelemetrySpan<T extends MetricBase = MetricBase> {
#startTime?: Date
private readonly state: Partial<T> = {}
private readonly definition = definitions[this.name] ?? {
unit: 'None',
passive: true,
requiredMetadata: [],
}
/**
* These fields appear on the base metric instead of the 'metadata' and
* so they should be filtered out from the metadata.
*/
static readonly #excludedFields = ['passive', 'value']
public constructor(public readonly name: string) {}
public get startTime(): Date | undefined {
return this.#startTime
}
public record(data: Partial<T>): this {
Object.assign(this.state, data)
return this
}
public emit(data?: Partial<T>): void {
const state = getValidatedState({ ...this.state, ...data }, this.definition)
const metadata = Object.entries(state)
.filter(([_, v]) => v !== '') // XXX: the telemetry service currently rejects empty strings :/
.filter(([k, v]) => v !== undefined && !TelemetrySpan.#excludedFields.includes(k))
.map(([k, v]) => ({ Key: k, Value: String(v) }))
globals.telemetry.record({
Metadata: metadata,
MetricName: this.name,
Value: state.value ?? 1,
Unit: this.definition.unit,
Passive: state.passive ?? this.definition.passive,
EpochTimestamp: (this.startTime ?? new globals.clock.Date()).getTime(),
})
}
/**
* Puts the span in a 'running' state.
*/
public start(): this {
this.#startTime = new globals.clock.Date()
return this
}
/**
* Immediately emits the span, adding a duration/result/reason to the final output if applicable.
*
* This places the span in a 'stopped' state but does not mutate the information held by the span.
*/
public stop(err?: unknown): void {
const duration = this.startTime !== undefined ? globals.clock.Date.now() - this.startTime.getTime() : undefined
this.emit({
duration,
result: getTelemetryResult(err),
reason: getTelemetryReason(err),
} as Partial<T>)
this.#startTime = undefined
}
/**
* Adds the values provided in {@link data} to the current state.
*
* Any `undefined` values are ignored. If the current {@link state} is `undefined` then the value
* is initialized as 0 prior to adding {@link data}.
*/
public increment(data: { [P in NumericKeys<T>]+?: number }): void {
for (const [k, v] of entries(data)) {
if (v !== undefined) {
;(this.state as Record<typeof k, number>)[k] = ((this.state[k] as number) ?? 0) + v
}
}
}
/**
* Creates a copy of the span with an uninitialized start time.
*/
public clone(): TelemetrySpan {
return new TelemetrySpan(this.name).record(this.state)
}
}
type Attributes = Partial<MetricShapes[MetricName]>
interface TelemetryContext {
readonly spans: TelemetrySpan[]
readonly attributes: Attributes
}
const rootSpanName = 'root'
// This class is called 'Telemetry' but really it can be used for any kind of tracing
// You would need to make `Span` a template type and reduce the interface to just create/start/stop
export class TelemetryTracer extends TelemetryBase {
readonly #context = new AsyncLocalStorage<TelemetryContext>()
/**
* All spans present in the current execution context.
*/
public get spans(): readonly TelemetrySpan[] {
return this.#context.getStore()?.spans ?? []
}
/**
* The most recently used span in the current execution context.
*
* Note that only {@link run} will change the active span. Recording information
* on existing spans has no effect on the active span.
*/
public get activeSpan(): TelemetrySpan | undefined {
return this.#context.getStore()?.spans[0]
}
/**
* State that is applied to all new spans within the current or subsequent executions.
*/
public get attributes(): Readonly<Attributes> | undefined {
return this.#context.getStore()?.attributes
}
/**
* Records information on the current and future spans in the execution context.
*
* This is merged in with the current state present in each span, **overwriting**
* any existing values for a given key. New spans are initialized with {@link attributes}
* but that may be overriden on subsequent writes.
*
* Callers must already be within an execution context for this to have any effect.
*/
public record(data: Attributes): void {
this.activeSpan?.record(data)
if (this.attributes) {
Object.assign(this.attributes, data)
}
}
/**
* Executes the provided callback function with a named span.
*
* All changes made to {@link attributes} (via {@link record}) during the execution are
* reverted after the execution completes.
*/
public run<T, U extends MetricName>(name: U, fn: (span: Metric<MetricShapes[U]>) => T): T {
const span = this.createSpan(name).start()
const frame = this.switchContext(span)
try {
const result = this.#context.run(frame, fn, span)
if (result instanceof Promise) {
return result
.then(v => (span.stop(), v))
.catch(e => {
span.stop(e)
throw e
}) as unknown as T
}
span.stop()
return result
} catch (e) {
span.stop(e)
throw e
}
}
/**
* **You should use {@link run} in the majority of cases. Only use this for instrumenting extension entrypoints.**
*
* Executes the given function within an anonymous 'root' span which does not emit
* any telemetry on its own.
*
* This can be used as a 'staging area' for adding attributes prior to creating spans.
*/
public runRoot<T>(fn: () => T): T {
const span = this.createSpan(rootSpanName)
const frame = this.switchContext(span)
return this.#context.run(frame, fn)
}
/**
* Wraps a function with {@link run}.
*
* This can be used when immediate execution of the function is not desirable.
*/
public instrument<T extends any[], U, R>(name: string, fn: (this: U, ...args: T) => R): (this: U, ...args: T) => R {
const run = this.run.bind(this)
return function (...args) {
// Typescript's `bind` overloading doesn't work well for parameter types
return run(name as MetricName, (fn as (this: U, ...args: any[]) => R).bind(this, ...args))
}
}
protected getMetric(name: string): Metric {
const getSpan = () => this.getSpan(name)
return {
name,
emit: data => getSpan().emit(data),
record: data => getSpan().record(data),
run: fn => this.run(name as MetricName, fn),
increment: data => getSpan().increment(data),
}
}
private getSpan(name: string): TelemetrySpan {
return this.spans.find(s => s.name === name) ?? this.createSpan(name)
}
private createSpan(name: string): TelemetrySpan {
const span = new TelemetrySpan(name).record(this.attributes ?? {})
if (this.activeSpan && this.activeSpan.name !== rootSpanName) {
return span.record({ parentMetric: this.activeSpan.name } satisfies { parentMetric: string } as any)
}
return span
}
private switchContext(span: TelemetrySpan): TelemetryContext {
const ctx = {
spans: [span, ...this.spans],
attributes: { ...this.attributes },
}
return ctx
}
}