|
1 | | -import type { SpanEvent, SpanId } from './types.js'; |
| 1 | +import type { SpanEvent } from './types.js'; |
2 | 2 | import { IdSortable, utils as idUtils } from '@matrixai/id'; |
3 | 3 |
|
4 | 4 | class Tracer { |
5 | | - protected activeSpans: Map<SpanId, string> = new Map(); |
| 5 | + protected activeSpans: Map<string, string> = new Map(); |
6 | 6 | protected queue: Array<SpanEvent> = []; |
7 | 7 | protected resolveWaitChunksP: (() => void) | undefined; |
8 | 8 | protected ended: boolean = false; |
| 9 | + protected idGen = new IdSortable(); |
9 | 10 |
|
10 | | - protected queueSpanEvent(evt: SpanEvent) { |
11 | | - // Convert the binary id to base64-encoded id |
12 | | - if (evt.id instanceof IdSortable) { |
13 | | - evt.id = idUtils.toMultibase(evt.id.get(), 'base64'); |
14 | | - } |
15 | | - if (evt.spanId instanceof IdSortable) { |
16 | | - evt.spanId = idUtils.toMultibase(evt.spanId.get(), 'base64'); |
17 | | - } |
18 | | - if (evt.parentSpanId instanceof IdSortable) { |
19 | | - evt.parentSpanId = idUtils.toMultibase(evt.parentSpanId.get(), 'base64'); |
| 11 | + protected nextId(): string { |
| 12 | + const result = this.idGen.next(); |
| 13 | + if (result.done || result.value == null) { |
| 14 | + throw new Error('Unexpected end of id generator'); |
20 | 15 | } |
| 16 | + return idUtils.toMultibase(result.value, 'base64'); |
| 17 | + } |
| 18 | + |
| 19 | + protected queueSpanEvent(evt: SpanEvent) { |
21 | 20 | this.queue.push(evt); |
22 | 21 | if (this.resolveWaitChunksP != null) this.resolveWaitChunksP(); |
23 | 22 | } |
24 | 23 |
|
25 | | - public startSpan(name: string, parentSpanId?: SpanId): SpanId { |
26 | | - const spanId = new IdSortable(); |
| 24 | + public startSpan(name: string, parentSpanId?: string): string { |
| 25 | + const spanId = this.nextId(); |
27 | 26 | this.activeSpans.set(spanId, name); |
28 | 27 | this.queueSpanEvent({ |
29 | 28 | type: 'start', |
30 | | - id: new IdSortable(), |
| 29 | + id: this.nextId(), |
31 | 30 | spanId: spanId, |
32 | 31 | parentSpanId: parentSpanId, |
33 | 32 | name: name, |
34 | 33 | }); |
35 | 34 | return spanId; |
36 | 35 | } |
37 | 36 |
|
38 | | - public endSpan(spanId: SpanId): void { |
| 37 | + public endSpan(spanId: string): void { |
39 | 38 | const name = this.activeSpans.get(spanId); |
40 | 39 | if (!name) return; |
41 | 40 | this.activeSpans.delete(spanId); |
42 | 41 | this.queueSpanEvent({ |
43 | 42 | type: 'end', |
44 | | - id: new IdSortable(), |
| 43 | + id: this.nextId(), |
45 | 44 | spanId: spanId, |
46 | 45 | name: name, |
47 | 46 | }); |
48 | 47 | } |
49 | 48 |
|
50 | 49 | public async traced<T>( |
51 | 50 | name: string, |
52 | | - parentSpanId: SpanId | undefined, |
| 51 | + parentSpanId: string | undefined, |
53 | 52 | fn: () => T | Promise<T>, |
54 | 53 | ): Promise<T> { |
55 | 54 | const fnProm = async () => { |
|
0 commit comments