-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtracing.ts
82 lines (71 loc) · 2.68 KB
/
tracing.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
import { MiddlewaresTracingContext, RequestConfig } from '..'
import { IOContext } from '../../service/worker/runtime/typings'
import { ErrorReport, getTraceInfo } from '../../tracing'
import { CustomHttpTags, OpentracingTags } from '../../tracing/Tags'
import { MiddlewareContext } from '../typings'
import { CacheType, isLocallyCacheable } from './cache'
interface HttpClientTracingMiddlewareConfig {
clientName: string
tracer: IOContext['tracer']
logger: IOContext['logger']
hasMemoryCacheMiddleware: boolean
hasDiskCacheMiddleware: boolean
}
export interface TraceableRequestConfig extends RequestConfig {
tracing: MiddlewaresTracingContext
}
export const createHttpClientTracingMiddleware = ({
tracer,
logger,
clientName,
hasMemoryCacheMiddleware,
hasDiskCacheMiddleware,
}: HttpClientTracingMiddlewareConfig) => {
return async function tracingMiddleware(ctx: MiddlewareContext, next: () => Promise<void>) {
if(!tracer.isTraceSampled){
await next()
return
}
const rootSpan = tracer.fallbackSpanContext()
const { requestSpanNameSuffix } = ctx.config.tracing || {}
const spanName = requestSpanNameSuffix ? `request:${requestSpanNameSuffix}` : 'request'
const span = tracer.startSpan(spanName, {childOf: rootSpan})
ctx.tracing = {
...ctx.config.tracing,
isSampled: getTraceInfo(span).isSampled,
logger,
rootSpan: span,
tracer,
}
// We can't pass ctx.tracing to axios, so we pass ctx.config.tracing with
// a reference to the ctx.tracing object (axios only receives the config object)
;(ctx.config as TraceableRequestConfig).tracing = ctx.tracing
const hasMemoCache = !(!isLocallyCacheable(ctx.config, CacheType.Any) || !ctx.config.memoizable)
const hasMemoryCache = hasMemoryCacheMiddleware && !!isLocallyCacheable(ctx.config, CacheType.Memory)
const hasDiskCache = hasDiskCacheMiddleware && !!isLocallyCacheable(ctx.config, CacheType.Disk)
span?.addTags({
[CustomHttpTags.HTTP_MEMOIZATION_CACHE_ENABLED]: hasMemoCache,
[CustomHttpTags.HTTP_MEMORY_CACHE_ENABLED]: hasMemoryCache,
[CustomHttpTags.HTTP_DISK_CACHE_ENABLED]: hasDiskCache,
[CustomHttpTags.HTTP_CLIENT_NAME]: clientName,
})
let response
try {
await next()
response = ctx.response
} catch (err: any) {
response = err.response
if(ctx.tracing?.isSampled) {
ErrorReport.create({ originalError: err }).injectOnSpan(span, logger)
}
throw err
} finally {
if (response) {
span?.setTag(OpentracingTags.HTTP_STATUS_CODE, response.status)
} else {
span?.setTag(CustomHttpTags.HTTP_NO_RESPONSE, true)
}
span?.finish()
}
}
}