From 8394f2e4b1e78f3a0948711482a5dbec99dee472 Mon Sep 17 00:00:00 2001 From: Jeymisson Oliveira Date: Thu, 7 Sep 2023 17:07:36 -0300 Subject: [PATCH] Make tracingMiddleware span creation optional --- src/service/logger/logger.ts | 2 +- src/service/tracing/tracingMiddlewares.ts | 9 +++++---- src/service/worker/runtime/builtIn/handlers.ts | 6 +++--- src/service/worker/runtime/statusTrack.ts | 2 +- src/service/worker/runtime/typings.ts | 2 +- src/service/worker/runtime/utils/context.ts | 2 +- src/tracing/UserLandTracer.ts | 16 ++++++++-------- src/tracing/errorReporting/ErrorReport.ts | 8 ++++---- src/tracing/utils.ts | 10 +++++----- 9 files changed, 29 insertions(+), 28 deletions(-) diff --git a/src/service/logger/logger.ts b/src/service/logger/logger.ts index a37ebd5bc..7b6f5b766 100644 --- a/src/service/logger/logger.ts +++ b/src/service/logger/logger.ts @@ -26,7 +26,7 @@ interface LoggerContext extends Pick { 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() @@ -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 = () => { @@ -119,7 +120,7 @@ export const addTracingMiddleware = (tracer: Tracer) => { export const nameSpanOperationMiddleware = (operationType: string, operationName: string) => { return function nameSpanOperation(ctx: ServiceContext, next: () => Promise) { - ctx.tracing?.currentSpan.setOperationName(`${operationType}:${operationName}`) + ctx.tracing?.currentSpan?.setOperationName(`${operationType}:${operationName}`) return next() } } @@ -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)), }) diff --git a/src/service/worker/runtime/builtIn/handlers.ts b/src/service/worker/runtime/builtIn/handlers.ts index 16d3c3f05..f817e9a9e 100644 --- a/src/service/worker/runtime/builtIn/handlers.ts +++ b/src/service/worker/runtime/builtIn/handlers.ts @@ -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, @@ -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, @@ -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() } diff --git a/src/service/worker/runtime/statusTrack.ts b/src/service/worker/runtime/statusTrack.ts index 5c3930d34..60ea53752 100644 --- a/src/service/worker/runtime/statusTrack.ts +++ b/src/service/worker/runtime/statusTrack.ts @@ -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) } diff --git a/src/service/worker/runtime/typings.ts b/src/service/worker/runtime/typings.ts index 8392cbe64..357a61cda 100644 --- a/src/service/worker/runtime/typings.ts +++ b/src/service/worker/runtime/typings.ts @@ -28,7 +28,7 @@ export type Maybe = T | null | undefined export interface TracingContext { tracer: Tracer - currentSpan: Span + currentSpan: Span | undefined } export interface Context { diff --git a/src/service/worker/runtime/utils/context.ts b/src/service/worker/runtime/utils/context.ts index 6fe1f1408..0f9cff5b9 100644 --- a/src/service/worker/runtime/utils/context.ts +++ b/src/service/worker/runtime/utils/context.ts @@ -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], } diff --git a/src/tracing/UserLandTracer.ts b/src/tracing/UserLandTracer.ts index 7b3e616f5..4f8454656 100644 --- a/src/tracing/UserLandTracer.ts +++ b/src/tracing/UserLandTracer.ts @@ -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 = ( @@ -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 @@ -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`) } @@ -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() } } diff --git a/src/tracing/errorReporting/ErrorReport.ts b/src/tracing/errorReporting/ErrorReport.ts index 91bf164a2..7a8d31344 100644 --- a/src/tracing/errorReporting/ErrorReport.ts +++ b/src/tracing/errorReporting/ErrorReport.ts @@ -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 = { [ErrorReportLogFields.ERROR_KIND]: this.kind, @@ -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) @@ -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 } } diff --git a/src/tracing/utils.ts b/src/tracing/utils.ts index 51d3be2e9..633f6df95 100644 --- a/src/tracing/utils.ts +++ b/src/tracing/utils.ts @@ -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(), } }