Skip to content

Commit

Permalink
Make tracingMiddleware span creation optional
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeymisson committed Sep 7, 2023
1 parent b3f0dd3 commit 8394f2e
Show file tree
Hide file tree
Showing 9 changed files with 29 additions and 28 deletions.
2 changes: 1 addition & 1 deletion src/service/logger/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ interface LoggerContext extends Pick<IOContext, 'account'|'workspace'|'requestI

interface TracingState {
isTraceSampled: boolean,
traceId: string
traceId?: string
}

export class Logger {
Expand Down
9 changes: 5 additions & 4 deletions src/service/tracing/tracingMiddlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const addTracingMiddleware = (tracer: Tracer) => {
const start = process.hrtime()
concurrentRequests.inc(1)
const rootSpan = tracer.extract(FORMAT_HTTP_HEADERS, ctx.request.headers) as undefined | SpanContext
ctx.tracing = { tracer, currentSpan: undefined}

if (!shouldTrace(ctx, rootSpan)) {
await next()
Expand Down Expand Up @@ -93,7 +94,7 @@ export const addTracingMiddleware = (tracer: Tracer) => {

currentSpan.log(cloneAndSanitizeHeaders(ctx.request.headers, 'req.headers.'))
currentSpan.log(cloneAndSanitizeHeaders(ctx.response.headers, 'res.headers.'))
ctx.set(TRACE_ID_HEADER, traceInfo.traceId)
ctx.set(TRACE_ID_HEADER, traceInfo.traceId!)
}

const onResFinished = () => {
Expand All @@ -119,7 +120,7 @@ export const addTracingMiddleware = (tracer: Tracer) => {

export const nameSpanOperationMiddleware = (operationType: string, operationName: string) => {
return function nameSpanOperation(ctx: ServiceContext, next: () => Promise<void>) {
ctx.tracing?.currentSpan.setOperationName(`${operationType}:${operationName}`)
ctx.tracing?.currentSpan?.setOperationName(`${operationType}:${operationName}`)
return next()
}
}
Expand All @@ -136,13 +137,13 @@ export const traceUserLandRemainingPipelineMiddleware = () => {
const startTime = process.hrtime()

try {
span.log({ event: RuntimeLogEvents.USER_MIDDLEWARES_START })
span?.log({ event: RuntimeLogEvents.USER_MIDDLEWARES_START })
await next()
} catch (err) {
ErrorReport.create({ originalError: err }).injectOnSpan(span, ctx.vtex.logger)
throw err
} finally {
span.log({
span?.log({
event: RuntimeLogEvents.USER_MIDDLEWARES_FINISH,
[RuntimeLogFields.USER_MIDDLEWARES_DURATION]: hrToMillis(process.hrtime(startTime)),
})
Expand Down
6 changes: 3 additions & 3 deletions src/service/worker/runtime/builtIn/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const whoAmIHandler = ({
events,
routes,
}: ServiceJSON) => (ctx: ServiceContext) => {
ctx.tracing?.currentSpan.setOperationName('builtin:whoami')
ctx.tracing?.currentSpan?.setOperationName('builtin:whoami')
ctx.status = 200
ctx.body = {
events,
Expand All @@ -17,7 +17,7 @@ export const healthcheckHandler = ({
events,
routes,
}: ServiceJSON) => (ctx: ServiceContext) => {
ctx.tracing?.currentSpan.setOperationName('builtin:healthcheck')
ctx.tracing?.currentSpan?.setOperationName('builtin:healthcheck')
ctx.status = 200
ctx.body = {
events,
Expand All @@ -26,7 +26,7 @@ export const healthcheckHandler = ({
}

export const metricsLoggerHandler = (ctx: ServiceContext) => {
ctx.tracing?.currentSpan.setOperationName('builtin:metrics-logger')
ctx.tracing?.currentSpan?.setOperationName('builtin:metrics-logger')
ctx.status = 200
ctx.body = ctx.metricsLogger.getSummaries()
}
2 changes: 1 addition & 1 deletion src/service/worker/runtime/statusTrack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const isStatusTrackBroadcast = (message: any): message is typeof BROADCAS
message === BROADCAST_STATUS_TRACK

export const statusTrackHandler = async (ctx: ServiceContext) => {
ctx.tracing?.currentSpan.setOperationName('builtin:status-track')
ctx.tracing?.currentSpan?.setOperationName('builtin:status-track')
if (!LINKED) {
process.send?.(BROADCAST_STATUS_TRACK)
}
Expand Down
2 changes: 1 addition & 1 deletion src/service/worker/runtime/typings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export type Maybe<T> = T | null | undefined

export interface TracingContext {
tracer: Tracer
currentSpan: Span
currentSpan: Span | undefined
}

export interface Context<T extends IOClients> {
Expand Down
2 changes: 1 addition & 1 deletion src/service/worker/runtime/utils/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const prepareHandlerCtx = (header: Context['request']['header'], tracingC
segmentToken: header[SEGMENT_HEADER],
sessionToken: header[SESSION_HEADER],
tenant: header[TENANT_HEADER] ? parseTenantHeaderValue(header[TENANT_HEADER]) : undefined,
tracer: new UserLandTracer(tracingContext.tracer, tracingContext.currentSpan),
tracer: new UserLandTracer(tracingContext?.tracer, tracingContext?.currentSpan),
userAgent: process.env.VTEX_APP_ID || '',
workspace: header[WORKSPACE_HEADER],
}
Expand Down
16 changes: 8 additions & 8 deletions src/tracing/UserLandTracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { TracerSingleton } from '../service/tracing/TracerSingleton'
import { getTraceInfo } from './utils'

export interface IUserLandTracer {
traceId: string
traceId?: string
isTraceSampled: boolean
startSpan: Tracer['startSpan']
inject: Tracer['inject']
fallbackSpanContext: () => SpanContext
fallbackSpanContext: () => SpanContext | undefined
}

export const createTracingContextFromCarrier = (
Expand All @@ -28,15 +28,15 @@ export const createTracingContextFromCarrier = (

export class UserLandTracer implements IUserLandTracer {
private tracer: Tracer
private fallbackSpan: Span
private fallbackSpan: Span | undefined
private fallbackSpanLock: boolean

// tslint:disable-next-line
private _isSampled: boolean
// tslint:disable-next-line
private _traceId: string
private _traceId?: string

constructor(tracer: Tracer, fallbackSpan: Span) {
constructor(tracer: Tracer, fallbackSpan?: Span) {
this.tracer = tracer
this.fallbackSpan = fallbackSpan
this.fallbackSpanLock = false
Expand All @@ -58,7 +58,7 @@ export class UserLandTracer implements IUserLandTracer {
this.fallbackSpanLock = true
}

public setFallbackSpan(newSpan: Span) {
public setFallbackSpan(newSpan?: Span) {
if (this.fallbackSpanLock) {
throw new Error(`FallbackSpan is locked, can't change it`)
}
Expand All @@ -78,7 +78,7 @@ export class UserLandTracer implements IUserLandTracer {
return this.tracer.inject(spanContext, format, carrier)
}

public fallbackSpanContext(): SpanContext {
return this.fallbackSpan.context()
public fallbackSpanContext(): SpanContext | undefined {
return this.fallbackSpan?.context()
}
}
8 changes: 4 additions & 4 deletions src/tracing/errorReporting/ErrorReport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ export class ErrorReport extends ErrorReportBase {
* instance on the provided Span. If a logger is provided and the
* span is part of a **sampled** trace, then the error will be logged.
*/
public injectOnSpan(span: Span, logger?: IOContext['logger']) {
span.setTag(TracingTags.ERROR, 'true')
public injectOnSpan(span?: Span, logger?: IOContext['logger']) {
span?.setTag(TracingTags.ERROR, 'true')

const indexedLogs: Record<string, string> = {
[ErrorReportLogFields.ERROR_KIND]: this.kind,
Expand All @@ -61,7 +61,7 @@ export class ErrorReport extends ErrorReportBase {
}

const serializableError = this.toObject()
span.log({ event: 'error', ...indexedLogs, error: serializableError })
span?.log({ event: 'error', ...indexedLogs, error: serializableError })

if (logger && this.shouldLogToSplunk(span)) {
logger.error(serializableError)
Expand All @@ -71,7 +71,7 @@ export class ErrorReport extends ErrorReportBase {
return this
}

private shouldLogToSplunk(span: Span) {
private shouldLogToSplunk(span?: Span) {
return !this.isErrorReported() && getTraceInfo(span).isSampled
}
}
10 changes: 5 additions & 5 deletions src/tracing/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { authFields, sanitizeAuth } from '@vtex/node-error-report'
import { Span } from 'opentracing'

export interface TraceInfo {
traceId: string
traceId?: string
isSampled: boolean
}

export function getTraceInfo(span: Span): TraceInfo {
const spanContext = span.context()
export function getTraceInfo(span?: Span): TraceInfo {
const spanContext = span?.context()
return {
isSampled: (spanContext as any).isSampled?.() ?? false,
traceId: spanContext.toTraceId(),
isSampled: (spanContext as any)?.isSampled?.() ?? false,
traceId: spanContext?.toTraceId(),
}
}

Expand Down

0 comments on commit 8394f2e

Please sign in to comment.