Skip to content

Commit

Permalink
refactor(otel): TraceService changed to Singleton, and more changes
Browse files Browse the repository at this point in the history
- remove DecoratorContext['otelComponent'], use DecoratorContext['traceService'].otel instead
- remove GenDecoratorExecutorOptions['otelComponent']
- change return type of startScopeActiveSpan() from `Span` to `{ span: Span, traceContext: TraceContext }`
- change param of TraceService.() to type EndSpanOptions
  • Loading branch information
waitingsong committed Jul 22, 2024
1 parent 22ce135 commit 44ffbc4
Show file tree
Hide file tree
Showing 50 changed files with 1,346 additions and 833 deletions.
3 changes: 3 additions & 0 deletions packages/otel/src/app/default.controller.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import assert from 'assert'

import {
Controller,
Get,
Expand Down Expand Up @@ -31,6 +33,7 @@ export class DefaultOtelComponentController {
async hello(): Promise<string> {
this.validateRoute()
const traceId = this.traceSvc.getTraceId()
assert(traceId, 'traceId is empty')
const msg = await this.svc.hello(Msg.hello)
const ret = `${msg}: ${traceId}`
return ret
Expand Down
5 changes: 5 additions & 0 deletions packages/otel/src/config/config.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ export const otelMiddlewareConfig: Readonly<Omit<MiddlewareConfig, 'match'>> = {
export const otlpGrpcExporterConfig: InitTraceOptions['otlpGrpcExporterConfig'] = {
...initOtlpGrpcExporterConfig,
}

export const asyncContextManager = {
enable: true,
}

8 changes: 4 additions & 4 deletions packages/otel/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import assert from 'node:assert'

import {
App,
Config,
Configuration,
ILifeCycle,
Inject,
Expand All @@ -15,6 +14,7 @@ import { ILogger } from '@midwayjs/logger'
import {
Application,
IMidwayContainer,
MConfig,
deleteRouter,
registerMiddleware,
} from '@mwcp/share'
Expand All @@ -28,7 +28,7 @@ import { OtelComponent } from './lib/component.js'
import { TraceInit } from './lib/index.js'
import { AutoRegister } from './lib/reg-decorator.js'
import {
Config as Conf,
Config,
ConfigKey,
MiddlewareConfig,
} from './lib/types.js'
Expand All @@ -53,8 +53,8 @@ export class AutoConfiguration implements ILifeCycle {

@App() readonly app: Application

@Config(ConfigKey.config) protected readonly config: Conf
@Config(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig
@MConfig(ConfigKey.config) protected readonly config: Config
@MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig

@Inject() protected readonly environmentService: MidwayEnvironmentService
@Inject() protected readonly informationService: MidwayInformationService
Expand Down
115 changes: 115 additions & 0 deletions packages/otel/src/lib/abstract.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import type { Attributes, Context as TraceContext, Span, SpanOptions, TimeInput } from '@opentelemetry/api'
import type { node } from '@opentelemetry/sdk-node'

import type { AddEventOptions, SpanStatusOptions } from './types.js'


/** OpenTelemetry Component */
export abstract class AbstractOtelComponent {

/** Active during Midway Lifecycle between onReady and onServerReady */
abstract appInitProcessContext: TraceContext | undefined
/** Active during Midway Lifecycle between onReady and onServerReady */
abstract appInitProcessSpan: Span | undefined

abstract otelLibraryName: string
abstract otelLibraryVersion: string
/* request|response -> Map<lower,norm> */
readonly abstract captureHeadersMap: Map<string, Map<string, string>>
readonly abstract traceContextMap: WeakMap<object, TraceContext[]>

protected abstract traceProvider: node.NodeTracerProvider | undefined
protected abstract spanProcessors: node.SpanProcessor[]

abstract getGlobalCurrentContext(): TraceContext
abstract getGlobalCurrentSpan(traceContext?: TraceContext): Span | undefined
abstract getTraceId(): string | undefined
abstract getScopeRootTraceContext(scope: TraceContext): TraceContext | undefined

/**
* Starts a new {@link Span}. Start the span without setting it on context.
* This method do NOT modify the current Context.
*/
abstract startSpan(name: string, options?: SpanOptions, traceContext?: TraceContext): Span
/**
* Starts a new {@link Span}. Start the span without setting it on context.
*/
abstract startSpanContext(name: string, options?: SpanOptions, traceContext?: TraceContext): { span: Span, traceContext: TraceContext }

/**
* Starts a new {@link Span} and calls the given function passing it the created span as first argument.
* Additionally the new span gets set in context and this context is activated
* for the duration of the function call.
*/
abstract startActiveSpan<F extends (
...args: [Span]) => ReturnType<F>>(
name: string,
callback: F,
options?: SpanOptions,
traceContext?: TraceContext,
): ReturnType<F>

abstract flush(): Promise<void>
abstract shutdown(): Promise<void>

/**
* Adds an event to the given span.
*/
abstract addEvent(
span: Span,
input: Attributes,
options?: AddEventOptions,
): void

abstract addSpanEventWithError(span: Span, error?: Error): void

/**
* Sets the attributes to the given span.
*/
abstract setAttributes(span: Span, input: Attributes): void

abstract setAttributesLater(span: Span | undefined, input: Attributes): void

/**
* Sets the span with the error passed in params, note span not ended.
*/
abstract setSpanWithError(
rootSpan: Span | undefined,
span: Span,
error: Error | undefined,
eventName?: string,
): void


/**
* - ends the given span
* - set span with error if error passed in params
* - set span status
* - call span.end(), except span is root span
*/
abstract endSpan(
rootSpan: Span | undefined,
span: Span,
spanStatusOptions?: SpanStatusOptions,
endTime?: TimeInput,
): void


abstract endRootSpan(
rootSpan: Span,
spanStatusOptions?: SpanStatusOptions,
endTime?: TimeInput,
): void


abstract addAppInitEvent(
input: Attributes,
options?: AddEventOptions,
/** if omit, use this.appInitProcessSpan */
span?: Span,
): void

abstract endAppInitEvent(): void

}

Loading

0 comments on commit 44ffbc4

Please sign in to comment.