/
sdk.ts
165 lines (146 loc) · 5.51 KB
/
sdk.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
import { propagation } from '@opentelemetry/api'
import { W3CTraceContextPropagator } from '@opentelemetry/core'
import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import {
AlwaysOnSampler,
ParentBasedSampler,
ReadableSpan,
Sampler,
SpanExporter,
TraceIdRatioBasedSampler,
} from '@opentelemetry/sdk-trace-base'
import { Initialiser } from './config.js'
import { OTLPExporter } from './exporter.js'
import { WorkerTracerProvider } from './provider.js'
import { isHeadSampled, isRootErrorSpan, multiTailSampler } from './sampling.js'
import { BatchTraceSpanProcessor } from './spanprocessor.js'
import { Trigger, TraceConfig, ResolvedTraceConfig, ExporterConfig, ParentRatioSamplingConfig } from './types.js'
import { unwrap } from './wrap.js'
import { createFetchHandler, instrumentGlobalFetch } from './instrumentation/fetch.js'
import { instrumentGlobalCache } from './instrumentation/cache.js'
import { createQueueHandler } from './instrumentation/queue.js'
import { DOClass, instrumentDOClass } from './instrumentation/do.js'
type FetchHandler = ExportedHandlerFetchHandler<unknown, unknown>
type QueueHandler = ExportedHandlerQueueHandler
export type ResolveConfigFn = (env: any, trigger: Trigger) => TraceConfig
export type ConfigurationOption = TraceConfig | ResolveConfigFn
export function isRequest(trigger: Trigger): trigger is Request {
return trigger instanceof Request
}
export function isMessageBatch(trigger: Trigger): trigger is MessageBatch {
return !!(trigger as MessageBatch).ackAll
}
export function isAlarm(trigger: Trigger): trigger is 'do-alarm' {
return trigger === 'do-alarm'
}
const createResource = (config: ResolvedTraceConfig): Resource => {
const workerResourceAttrs = {
[SemanticResourceAttributes.CLOUD_PROVIDER]: 'cloudflare',
[SemanticResourceAttributes.CLOUD_PLATFORM]: 'cloudflare.workers',
[SemanticResourceAttributes.CLOUD_REGION]: 'earth',
// [SemanticResourceAttributes.FAAS_NAME]: '//TODO',
// [SemanticResourceAttributes.FAAS_VERSION]: '//TODO',
[SemanticResourceAttributes.FAAS_MAX_MEMORY]: 128,
[SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]: 'JavaScript',
[SemanticResourceAttributes.TELEMETRY_SDK_NAME]: '@microlabs/otel-workers-sdk',
}
const serviceResource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: config.service.name,
[SemanticResourceAttributes.SERVICE_NAMESPACE]: config.service.namespace,
[SemanticResourceAttributes.SERVICE_VERSION]: config.service.version,
})
const resource = new Resource(workerResourceAttrs)
return resource.merge(serviceResource)
}
function isSpanExporter(exporterConfig: ExporterConfig): exporterConfig is SpanExporter {
return !!(exporterConfig as SpanExporter).export
}
let initialised = false
function init(config: ResolvedTraceConfig): void {
if (!initialised) {
instrumentGlobalCache()
instrumentGlobalFetch()
propagation.setGlobalPropagator(new W3CTraceContextPropagator())
const resource = createResource(config)
const spanProcessor = new BatchTraceSpanProcessor()
const provider = new WorkerTracerProvider(spanProcessor, resource)
provider.register()
initialised = true
}
}
function isSampler(sampler: Sampler | ParentRatioSamplingConfig): sampler is Sampler {
return !!(sampler as Sampler).shouldSample
}
function createSampler(conf: ParentRatioSamplingConfig): Sampler {
const ratioSampler = new TraceIdRatioBasedSampler(conf.ratio)
if (typeof conf.acceptRemote === 'boolean' && !conf.acceptRemote) {
return new ParentBasedSampler({
root: ratioSampler,
remoteParentSampled: ratioSampler,
remoteParentNotSampled: ratioSampler,
})
} else {
return new ParentBasedSampler({ root: ratioSampler })
}
}
function parseConfig(supplied: TraceConfig): ResolvedTraceConfig {
const headSampleConf = supplied.sampling?.headSampler
const headSampler = headSampleConf
? isSampler(headSampleConf)
? headSampleConf
: createSampler(headSampleConf)
: new AlwaysOnSampler()
return {
exporter: isSpanExporter(supplied.exporter) ? supplied.exporter : new OTLPExporter(supplied.exporter),
fetch: {
includeTraceContext: supplied.fetch?.includeTraceContext ?? true,
},
handlers: {
fetch: {
acceptTraceContext: supplied.handlers?.fetch?.acceptTraceContext ?? true,
},
},
postProcessor: supplied.postProcessor || ((spans: ReadableSpan[]) => spans),
sampling: {
headSampler,
tailSampler: supplied.sampling?.tailSampler || multiTailSampler([isHeadSampled, isRootErrorSpan]),
},
service: supplied.service,
}
}
function createInitialiser(config: ConfigurationOption): Initialiser {
if (typeof config === 'function') {
return (env, trigger) => {
const conf = parseConfig(config(env, trigger))
init(conf)
return conf
}
} else {
return () => {
const conf = parseConfig(config)
init(conf)
return conf
}
}
}
export function instrument<E, Q, C>(
handler: ExportedHandler<E, Q, C>,
config: ConfigurationOption
): ExportedHandler<E, Q, C> {
const initialiser = createInitialiser(config)
if (handler.fetch) {
const fetcher = unwrap(handler.fetch) as FetchHandler
handler.fetch = createFetchHandler(fetcher, initialiser)
}
if (handler.queue) {
const queuer = unwrap(handler.queue) as QueueHandler
handler.queue = createQueueHandler(queuer, initialiser)
}
return handler
}
export function instrumentDO(doClass: DOClass, config: ConfigurationOption) {
const initialiser = createInitialiser(config)
return instrumentDOClass(doClass, initialiser)
}
export { waitUntilTrace } from './instrumentation/fetch.js'