@ogcio/o11y-sdk-node 0.2.0 → 0.3.1

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +158 -13
  3. package/dist/lib/config-manager.d.ts +3 -0
  4. package/dist/lib/config-manager.js +11 -0
  5. package/dist/lib/exporter/console.js +3 -4
  6. package/dist/lib/exporter/grpc.js +14 -13
  7. package/dist/lib/exporter/http.d.ts +1 -1
  8. package/dist/lib/exporter/http.js +14 -13
  9. package/dist/lib/exporter/pii-exporter-decorator.d.ts +20 -0
  10. package/dist/lib/exporter/pii-exporter-decorator.js +104 -0
  11. package/dist/lib/exporter/processor-config.d.ts +5 -0
  12. package/dist/lib/exporter/processor-config.js +16 -0
  13. package/dist/lib/index.d.ts +18 -4
  14. package/dist/lib/instrumentation.node.js +13 -11
  15. package/dist/lib/internals/hooks.d.ts +3 -0
  16. package/dist/lib/internals/hooks.js +12 -0
  17. package/dist/lib/internals/pii-detection.d.ts +17 -0
  18. package/dist/lib/internals/pii-detection.js +116 -0
  19. package/dist/lib/internals/shared-metrics.d.ts +7 -0
  20. package/dist/lib/internals/shared-metrics.js +18 -0
  21. package/dist/lib/traces.d.ts +20 -1
  22. package/dist/lib/traces.js +47 -1
  23. package/dist/package.json +3 -2
  24. package/dist/vitest.config.js +7 -1
  25. package/lib/config-manager.ts +16 -0
  26. package/lib/exporter/console.ts +6 -4
  27. package/lib/exporter/grpc.ts +34 -21
  28. package/lib/exporter/http.ts +33 -20
  29. package/lib/exporter/pii-exporter-decorator.ts +152 -0
  30. package/lib/exporter/processor-config.ts +23 -0
  31. package/lib/index.ts +19 -4
  32. package/lib/instrumentation.node.ts +16 -16
  33. package/lib/internals/hooks.ts +14 -0
  34. package/lib/internals/pii-detection.ts +145 -0
  35. package/lib/internals/shared-metrics.ts +34 -0
  36. package/lib/traces.ts +74 -1
  37. package/package.json +3 -2
  38. package/test/config-manager.test.ts +34 -0
  39. package/test/exporter/pii-exporter-decorator.test.ts +88 -0
  40. package/test/integration/{integration.test.ts → http-tracing.integration.test.ts} +0 -2
  41. package/test/integration/pii.integration.test.ts +68 -0
  42. package/test/integration/run.sh +2 -2
  43. package/test/internals/hooks.test.ts +45 -0
  44. package/test/internals/pii-detection.test.ts +141 -0
  45. package/test/internals/shared-metrics.test.ts +34 -0
  46. package/test/node-config.test.ts +59 -14
  47. package/test/processor/enrich-span-processor.test.ts +2 -54
  48. package/test/traces/active-span.test.ts +28 -0
  49. package/test/traces/with-span.test.ts +340 -0
  50. package/test/utils/alloy-log-parser.ts +7 -0
  51. package/test/utils/mock-signals.ts +144 -0
  52. package/vitest.config.ts +7 -1
@@ -0,0 +1,340 @@
1
+ import { Span, SpanOptions, SpanStatusCode, trace } from "@opentelemetry/api";
2
+ import { TraceState } from "@opentelemetry/core";
3
+ import { NodeSDK } from "@opentelemetry/sdk-node";
4
+ import {
5
+ InMemorySpanExporter,
6
+ SimpleSpanProcessor,
7
+ SpanProcessor,
8
+ } from "@opentelemetry/sdk-trace-base";
9
+ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
10
+ import { setNodeSdkConfig } from "../../lib/config-manager.js";
11
+ import { getActiveSpan, withSpan } from "../../lib/traces.js";
12
+
13
+ describe("withSpan", () => {
14
+ let memoryExporter: InMemorySpanExporter;
15
+ let spanProcessor: SpanProcessor;
16
+ let sdk: NodeSDK;
17
+
18
+ beforeAll(() => {
19
+ memoryExporter = new InMemorySpanExporter();
20
+ spanProcessor = new SimpleSpanProcessor(memoryExporter);
21
+ sdk = new NodeSDK({
22
+ spanProcessors: [spanProcessor],
23
+ instrumentations: [],
24
+ });
25
+
26
+ setNodeSdkConfig({
27
+ collectorUrl: "http://localhost:4317",
28
+ });
29
+ sdk.start();
30
+ });
31
+
32
+ afterEach(async () => {
33
+ // Flush any remaining spans
34
+ await spanProcessor.forceFlush();
35
+ // Clean up
36
+ memoryExporter.reset();
37
+ });
38
+
39
+ afterAll(async () => {
40
+ await sdk.shutdown();
41
+ });
42
+
43
+ it("should handle simple synchronous usage", async ({}) => {
44
+ let capturedSpan: Span;
45
+
46
+ await withSpan({
47
+ spanName: "test-sync-span",
48
+ fn: (span: Span) => {
49
+ capturedSpan = span;
50
+ },
51
+ });
52
+
53
+ await spanProcessor.forceFlush();
54
+ const spans = memoryExporter.getFinishedSpans();
55
+ expect(spans).toHaveLength(1);
56
+ expect(spans[0].name).toBe("test-sync-span");
57
+ expect(spans[0].status.code).toBe(SpanStatusCode.OK);
58
+ expect(capturedSpan).toBeTruthy();
59
+ expect(capturedSpan.spanContext().traceId).toBe(
60
+ spans[0].spanContext().traceId,
61
+ );
62
+ });
63
+
64
+ it("should handle synchronous functions that throw errors", async ({}) => {
65
+ const error = new Error("Sync error");
66
+
67
+ await expect(
68
+ withSpan({
69
+ spanName: "test-sync-error-span",
70
+ fn: () => {
71
+ throw error;
72
+ },
73
+ }),
74
+ ).rejects.toThrow(error.message);
75
+
76
+ await spanProcessor.forceFlush();
77
+ const spans = memoryExporter.getFinishedSpans();
78
+ expect(spans).toHaveLength(1);
79
+ expect(spans[0].name).toBe("test-sync-error-span");
80
+ expect(spans[0].status.code).toBe(SpanStatusCode.ERROR);
81
+ expect(spans[0].status.message).toBe(error.message);
82
+ expect(spans[0].events).toHaveLength(1);
83
+ expect(spans[0].events[0].name).toBe("exception");
84
+ });
85
+
86
+ it("should handle asynchronous functions correctly", async ({}) => {
87
+ let capturedSpan: Span;
88
+
89
+ await withSpan({
90
+ spanName: "test-async-span",
91
+ fn: async (span: Span) => {
92
+ capturedSpan = span;
93
+ await new Promise((resolve) => setTimeout(resolve, 10));
94
+ return "async-result";
95
+ },
96
+ });
97
+
98
+ await spanProcessor.forceFlush();
99
+ const spans = memoryExporter.getFinishedSpans();
100
+ expect(spans).toHaveLength(1);
101
+ expect(spans[0].name).toBe("test-async-span");
102
+ expect(spans[0].status.code).toBe(SpanStatusCode.OK);
103
+ expect(capturedSpan).toBeTruthy();
104
+ expect(capturedSpan.spanContext().traceId).toBe(
105
+ spans[0].spanContext().traceId,
106
+ );
107
+ });
108
+
109
+ it("should handle asynchronous functions that reject", async () => {
110
+ const error = new Error("Async error");
111
+
112
+ await expect(
113
+ withSpan({
114
+ spanName: "test-async-error-span",
115
+ fn: async () => {
116
+ await new Promise((resolve) => setTimeout(resolve, 10));
117
+ throw error;
118
+ },
119
+ }),
120
+ ).rejects.toThrow(error.message);
121
+
122
+ await spanProcessor.forceFlush();
123
+ const spans = memoryExporter.getFinishedSpans();
124
+ expect(spans).toHaveLength(1);
125
+ expect(spans[0].name).toBe("test-async-error-span");
126
+ expect(spans[0].status.code).toBe(SpanStatusCode.ERROR);
127
+ expect(spans[0].status.message).toBe(error.message);
128
+ expect(spans[0].events).toHaveLength(1);
129
+ expect(spans[0].events[0].name).toBe("exception");
130
+ });
131
+
132
+ it("should handle non-Error exceptions", async () => {
133
+ const nonErrorException = { message: "Not an error object", code: 500 };
134
+
135
+ await expect(
136
+ withSpan({
137
+ spanName: "test-non-error-span",
138
+ fn: () => {
139
+ throw nonErrorException;
140
+ },
141
+ }),
142
+ ).rejects.toEqual(nonErrorException);
143
+
144
+ const spans = memoryExporter.getFinishedSpans();
145
+ expect(spans).toHaveLength(1);
146
+ expect(spans[0].status.code).toBe(SpanStatusCode.ERROR);
147
+ expect(spans[0].status.message).toBe(JSON.stringify(nonErrorException));
148
+ expect(spans[0].events).toHaveLength(1);
149
+ expect(spans[0].events[0].name).toBe("exception");
150
+ });
151
+
152
+ it("should ensure span is ended even when errors occur", async () => {
153
+ const error = new Error("Test error");
154
+
155
+ await expect(
156
+ withSpan({
157
+ spanName: "test-finally-span",
158
+ fn: () => {
159
+ throw error;
160
+ },
161
+ }),
162
+ ).rejects.toThrow("Test error");
163
+
164
+ const spans = memoryExporter.getFinishedSpans();
165
+ expect(spans).toHaveLength(1);
166
+ expect(spans[0].ended).toBe(true);
167
+ });
168
+
169
+ it("should pass span options to tracer", async () => {
170
+ const spanOptions: SpanOptions = {
171
+ attributes: { "custom.attribute": "custom-value" },
172
+ kind: 1,
173
+ };
174
+
175
+ await withSpan({
176
+ spanName: "test-options-span",
177
+ spanOptions,
178
+ fn: () => "result",
179
+ });
180
+
181
+ await spanProcessor.forceFlush();
182
+ const spans = memoryExporter.getFinishedSpans();
183
+ expect(spans).toHaveLength(1);
184
+ expect(spans[0].attributes["custom.attribute"]).toBe("custom-value");
185
+ expect(spans[0].kind).toBe(1);
186
+ });
187
+
188
+ it("should use custom tracer name", async () => {
189
+ const customTracerName = "custom-tracer";
190
+
191
+ await withSpan({
192
+ traceName: customTracerName,
193
+ spanName: "test-custom-tracer-span",
194
+ fn: () => "result",
195
+ });
196
+
197
+ await spanProcessor.forceFlush();
198
+ const spans = memoryExporter.getFinishedSpans();
199
+ expect(spans).toHaveLength(1);
200
+ expect(spans[0].name).toBe("test-custom-tracer-span");
201
+ expect(spans[0].instrumentationScope.name).toBe(customTracerName);
202
+ });
203
+
204
+ it("should use default tracer name when not specified", async () => {
205
+ await withSpan({
206
+ spanName: "test-default-tracer-span",
207
+ fn: () => "result",
208
+ });
209
+
210
+ await spanProcessor.forceFlush();
211
+ const defaultSpans = memoryExporter.getFinishedSpans();
212
+ expect(defaultSpans).toHaveLength(1);
213
+ expect(defaultSpans[0].name).toBe("test-default-tracer-span");
214
+ expect(defaultSpans[0].instrumentationScope.name).toBe("o11y-sdk");
215
+
216
+ memoryExporter.reset();
217
+
218
+ setNodeSdkConfig({
219
+ collectorUrl: "",
220
+ serviceName: "test-service",
221
+ serviceVersion: "v1.0.0",
222
+ });
223
+
224
+ await withSpan({
225
+ spanName: "test-default-tracer-span",
226
+ fn: () => "result",
227
+ });
228
+ await spanProcessor.forceFlush();
229
+ const spans = memoryExporter.getFinishedSpans();
230
+ expect(spans).toHaveLength(1);
231
+ expect(spans[0].name).toBe("test-default-tracer-span");
232
+ expect(spans[0].instrumentationScope.name).toBe("test-service");
233
+ expect(spans[0].instrumentationScope.version).toBe("v1.0.0");
234
+ });
235
+
236
+ it("should allow function to interact with span context", async () => {
237
+ let receivedSpan: Span;
238
+
239
+ await withSpan({
240
+ spanName: "test-span-context",
241
+ fn: (span: Span) => {
242
+ receivedSpan = span;
243
+ span.spanContext().traceState = new TraceState(
244
+ "alpha=aaaaaaaaaaaa,bravo=bbbbbbbbbbbb",
245
+ );
246
+ },
247
+ });
248
+
249
+ await spanProcessor.forceFlush();
250
+ const spans = memoryExporter.getFinishedSpans();
251
+ expect(spans).toHaveLength(1);
252
+ expect(receivedSpan).toBeTruthy();
253
+ expect(receivedSpan.spanContext().traceId).toBe(
254
+ spans[0].spanContext().traceId,
255
+ );
256
+ expect(receivedSpan.spanContext().spanId).toBe(
257
+ spans[0].spanContext().spanId,
258
+ );
259
+ expect(spans[0].spanContext().traceState.serialize()).toStrictEqual(
260
+ "alpha=aaaaaaaaaaaa,bravo=bbbbbbbbbbbb",
261
+ );
262
+ });
263
+
264
+ it("should preserve context across setTimeout", async () => {
265
+ await withSpan({
266
+ spanName: "test-timeout-context",
267
+ fn: async (span: Span) => {
268
+ return new Promise((resolve) => {
269
+ setTimeout(() => {
270
+ getActiveSpan().addEvent("promise-resolved", {
271
+ result: "timeout-result",
272
+ });
273
+ resolve("timeout-result");
274
+ }, 10);
275
+ });
276
+ },
277
+ });
278
+
279
+ let newSpan: Span;
280
+ await trace
281
+ .getTracer("some-tracer")
282
+ .startActiveSpan("other-context", async (span) => {
283
+ newSpan = span;
284
+ span.addEvent("other-context-event", {
285
+ result: "other-context-result",
286
+ });
287
+ });
288
+
289
+ newSpan.addEvent("another-context-event", {
290
+ result: "another-context-result",
291
+ });
292
+ newSpan.setStatus({ code: SpanStatusCode.OK });
293
+ newSpan.end();
294
+ await spanProcessor.forceFlush();
295
+ const spans = memoryExporter.getFinishedSpans();
296
+ expect(spans).toHaveLength(2);
297
+
298
+ const timeoutSpan = spans.find((s) => s.name === "test-timeout-context");
299
+ expect(timeoutSpan.status.code).toBe(SpanStatusCode.OK);
300
+ expect(timeoutSpan.events).toHaveLength(1);
301
+ expect(timeoutSpan.events[0].name).toStrictEqual("promise-resolved");
302
+
303
+ const otherTrackedSpan = spans.find((s) => s.name === "other-context");
304
+ expect(otherTrackedSpan.status.code).toBe(SpanStatusCode.OK);
305
+ expect(otherTrackedSpan.events).toHaveLength(2);
306
+ expect(otherTrackedSpan.events[0].name).toStrictEqual(
307
+ "other-context-event",
308
+ );
309
+ expect(otherTrackedSpan.events[1].name).toStrictEqual(
310
+ "another-context-event",
311
+ );
312
+ });
313
+
314
+ it("should handle nested spans correctly", async () => {
315
+ await withSpan({
316
+ spanName: "outer-span",
317
+ fn: async () => {
318
+ await withSpan({
319
+ spanName: "inner-span",
320
+ fn: async () => {
321
+ await new Promise((resolve) => setTimeout(resolve, 1));
322
+ },
323
+ });
324
+ },
325
+ });
326
+
327
+ await spanProcessor.forceFlush();
328
+ const spans = memoryExporter.getFinishedSpans();
329
+ expect(spans).toHaveLength(2);
330
+
331
+ const innerSpan = spans.find((s) => s.name === "inner-span");
332
+ const outerSpan = spans.find((s) => s.name === "outer-span");
333
+
334
+ expect(innerSpan).toBeTruthy();
335
+ expect(outerSpan).toBeTruthy();
336
+ expect(innerSpan!.parentSpanContext.spanId).toBe(
337
+ outerSpan!.spanContext().spanId,
338
+ );
339
+ });
340
+ });
@@ -40,6 +40,13 @@ export function parseLog(
40
40
  // Additional metadata at the end, store it separately
41
41
  jsonObject["metadata"] = line;
42
42
  }
43
+
44
+ if (line.includes("Body:")) {
45
+ const match = line.match(/Body:\s+(\w+)\((.+)\)/);
46
+ if (match) {
47
+ jsonObject["log_body"] = match[2];
48
+ }
49
+ }
43
50
  });
44
51
 
45
52
  return jsonObject;
@@ -0,0 +1,144 @@
1
+ import type {
2
+ Span,
3
+ SpanContext,
4
+ AttributeValue,
5
+ SpanStatus,
6
+ TimeInput,
7
+ Link,
8
+ Exception,
9
+ Attributes,
10
+ TraceState,
11
+ } from "@opentelemetry/api";
12
+
13
+ export class MockSpan implements Span {
14
+ public attributes: Record<string, AttributeValue> = {};
15
+ public events: {
16
+ name: string;
17
+ attributes?: Attributes | TimeInput;
18
+ startTime?: TimeInput;
19
+ }[] = [];
20
+ public links: Link[] = [];
21
+ public status?: SpanStatus;
22
+ public updatedName?: string;
23
+ public ended: boolean = false;
24
+ public endTime?: TimeInput;
25
+ public exceptions: { exception: Exception; time?: TimeInput }[] = [];
26
+
27
+ public resource: { attributes: Attributes } = { attributes: {} };
28
+
29
+ spanContext(): SpanContext {
30
+ return {
31
+ traceId: "test-trace-id",
32
+ spanId: "test-span-id",
33
+ traceFlags: 1,
34
+ };
35
+ }
36
+
37
+ setAttribute(key: string, value: AttributeValue): this {
38
+ this.attributes[key] = value;
39
+ return this;
40
+ }
41
+
42
+ setAttributes(attributes: Attributes): this {
43
+ Object.assign(this.attributes, attributes);
44
+ return this;
45
+ }
46
+
47
+ addEvent(
48
+ name: string,
49
+ attributesOrStartTime?: Attributes | TimeInput,
50
+ startTime?: TimeInput,
51
+ ): this {
52
+ this.events.push({ name, attributes: attributesOrStartTime, startTime });
53
+ return this;
54
+ }
55
+
56
+ addLink(link: Link): this {
57
+ this.links.push(link);
58
+ return this;
59
+ }
60
+
61
+ addLinks(links: Link[]): this {
62
+ this.links.push(...links);
63
+ return this;
64
+ }
65
+
66
+ setStatus(status: SpanStatus): this {
67
+ this.status = status;
68
+ return this;
69
+ }
70
+
71
+ updateName(name: string): this {
72
+ this.updatedName = name;
73
+ return this;
74
+ }
75
+
76
+ end(endTime?: TimeInput): void {
77
+ this.ended = true;
78
+ this.endTime = endTime;
79
+ }
80
+
81
+ isRecording(): boolean {
82
+ return true;
83
+ }
84
+
85
+ recordException(exception: Exception, time?: TimeInput): void {
86
+ this.exceptions.push({ exception, time });
87
+ }
88
+
89
+ reset(): void {
90
+ this.attributes = {};
91
+ this.events = [];
92
+ this.links = [];
93
+ this.status = undefined;
94
+ this.updatedName = undefined;
95
+ this.ended = false;
96
+ this.endTime = undefined;
97
+ this.exceptions = [];
98
+ this.resource = { attributes: {} };
99
+ }
100
+ }
101
+
102
+ export class TestTraceState implements TraceState {
103
+ private entries: Map<string, string>;
104
+
105
+ constructor(initEntries?: [string, string][]) {
106
+ this.entries = new Map(initEntries ?? []);
107
+ }
108
+
109
+ set(key: string, value: string): TraceState {
110
+ const newEntries: [string, string][] = [[key, value]];
111
+ for (const [k, v] of this.entries.entries()) {
112
+ if (k !== key) {
113
+ newEntries.push([k, v]);
114
+ }
115
+ }
116
+ return new TestTraceState(newEntries);
117
+ }
118
+
119
+ unset(key: string): TraceState {
120
+ const newEntries: [string, string][] = [];
121
+ for (const [k, v] of this.entries.entries()) {
122
+ if (k !== key) {
123
+ newEntries.push([k, v]);
124
+ }
125
+ }
126
+ return new TestTraceState(newEntries);
127
+ }
128
+
129
+ get(key: string): string | undefined {
130
+ return this.entries.get(key);
131
+ }
132
+
133
+ serialize(): string {
134
+ return Array.from(this.entries)
135
+ .slice(0, 32) // Enforce 32-member max
136
+ .map(([key, value]) => `${key}=${value}`)
137
+ .join(",");
138
+ }
139
+
140
+ // Optional: for testing/debugging
141
+ toJSON(): Record<string, string> {
142
+ return Object.fromEntries(this.entries);
143
+ }
144
+ }
package/vitest.config.ts CHANGED
@@ -25,7 +25,13 @@ export default defineConfig({
25
25
  projects: [
26
26
  {
27
27
  test: {
28
- include: ["**/test/*.test.ts", "**/test/processor/*.test.ts"],
28
+ include: [
29
+ "**/test/*.test.ts",
30
+ "**/test/processor/*.test.ts",
31
+ "**/test/traces/*.test.ts",
32
+ "**/test/internals/*.test.ts",
33
+ "**/test/exporter/*.test.ts",
34
+ ],
29
35
  name: "unit",
30
36
  },
31
37
  },