@lobu/runtime-device 24.3.0 → 24.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,30 @@
1
1
  import type { Span, Tracer } from "@opentelemetry/api";
2
2
  import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
3
+ import type { SpanProcessor } from "@opentelemetry/sdk-trace-node";
3
4
  export interface OtelConfig {
4
5
  serviceName: string;
5
6
  serviceVersion?: string;
6
7
  otlpEndpoint?: string;
7
8
  enabled?: boolean;
9
+ /**
10
+ * Replaces the OTLP exporter. Tests pass an in-memory processor so init
11
+ * never constructs a gRPC client. Production leaves this unset.
12
+ */
13
+ spanProcessors?: SpanProcessor[];
8
14
  }
9
15
  export declare function initTracing(config: OtelConfig): void;
10
16
  export declare function getTracer(): Tracer | null;
11
- export declare function shutdownTracing(): Promise<void>;
17
+ /**
18
+ * Flush and stop tracing. With `timeoutMs`, an unreachable collector cannot
19
+ * hold up process exit past that budget; the timeout rejects.
20
+ */
21
+ export declare function shutdownTracing(timeoutMs?: number): Promise<void>;
12
22
  export declare function flushTracing(): Promise<void>;
13
23
  export declare function createSpan(name: string, attributes?: Record<string, string | number | boolean>, kind?: SpanKind): Span | null;
14
24
  export declare function withSpan<T>(name: string, fn: (span: Span | null) => Promise<T>, attributes?: Record<string, string | number | boolean>): Promise<T>;
15
25
  export declare function getCurrentSpan(): Span | undefined;
16
- export declare function runInSpanContext<T>(span: Span, fn: () => T): T;
26
+ /** Run `fn` with `span` active, or plainly when tracing produced no span. */
27
+ export declare function runInSpanContext<T>(span: Span | null, fn: () => T): T;
17
28
  export declare function createRootSpan(name: string, attributes?: Record<string, string | number | boolean>): {
18
29
  span: Span | null;
19
30
  traceparent: string | null;
@@ -17,6 +17,7 @@ const api_1 = require("@opentelemetry/api");
17
17
  Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return api_1.SpanKind; } });
18
18
  Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return api_1.SpanStatusCode; } });
19
19
  const logger_1 = require("./logger");
20
+ const trace_context_1 = require("./trace-context");
20
21
  const logger = (0, logger_1.createLogger)("otel");
21
22
  let provider = null;
22
23
  let tracer = null;
@@ -24,7 +25,9 @@ function initTracing(config) {
24
25
  if (provider) {
25
26
  return;
26
27
  }
27
- const enabled = config.enabled ?? !!config.otlpEndpoint;
28
+ const customProcessors = config.spanProcessors;
29
+ const useCustomProcessors = (customProcessors?.length ?? 0) > 0;
30
+ const enabled = config.enabled ?? (!!config.otlpEndpoint || useCustomProcessors);
28
31
  if (!enabled) {
29
32
  logger.debug("Tracing disabled (no OTEL_EXPORTER_OTLP_ENDPOINT configured)");
30
33
  return;
@@ -33,25 +36,39 @@ function initTracing(config) {
33
36
  // require, bun provides one for src TS, and the server ESM bundle banner
34
37
  // defines `const require = __createRequire(import.meta.url)` for exactly
35
38
  // these calls — while __filename has no shim there and would throw.
36
- let exporterCtor;
37
39
  let resourceFromAttributes;
38
40
  let NodeTracerProvider;
39
- let SimpleSpanProcessor;
40
41
  let ATTR_SERVICE_NAME;
41
42
  let ATTR_SERVICE_VERSION;
43
+ let spanProcessors;
42
44
  try {
43
- exporterCtor =
44
- require("@opentelemetry/exporter-trace-otlp-grpc").OTLPTraceExporter;
45
45
  resourceFromAttributes =
46
46
  require("@opentelemetry/resources").resourceFromAttributes;
47
+ let BatchSpanProcessor;
47
48
  ({
49
+ BatchSpanProcessor,
48
50
  NodeTracerProvider,
49
- SimpleSpanProcessor,
50
51
  } = require("@opentelemetry/sdk-trace-node"));
51
52
  ({
52
53
  ATTR_SERVICE_NAME,
53
54
  ATTR_SERVICE_VERSION,
54
55
  } = require("@opentelemetry/semantic-conventions"));
56
+ if (customProcessors?.length) {
57
+ // A caller-supplied processor (tests) never loads the gRPC exporter.
58
+ spanProcessors = customProcessors;
59
+ }
60
+ else {
61
+ // The server is long-lived: a batch keeps export off the request path
62
+ // and bounds memory with a drop-on-full queue while a collector is
63
+ // down. shutdownTracing flushes it.
64
+ const exporterCtor = require("@opentelemetry/exporter-trace-otlp-grpc").OTLPTraceExporter;
65
+ spanProcessors = [
66
+ new BatchSpanProcessor(new exporterCtor({
67
+ url: config.otlpEndpoint,
68
+ timeoutMillis: 30000,
69
+ })),
70
+ ];
71
+ }
55
72
  }
56
73
  catch (err) {
57
74
  // Only a missing module means the optional peers aren't installed. A
@@ -65,27 +82,47 @@ function initTracing(config) {
65
82
  [ATTR_SERVICE_NAME]: config.serviceName,
66
83
  [ATTR_SERVICE_VERSION]: config.serviceVersion || "1.0.0",
67
84
  });
68
- const exporter = new exporterCtor({
69
- url: config.otlpEndpoint,
70
- timeoutMillis: 30000,
71
- });
72
- // SimpleSpanProcessor exports immediately — workers are short-lived
73
85
  provider = new NodeTracerProvider({
74
86
  resource,
75
- spanProcessors: [new SimpleSpanProcessor(exporter)],
87
+ spanProcessors,
76
88
  });
77
89
  provider.register();
78
- tracer = api_1.trace.getTracer(config.serviceName, config.serviceVersion);
79
- logger.info(`Tracing initialized: ${config.serviceName} -> ${config.otlpEndpoint}`);
90
+ // Bind the tracer we just built. trace.getTracer() stays on the first
91
+ // globally registered provider, so a later init would otherwise export
92
+ // into a provider this call does not own.
93
+ tracer = provider.getTracer(config.serviceName, config.serviceVersion);
94
+ logger.info(useCustomProcessors
95
+ ? `Tracing initialized: ${config.serviceName} (custom span processors)`
96
+ : `Tracing initialized: ${config.serviceName} -> ${config.otlpEndpoint}`);
80
97
  }
81
98
  function getTracer() {
82
99
  return tracer;
83
100
  }
84
- async function shutdownTracing() {
85
- if (provider) {
86
- await provider.shutdown();
87
- provider = null;
88
- tracer = null;
101
+ /**
102
+ * Flush and stop tracing. With `timeoutMs`, an unreachable collector cannot
103
+ * hold up process exit past that budget; the timeout rejects.
104
+ */
105
+ async function shutdownTracing(timeoutMs) {
106
+ if (!provider)
107
+ return;
108
+ const shutdown = provider.shutdown();
109
+ provider = null;
110
+ tracer = null;
111
+ if (timeoutMs === undefined) {
112
+ await shutdown;
113
+ return;
114
+ }
115
+ let timer;
116
+ try {
117
+ await Promise.race([
118
+ shutdown,
119
+ new Promise((_, reject) => {
120
+ timer = setTimeout(() => reject(new Error(`Tracing shutdown exceeded its ${timeoutMs}ms budget`)), timeoutMs);
121
+ }),
122
+ ]);
123
+ }
124
+ finally {
125
+ clearTimeout(timer);
89
126
  }
90
127
  }
91
128
  async function flushTracing() {
@@ -129,43 +166,33 @@ async function withSpan(name, fn, attributes) {
129
166
  function getCurrentSpan() {
130
167
  return api_1.trace.getActiveSpan();
131
168
  }
169
+ /** Run `fn` with `span` active, or plainly when tracing produced no span. */
132
170
  function runInSpanContext(span, fn) {
133
- const ctx = api_1.trace.setSpan(api_1.context.active(), span);
134
- return api_1.context.with(ctx, fn);
171
+ if (!span)
172
+ return fn();
173
+ return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), fn);
135
174
  }
136
175
  function createRootSpan(name, attributes) {
137
176
  if (!tracer) {
138
177
  return { span: null, traceparent: null };
139
178
  }
179
+ // Not the active context. Callers that want logs to see this span run
180
+ // the work through runInSpanContext.
140
181
  const span = tracer.startSpan(name, {
141
182
  kind: api_1.SpanKind.SERVER,
142
183
  attributes,
143
184
  });
144
- const spanContext = span.spanContext();
145
- const traceparent = `00-${spanContext.traceId}-${spanContext.spanId}-01`;
146
- return { span, traceparent };
185
+ return { span, traceparent: (0, trace_context_1.formatTraceparent)(span.spanContext()) };
147
186
  }
148
187
  function createChildSpan(name, traceparent, attributes) {
149
188
  if (!tracer) {
150
189
  return null;
151
190
  }
152
- if (!traceparent) {
191
+ const parent = (0, trace_context_1.parseTraceparent)(traceparent);
192
+ if (!parent) {
153
193
  return createSpan(name, attributes);
154
194
  }
155
- // W3C traceparent: 00-traceId-parentSpanId-flags
156
- const parts = traceparent.split("-");
157
- if (parts.length !== 4) {
158
- return createSpan(name, attributes);
159
- }
160
- const traceId = parts[1];
161
- const parentSpanId = parts[2];
162
- const parentContext = api_1.trace.setSpanContext(api_1.context.active(), {
163
- traceId,
164
- spanId: parentSpanId,
165
- traceFlags: 1,
166
- isRemote: true,
167
- });
168
- return tracer.startSpan(name, { kind: api_1.SpanKind.INTERNAL, attributes }, parentContext);
195
+ return tracer.startSpan(name, { kind: api_1.SpanKind.INTERNAL, attributes }, api_1.trace.setSpanContext(api_1.context.active(), parent));
169
196
  }
170
197
  async function withChildSpan(name, traceparent, fn, attributes) {
171
198
  return runInSpan(createChildSpan(name, traceparent, attributes), fn);
@@ -173,7 +200,6 @@ async function withChildSpan(name, traceparent, fn, attributes) {
173
200
  function getTraceparent(span) {
174
201
  if (!span)
175
202
  return null;
176
- const ctx = span.spanContext();
177
- return `00-${ctx.traceId}-${ctx.spanId}-01`;
203
+ return (0, trace_context_1.formatTraceparent)(span.spanContext());
178
204
  }
179
205
  //# sourceMappingURL=otel.js.map
@@ -0,0 +1,12 @@
1
+ import { type SpanContext } from "@opentelemetry/api";
2
+ /** The remote parent a valid `traceparent` names, or null for anything else. */
3
+ export declare function parseTraceparent(value: unknown): SpanContext | null;
4
+ export declare function formatTraceparent(spanContext: SpanContext): string;
5
+ /** A W3C `traceparent` value, or null when the input is not one. */
6
+ export declare function traceparentHeader(value: unknown): string | null;
7
+ /** W3C ids of the active span. Empty when the log is outside a real span. */
8
+ export declare function currentTraceLogFields(): {
9
+ trace_id?: string;
10
+ span_id?: string;
11
+ };
12
+ //# sourceMappingURL=trace-context.d.ts.map
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTraceparent = parseTraceparent;
4
+ exports.formatTraceparent = formatTraceparent;
5
+ exports.traceparentHeader = traceparentHeader;
6
+ exports.currentTraceLogFields = currentTraceLogFields;
7
+ const api_1 = require("@opentelemetry/api");
8
+ // The only W3C `traceparent` parser and formatter. Depends on the OTel API
9
+ // alone, so the logger can import it without a cycle through otel.ts.
10
+ /** The remote parent a valid `traceparent` names, or null for anything else. */
11
+ function parseTraceparent(value) {
12
+ if (typeof value !== "string" || value !== value.toLowerCase())
13
+ return null;
14
+ const [version, traceId, spanId, flags, ...rest] = value.split("-");
15
+ if (version !== "00" || rest.length > 0 || flags?.length !== 2)
16
+ return null;
17
+ const traceFlags = Number.parseInt(flags, 16);
18
+ const spanContext = {
19
+ traceId: traceId ?? "",
20
+ spanId: spanId ?? "",
21
+ traceFlags,
22
+ isRemote: true,
23
+ };
24
+ // The round trip rejects non-hex and signed flags without a pattern.
25
+ return traceFlags >= 0 &&
26
+ formatFlags(traceFlags) === flags &&
27
+ api_1.trace.isSpanContextValid(spanContext)
28
+ ? spanContext
29
+ : null;
30
+ }
31
+ function formatTraceparent(spanContext) {
32
+ return `00-${spanContext.traceId}-${spanContext.spanId}-${formatFlags(spanContext.traceFlags)}`;
33
+ }
34
+ function formatFlags(traceFlags) {
35
+ return traceFlags.toString(16).padStart(2, "0");
36
+ }
37
+ /** A W3C `traceparent` value, or null when the input is not one. */
38
+ function traceparentHeader(value) {
39
+ const spanContext = parseTraceparent(value);
40
+ return spanContext ? formatTraceparent(spanContext) : null;
41
+ }
42
+ /** W3C ids of the active span. Empty when the log is outside a real span. */
43
+ function currentTraceLogFields() {
44
+ const spanContext = api_1.trace.getActiveSpan()?.spanContext();
45
+ if (!spanContext || !api_1.trace.isSpanContextValid(spanContext)) {
46
+ return {};
47
+ }
48
+ return { trace_id: spanContext.traceId, span_id: spanContext.spanId };
49
+ }
50
+ //# sourceMappingURL=trace-context.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobu/core",
3
- "version": "24.3.0",
3
+ "version": "24.4.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Core types and utilities for Lobu agent platform",
6
6
  "repository": {