File size: 1,620 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import mitt from '../../shared/lib/mitt'
import type { MittEmitter } from '../../shared/lib/mitt'

export type SpanOptions = {
  startTime?: number
  attributes?: Record<string, unknown>
}

export type SpanState =
  | {
      state: 'inprogress'
    }
  | {
      state: 'ended'
      endTime: number
    }

interface ISpan {
  name: string
  startTime: number
  attributes: Record<string, unknown>
  state: SpanState
  end(endTime?: number): void
}

class Span implements ISpan {
  name: string
  startTime: number
  onSpanEnd: (span: Span) => void
  state: SpanState
  attributes: Record<string, unknown>

  constructor(
    name: string,
    options: SpanOptions,
    onSpanEnd: (span: Span) => void
  ) {
    this.name = name
    this.attributes = options.attributes ?? {}
    this.startTime = options.startTime ?? Date.now()
    this.onSpanEnd = onSpanEnd
    this.state = { state: 'inprogress' }
  }

  end(endTime?: number) {
    if (this.state.state === 'ended') {
      throw new Error('Span has already ended')
    }

    this.state = {
      state: 'ended',
      endTime: endTime ?? Date.now(),
    }

    this.onSpanEnd(this)
  }
}

class Tracer {
  _emitter: MittEmitter<string> = mitt()

  private handleSpanEnd = (span: Span) => {
    this._emitter.emit('spanend', span)
  }

  startSpan(name: string, options: SpanOptions) {
    return new Span(name, options, this.handleSpanEnd)
  }

  onSpanEnd(cb: (span: ISpan) => void): () => void {
    this._emitter.on('spanend', cb)
    return () => {
      this._emitter.off('spanend', cb)
    }
  }
}

export type { ISpan as Span }
export default new Tracer()