autotel 2.1.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.
Files changed (272) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1946 -0
  3. package/dist/chunk-2LNRY4QK.js +273 -0
  4. package/dist/chunk-2LNRY4QK.js.map +1 -0
  5. package/dist/chunk-3HENGDW2.js +587 -0
  6. package/dist/chunk-3HENGDW2.js.map +1 -0
  7. package/dist/chunk-4OAT42CA.cjs +73 -0
  8. package/dist/chunk-4OAT42CA.cjs.map +1 -0
  9. package/dist/chunk-5GWX5LFW.js +70 -0
  10. package/dist/chunk-5GWX5LFW.js.map +1 -0
  11. package/dist/chunk-5R2M36QB.js +195 -0
  12. package/dist/chunk-5R2M36QB.js.map +1 -0
  13. package/dist/chunk-5ZN622AO.js +73 -0
  14. package/dist/chunk-5ZN622AO.js.map +1 -0
  15. package/dist/chunk-77MSMAUQ.cjs +498 -0
  16. package/dist/chunk-77MSMAUQ.cjs.map +1 -0
  17. package/dist/chunk-ABPEQ6RK.cjs +596 -0
  18. package/dist/chunk-ABPEQ6RK.cjs.map +1 -0
  19. package/dist/chunk-BWYGJKRB.js +95 -0
  20. package/dist/chunk-BWYGJKRB.js.map +1 -0
  21. package/dist/chunk-BZHG5IZ4.js +73 -0
  22. package/dist/chunk-BZHG5IZ4.js.map +1 -0
  23. package/dist/chunk-G7VZBCD6.cjs +35 -0
  24. package/dist/chunk-G7VZBCD6.cjs.map +1 -0
  25. package/dist/chunk-GVLK7YUU.cjs +30 -0
  26. package/dist/chunk-GVLK7YUU.cjs.map +1 -0
  27. package/dist/chunk-HCCXC7XG.js +205 -0
  28. package/dist/chunk-HCCXC7XG.js.map +1 -0
  29. package/dist/chunk-HE6T6FIX.cjs +203 -0
  30. package/dist/chunk-HE6T6FIX.cjs.map +1 -0
  31. package/dist/chunk-KIXWPOCO.cjs +100 -0
  32. package/dist/chunk-KIXWPOCO.cjs.map +1 -0
  33. package/dist/chunk-KVGNW3FC.js +87 -0
  34. package/dist/chunk-KVGNW3FC.js.map +1 -0
  35. package/dist/chunk-LITNXTTT.js +3 -0
  36. package/dist/chunk-LITNXTTT.js.map +1 -0
  37. package/dist/chunk-M4ANN7RL.js +114 -0
  38. package/dist/chunk-M4ANN7RL.js.map +1 -0
  39. package/dist/chunk-NC52UBR2.cjs +32 -0
  40. package/dist/chunk-NC52UBR2.cjs.map +1 -0
  41. package/dist/chunk-NHCNRQD3.cjs +212 -0
  42. package/dist/chunk-NHCNRQD3.cjs.map +1 -0
  43. package/dist/chunk-NZ72VDNY.cjs +4 -0
  44. package/dist/chunk-NZ72VDNY.cjs.map +1 -0
  45. package/dist/chunk-P6JUDYNO.js +57 -0
  46. package/dist/chunk-P6JUDYNO.js.map +1 -0
  47. package/dist/chunk-RJYY7BWX.js +1349 -0
  48. package/dist/chunk-RJYY7BWX.js.map +1 -0
  49. package/dist/chunk-TRI4V5BF.cjs +126 -0
  50. package/dist/chunk-TRI4V5BF.cjs.map +1 -0
  51. package/dist/chunk-UL33I6IS.js +139 -0
  52. package/dist/chunk-UL33I6IS.js.map +1 -0
  53. package/dist/chunk-URRW6M2C.cjs +61 -0
  54. package/dist/chunk-URRW6M2C.cjs.map +1 -0
  55. package/dist/chunk-UY3UYPBZ.cjs +77 -0
  56. package/dist/chunk-UY3UYPBZ.cjs.map +1 -0
  57. package/dist/chunk-W3253FGB.cjs +277 -0
  58. package/dist/chunk-W3253FGB.cjs.map +1 -0
  59. package/dist/chunk-W7LHZVQF.js +26 -0
  60. package/dist/chunk-W7LHZVQF.js.map +1 -0
  61. package/dist/chunk-WBWNM6LB.cjs +1360 -0
  62. package/dist/chunk-WBWNM6LB.cjs.map +1 -0
  63. package/dist/chunk-WFJ7L2RV.js +494 -0
  64. package/dist/chunk-WFJ7L2RV.js.map +1 -0
  65. package/dist/chunk-X4RMFFMR.js +28 -0
  66. package/dist/chunk-X4RMFFMR.js.map +1 -0
  67. package/dist/chunk-Y4Y2S7BM.cjs +92 -0
  68. package/dist/chunk-Y4Y2S7BM.cjs.map +1 -0
  69. package/dist/chunk-YLPNXZFI.cjs +143 -0
  70. package/dist/chunk-YLPNXZFI.cjs.map +1 -0
  71. package/dist/chunk-YTXEZ4SD.cjs +77 -0
  72. package/dist/chunk-YTXEZ4SD.cjs.map +1 -0
  73. package/dist/chunk-Z6ZWNWWR.js +30 -0
  74. package/dist/chunk-Z6ZWNWWR.js.map +1 -0
  75. package/dist/config.cjs +26 -0
  76. package/dist/config.cjs.map +1 -0
  77. package/dist/config.d.cts +75 -0
  78. package/dist/config.d.ts +75 -0
  79. package/dist/config.js +5 -0
  80. package/dist/config.js.map +1 -0
  81. package/dist/db.cjs +233 -0
  82. package/dist/db.cjs.map +1 -0
  83. package/dist/db.d.cts +123 -0
  84. package/dist/db.d.ts +123 -0
  85. package/dist/db.js +228 -0
  86. package/dist/db.js.map +1 -0
  87. package/dist/decorators.cjs +67 -0
  88. package/dist/decorators.cjs.map +1 -0
  89. package/dist/decorators.d.cts +91 -0
  90. package/dist/decorators.d.ts +91 -0
  91. package/dist/decorators.js +65 -0
  92. package/dist/decorators.js.map +1 -0
  93. package/dist/event-subscriber.cjs +6 -0
  94. package/dist/event-subscriber.cjs.map +1 -0
  95. package/dist/event-subscriber.d.cts +116 -0
  96. package/dist/event-subscriber.d.ts +116 -0
  97. package/dist/event-subscriber.js +3 -0
  98. package/dist/event-subscriber.js.map +1 -0
  99. package/dist/event-testing.cjs +21 -0
  100. package/dist/event-testing.cjs.map +1 -0
  101. package/dist/event-testing.d.cts +110 -0
  102. package/dist/event-testing.d.ts +110 -0
  103. package/dist/event-testing.js +4 -0
  104. package/dist/event-testing.js.map +1 -0
  105. package/dist/event.cjs +30 -0
  106. package/dist/event.cjs.map +1 -0
  107. package/dist/event.d.cts +282 -0
  108. package/dist/event.d.ts +282 -0
  109. package/dist/event.js +13 -0
  110. package/dist/event.js.map +1 -0
  111. package/dist/exporters.cjs +17 -0
  112. package/dist/exporters.cjs.map +1 -0
  113. package/dist/exporters.d.cts +1 -0
  114. package/dist/exporters.d.ts +1 -0
  115. package/dist/exporters.js +4 -0
  116. package/dist/exporters.js.map +1 -0
  117. package/dist/functional.cjs +46 -0
  118. package/dist/functional.cjs.map +1 -0
  119. package/dist/functional.d.cts +478 -0
  120. package/dist/functional.d.ts +478 -0
  121. package/dist/functional.js +13 -0
  122. package/dist/functional.js.map +1 -0
  123. package/dist/http.cjs +189 -0
  124. package/dist/http.cjs.map +1 -0
  125. package/dist/http.d.cts +169 -0
  126. package/dist/http.d.ts +169 -0
  127. package/dist/http.js +184 -0
  128. package/dist/http.js.map +1 -0
  129. package/dist/index.cjs +333 -0
  130. package/dist/index.cjs.map +1 -0
  131. package/dist/index.d.cts +758 -0
  132. package/dist/index.d.ts +758 -0
  133. package/dist/index.js +143 -0
  134. package/dist/index.js.map +1 -0
  135. package/dist/instrumentation.cjs +182 -0
  136. package/dist/instrumentation.cjs.map +1 -0
  137. package/dist/instrumentation.d.cts +49 -0
  138. package/dist/instrumentation.d.ts +49 -0
  139. package/dist/instrumentation.js +179 -0
  140. package/dist/instrumentation.js.map +1 -0
  141. package/dist/logger.cjs +19 -0
  142. package/dist/logger.cjs.map +1 -0
  143. package/dist/logger.d.cts +146 -0
  144. package/dist/logger.d.ts +146 -0
  145. package/dist/logger.js +6 -0
  146. package/dist/logger.js.map +1 -0
  147. package/dist/metric-helpers.cjs +31 -0
  148. package/dist/metric-helpers.cjs.map +1 -0
  149. package/dist/metric-helpers.d.cts +13 -0
  150. package/dist/metric-helpers.d.ts +13 -0
  151. package/dist/metric-helpers.js +6 -0
  152. package/dist/metric-helpers.js.map +1 -0
  153. package/dist/metric-testing.cjs +21 -0
  154. package/dist/metric-testing.cjs.map +1 -0
  155. package/dist/metric-testing.d.cts +110 -0
  156. package/dist/metric-testing.d.ts +110 -0
  157. package/dist/metric-testing.js +4 -0
  158. package/dist/metric-testing.js.map +1 -0
  159. package/dist/metric.cjs +26 -0
  160. package/dist/metric.cjs.map +1 -0
  161. package/dist/metric.d.cts +240 -0
  162. package/dist/metric.d.ts +240 -0
  163. package/dist/metric.js +9 -0
  164. package/dist/metric.js.map +1 -0
  165. package/dist/processors.cjs +17 -0
  166. package/dist/processors.cjs.map +1 -0
  167. package/dist/processors.d.cts +1 -0
  168. package/dist/processors.d.ts +1 -0
  169. package/dist/processors.js +4 -0
  170. package/dist/processors.js.map +1 -0
  171. package/dist/sampling.cjs +40 -0
  172. package/dist/sampling.cjs.map +1 -0
  173. package/dist/sampling.d.cts +260 -0
  174. package/dist/sampling.d.ts +260 -0
  175. package/dist/sampling.js +7 -0
  176. package/dist/sampling.js.map +1 -0
  177. package/dist/semantic-helpers.cjs +35 -0
  178. package/dist/semantic-helpers.cjs.map +1 -0
  179. package/dist/semantic-helpers.d.cts +442 -0
  180. package/dist/semantic-helpers.d.ts +442 -0
  181. package/dist/semantic-helpers.js +14 -0
  182. package/dist/semantic-helpers.js.map +1 -0
  183. package/dist/tail-sampling-processor.cjs +13 -0
  184. package/dist/tail-sampling-processor.cjs.map +1 -0
  185. package/dist/tail-sampling-processor.d.cts +27 -0
  186. package/dist/tail-sampling-processor.d.ts +27 -0
  187. package/dist/tail-sampling-processor.js +4 -0
  188. package/dist/tail-sampling-processor.js.map +1 -0
  189. package/dist/testing.cjs +286 -0
  190. package/dist/testing.cjs.map +1 -0
  191. package/dist/testing.d.cts +291 -0
  192. package/dist/testing.d.ts +291 -0
  193. package/dist/testing.js +263 -0
  194. package/dist/testing.js.map +1 -0
  195. package/dist/trace-context-DRZdUvVY.d.cts +181 -0
  196. package/dist/trace-context-DRZdUvVY.d.ts +181 -0
  197. package/dist/trace-helpers.cjs +54 -0
  198. package/dist/trace-helpers.cjs.map +1 -0
  199. package/dist/trace-helpers.d.cts +524 -0
  200. package/dist/trace-helpers.d.ts +524 -0
  201. package/dist/trace-helpers.js +5 -0
  202. package/dist/trace-helpers.js.map +1 -0
  203. package/dist/tracer-provider.cjs +21 -0
  204. package/dist/tracer-provider.cjs.map +1 -0
  205. package/dist/tracer-provider.d.cts +169 -0
  206. package/dist/tracer-provider.d.ts +169 -0
  207. package/dist/tracer-provider.js +4 -0
  208. package/dist/tracer-provider.js.map +1 -0
  209. package/package.json +280 -0
  210. package/src/baggage-span-processor.test.ts +202 -0
  211. package/src/baggage-span-processor.ts +98 -0
  212. package/src/circuit-breaker.test.ts +341 -0
  213. package/src/circuit-breaker.ts +184 -0
  214. package/src/config.test.ts +94 -0
  215. package/src/config.ts +169 -0
  216. package/src/db.test.ts +252 -0
  217. package/src/db.ts +447 -0
  218. package/src/decorators.test.ts +203 -0
  219. package/src/decorators.ts +188 -0
  220. package/src/env-config.test.ts +246 -0
  221. package/src/env-config.ts +158 -0
  222. package/src/event-queue.test.ts +222 -0
  223. package/src/event-queue.ts +203 -0
  224. package/src/event-subscriber.ts +136 -0
  225. package/src/event-testing.ts +197 -0
  226. package/src/event.test.ts +718 -0
  227. package/src/event.ts +556 -0
  228. package/src/exporters.ts +96 -0
  229. package/src/functional.test.ts +1059 -0
  230. package/src/functional.ts +2295 -0
  231. package/src/http.test.ts +487 -0
  232. package/src/http.ts +424 -0
  233. package/src/index.ts +158 -0
  234. package/src/init.customization.test.ts +210 -0
  235. package/src/init.integrations.test.ts +366 -0
  236. package/src/init.openllmetry.test.ts +282 -0
  237. package/src/init.protocol.test.ts +215 -0
  238. package/src/init.ts +1426 -0
  239. package/src/instrumentation.test.ts +108 -0
  240. package/src/instrumentation.ts +308 -0
  241. package/src/logger.test.ts +117 -0
  242. package/src/logger.ts +246 -0
  243. package/src/metric-helpers.ts +47 -0
  244. package/src/metric-testing.ts +197 -0
  245. package/src/metric.ts +434 -0
  246. package/src/metrics.test.ts +205 -0
  247. package/src/operation-context.ts +93 -0
  248. package/src/processors.ts +106 -0
  249. package/src/rate-limiter.test.ts +199 -0
  250. package/src/rate-limiter.ts +98 -0
  251. package/src/sampling.test.ts +513 -0
  252. package/src/sampling.ts +428 -0
  253. package/src/semantic-helpers.test.ts +311 -0
  254. package/src/semantic-helpers.ts +584 -0
  255. package/src/shutdown.test.ts +311 -0
  256. package/src/shutdown.ts +222 -0
  257. package/src/stub.integration.test.ts +361 -0
  258. package/src/tail-sampling-processor.test.ts +226 -0
  259. package/src/tail-sampling-processor.ts +51 -0
  260. package/src/testing.ts +670 -0
  261. package/src/trace-context.ts +470 -0
  262. package/src/trace-helpers.new.test.ts +278 -0
  263. package/src/trace-helpers.test.ts +242 -0
  264. package/src/trace-helpers.ts +690 -0
  265. package/src/tracer-provider.test.ts +183 -0
  266. package/src/tracer-provider.ts +266 -0
  267. package/src/track.test.ts +153 -0
  268. package/src/track.ts +120 -0
  269. package/src/validation.test.ts +306 -0
  270. package/src/validation.ts +239 -0
  271. package/src/variable-name-inference.test.ts +178 -0
  272. package/src/variable-name-inference.ts +242 -0
@@ -0,0 +1,108 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import {
3
+ initInstrumentation,
4
+ shutdownInstrumentation,
5
+ } from './instrumentation';
6
+ import type { NodeSDK } from '@opentelemetry/sdk-node';
7
+
8
+ describe('initInstrumentation', () => {
9
+ let sdk: NodeSDK | undefined;
10
+
11
+ afterEach(async () => {
12
+ if (sdk) {
13
+ try {
14
+ await shutdownInstrumentation(sdk);
15
+ } catch {
16
+ // Ignore shutdown errors in tests
17
+ }
18
+ sdk = undefined;
19
+ }
20
+ });
21
+
22
+ it('should initialize with minimal config', async () => {
23
+ sdk = await initInstrumentation({
24
+ serviceName: 'test-service',
25
+ });
26
+
27
+ expect(sdk).toBeDefined();
28
+ });
29
+
30
+ it('should initialize with full config', async () => {
31
+ sdk = await initInstrumentation({
32
+ serviceName: 'test-service',
33
+ serviceVersion: '2.0.0',
34
+ deploymentEnvironment: 'test',
35
+ otlpEndpoint: 'http://localhost:4318',
36
+ });
37
+
38
+ expect(sdk).toBeDefined();
39
+ });
40
+
41
+ it('should support detectResources option', async () => {
42
+ sdk = await initInstrumentation({
43
+ serviceName: 'test-service',
44
+ detectResources: true,
45
+ });
46
+
47
+ expect(sdk).toBeDefined();
48
+ });
49
+
50
+ it('should return NodeSDK instance', async () => {
51
+ sdk = await initInstrumentation({
52
+ serviceName: 'test-service',
53
+ });
54
+
55
+ expect(sdk).toBeDefined();
56
+ expect(typeof sdk.start).toBe('function');
57
+ expect(typeof sdk.shutdown).toBe('function');
58
+ });
59
+ });
60
+
61
+ describe('shutdownInstrumentation', () => {
62
+ it('should shutdown without error', async () => {
63
+ const sdk = await initInstrumentation({
64
+ serviceName: 'test-shutdown',
65
+ });
66
+
67
+ await expect(shutdownInstrumentation(sdk)).resolves.not.toThrow();
68
+ });
69
+
70
+ it('should handle shutdown with no SDK gracefully', async () => {
71
+ // Should warn but not throw
72
+ await expect(shutdownInstrumentation()).resolves.not.toThrow();
73
+ });
74
+
75
+ it('should handle multiple shutdowns gracefully', async () => {
76
+ const sdk = await initInstrumentation({
77
+ serviceName: 'test-multiple-shutdown',
78
+ });
79
+
80
+ await shutdownInstrumentation(sdk);
81
+
82
+ // Second shutdown should not throw
83
+ await expect(shutdownInstrumentation(sdk)).resolves.not.toThrow();
84
+ });
85
+ });
86
+
87
+ describe('SIGTERM handler', () => {
88
+ it('should not add new handlers on subsequent inits', async () => {
89
+ const sdk1 = await initInstrumentation({
90
+ serviceName: 'test-1',
91
+ });
92
+
93
+ const countAfterFirst = process.listenerCount('SIGTERM');
94
+
95
+ const sdk2 = await initInstrumentation({
96
+ serviceName: 'test-2',
97
+ });
98
+
99
+ const countAfterSecond = process.listenerCount('SIGTERM');
100
+
101
+ // Should not add a new handler on second init
102
+ expect(countAfterSecond).toBe(countAfterFirst);
103
+
104
+ // Cleanup
105
+ await shutdownInstrumentation(sdk1);
106
+ await shutdownInstrumentation(sdk2);
107
+ });
108
+ });
@@ -0,0 +1,308 @@
1
+ import { NodeSDK } from '@opentelemetry/sdk-node';
2
+ import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
3
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
4
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
5
+ import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';
6
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
7
+ import { TailSamplingSpanProcessor } from './tail-sampling-processor';
8
+ import { getLogger } from './init';
9
+ import {
10
+ resourceFromAttributes,
11
+ detectResources,
12
+ processDetector,
13
+ hostDetector,
14
+ type Resource,
15
+ type ResourceDetector,
16
+ } from '@opentelemetry/resources';
17
+ import {
18
+ ATTR_SERVICE_NAME,
19
+ ATTR_SERVICE_VERSION,
20
+ } from '@opentelemetry/semantic-conventions/incubating';
21
+ import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
22
+ import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
23
+
24
+ /**
25
+ * Parse OTLP headers string into object format
26
+ * @param headersString - Headers as "key1=value1,key2=value2" or "Authorization=Basic ..."
27
+ * @returns Headers object for OTLP exporters
28
+ */
29
+ function parseOtlpHeaders(headersString?: string): Record<string, string> {
30
+ if (!headersString) return {};
31
+
32
+ const headers: Record<string, string> = {};
33
+ const pairs = headersString.split(',');
34
+
35
+ for (const pair of pairs) {
36
+ const [key, ...valueParts] = pair.split('=');
37
+ if (key && valueParts.length > 0) {
38
+ headers[key.trim()] = valueParts.join('=').trim();
39
+ }
40
+ }
41
+
42
+ return headers;
43
+ }
44
+
45
+ /**
46
+ * Parse resource attributes string into object format
47
+ * @param attributesString - Attributes as "key1=value1,key2=value2"
48
+ * @returns Resource attributes object
49
+ */
50
+ function parseResourceAttributes(
51
+ attributesString?: string,
52
+ ): Record<string, string> {
53
+ if (!attributesString) return {};
54
+
55
+ const attributes: Record<string, string> = {};
56
+ const pairs = attributesString.split(',');
57
+
58
+ for (const pair of pairs) {
59
+ const [key, ...valueParts] = pair.split('=');
60
+ if (key && valueParts.length > 0) {
61
+ attributes[key.trim()] = valueParts.join('=').trim();
62
+ }
63
+ }
64
+
65
+ return attributes;
66
+ }
67
+
68
+ export interface InstrumentationConfig {
69
+ serviceName: string;
70
+ serviceVersion?: string;
71
+ deploymentEnvironment?: string;
72
+ otlpEndpoint?: string;
73
+ /** OTLP headers for authentication (e.g., Grafana Cloud) */
74
+ otlpHeaders?: string;
75
+ /** Resource attributes as comma-separated key=value pairs */
76
+ resourceAttributes?: string;
77
+ /** Enable async resource detection for process/host info (default: false) */
78
+ detectResources?: boolean;
79
+ /**
80
+ * Use selective instrumentation instead of full auto-instrumentation
81
+ * **Default: true** (performance-first)
82
+ *
83
+ * When true, auto-instrumentation is disabled. You can manually add
84
+ * specific instrumentations via the `instrumentations` field.
85
+ * This reduces overhead from ~81% to near-zero based on Platformatic benchmarks.
86
+ *
87
+ * Set to false to enable full auto-instrumentation (not recommended for production).
88
+ *
89
+ * @see https://blogger.platformatic.dev/the-hidden-cost-of-context
90
+ */
91
+ selectiveInstrumentation?: boolean;
92
+
93
+ /**
94
+ * Custom instrumentations to use (only when selectiveInstrumentation is true)
95
+ * @example
96
+ * ```typescript
97
+ * import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'
98
+ *
99
+ * initInstrumentation({
100
+ * serviceName: 'api',
101
+ * selectiveInstrumentation: true,
102
+ * instrumentations: [new HttpInstrumentation()]
103
+ * })
104
+ * ```
105
+ */
106
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
107
+ instrumentations?: any[];
108
+ }
109
+
110
+ /**
111
+ * Initialize OpenTelemetry instrumentation with OTLP exporters
112
+ *
113
+ * This sets up:
114
+ * - Traces (OTLP HTTP)
115
+ * - Metrics (OTLP HTTP)
116
+ * - Logs (OTLP HTTP)
117
+ * - Auto-instrumentation for common Node.js libraries
118
+ *
119
+ * @example
120
+ * // Call this at the very start of your application
121
+ * import { initInstrumentation } from '@your-org/otel-decorators'
122
+ *
123
+ * initInstrumentation({
124
+ * serviceName: 'my-service' }
125
+ * serviceVersion: '1.0.0',
126
+ * deploymentEnvironment: 'production',
127
+ * otlpEndpoint: 'http://localhost:4318'
128
+ * })
129
+ *
130
+ * // Or with async resource detection (top-level await required)
131
+ * await initInstrumentation({
132
+ * serviceName: 'my-service' }
133
+ * detectResources: true
134
+ * })
135
+ */
136
+ // Enables graceful shutdown and prevents SDK leaks on hot-reload
137
+ let currentSDK: NodeSDK | null = null;
138
+ let shutdownHandlerRegistered = false;
139
+
140
+ /**
141
+ * Shutdown the OpenTelemetry SDK gracefully
142
+ * Call this before process exit or during hot-reloads
143
+ */
144
+ export async function shutdownInstrumentation(sdk?: NodeSDK): Promise<void> {
145
+ const sdkToShutdown = sdk || currentSDK;
146
+ if (!sdkToShutdown) {
147
+ getLogger().warn('No SDK to shutdown');
148
+ return;
149
+ }
150
+
151
+ try {
152
+ await sdkToShutdown.shutdown();
153
+ getLogger().info('OpenTelemetry terminated successfully');
154
+ if (sdkToShutdown === currentSDK) {
155
+ currentSDK = null;
156
+ }
157
+ } catch (error) {
158
+ getLogger().error(
159
+ 'Error terminating OpenTelemetry',
160
+ error instanceof Error ? error : undefined,
161
+ );
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ export async function initInstrumentation(
167
+ config: InstrumentationConfig,
168
+ ): Promise<NodeSDK> {
169
+ // Prevents resource leaks on hot-reload or multiple init calls
170
+ if (currentSDK) {
171
+ getLogger().info(
172
+ 'Shutting down existing OpenTelemetry SDK before reinitializing...',
173
+ );
174
+ await shutdownInstrumentation(currentSDK);
175
+ }
176
+
177
+ // Parse OTLP headers and resource attributes
178
+ const otlpHeaders = parseOtlpHeaders(config.otlpHeaders);
179
+ const customResourceAttributes = parseResourceAttributes(
180
+ config.resourceAttributes,
181
+ );
182
+
183
+ let resource: Resource;
184
+
185
+ // Dynamically load optional resource detectors
186
+ const detectors: ResourceDetector[] = [processDetector, hostDetector];
187
+ try {
188
+ const awsDetectors = await import('@opentelemetry/resource-detector-aws');
189
+ detectors.push(
190
+ awsDetectors.awsEc2Detector,
191
+ awsDetectors.awsEcsDetector,
192
+ awsDetectors.awsEksDetector,
193
+ );
194
+ } catch {
195
+ // ignore
196
+ }
197
+ try {
198
+ const gcpDetectors = await import('@opentelemetry/resource-detector-gcp');
199
+ detectors.push(gcpDetectors.gcpDetector);
200
+ } catch {
201
+ // ignore
202
+ }
203
+ try {
204
+ const containerDetectors = await import(
205
+ '@opentelemetry/resource-detector-container'
206
+ );
207
+ detectors.push(containerDetectors.containerDetector);
208
+ } catch {
209
+ // ignore
210
+ }
211
+
212
+ if (config.detectResources) {
213
+ const detectedResource = await detectResources({
214
+ detectors,
215
+ });
216
+
217
+ resource = detectedResource.merge(
218
+ resourceFromAttributes({
219
+ [ATTR_SERVICE_NAME]: config.serviceName,
220
+ [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',
221
+ 'deployment.environment': config.deploymentEnvironment || 'development',
222
+ ...customResourceAttributes, // Merge custom resource attributes
223
+ }),
224
+ );
225
+ } else {
226
+ resource = resourceFromAttributes({
227
+ [ATTR_SERVICE_NAME]: config.serviceName,
228
+ [ATTR_SERVICE_VERSION]: config.serviceVersion || '1.0.0',
229
+ 'deployment.environment': config.deploymentEnvironment || 'development',
230
+ ...customResourceAttributes, // Merge custom resource attributes
231
+ });
232
+ }
233
+
234
+ // Default to selective (near-zero overhead) vs full auto (~81% overhead)
235
+ const instrumentations =
236
+ config.selectiveInstrumentation === false
237
+ ? [getNodeAutoInstrumentations()]
238
+ : config.instrumentations || [];
239
+
240
+ const traceExporter = new OTLPTraceExporter({
241
+ url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/traces`,
242
+ headers: otlpHeaders,
243
+ });
244
+
245
+ // Enables tail sampling via sampling.tail.keep attribute
246
+ const spanProcessor = new TailSamplingSpanProcessor(
247
+ new BatchSpanProcessor(traceExporter),
248
+ );
249
+
250
+ const sdk = new NodeSDK({
251
+ resource,
252
+ spanProcessor, // Use our wrapped processor instead of traceExporter directly
253
+ metricReader: new PeriodicExportingMetricReader({
254
+ exporter: new OTLPMetricExporter({
255
+ url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/metrics`,
256
+ headers: otlpHeaders,
257
+ }),
258
+ }),
259
+ logRecordProcessors: [
260
+ new BatchLogRecordProcessor(
261
+ new OTLPLogExporter({
262
+ url: `${config.otlpEndpoint || 'http://localhost:4318'}/v1/logs`,
263
+ headers: otlpHeaders,
264
+ }),
265
+ ),
266
+ ],
267
+ instrumentations,
268
+ });
269
+
270
+ try {
271
+ await sdk.start();
272
+ getLogger().info('OpenTelemetry instrumentation started successfully');
273
+ } catch (error) {
274
+ getLogger().error(
275
+ 'Failed to start OpenTelemetry SDK',
276
+ error instanceof Error ? error : undefined,
277
+ );
278
+ throw error;
279
+ }
280
+
281
+ // Track current SDK for shutdown handler
282
+ currentSDK = sdk;
283
+
284
+ if (!shutdownHandlerRegistered) {
285
+ shutdownHandlerRegistered = true;
286
+
287
+ const shutdownHandler = () => {
288
+ shutdownInstrumentation()
289
+ .then(() => {
290
+ // eslint-disable-next-line unicorn/no-process-exit
291
+ process.exit(0);
292
+ })
293
+ .catch((error) => {
294
+ getLogger().error(
295
+ 'Shutdown error',
296
+ error instanceof Error ? error : undefined,
297
+ );
298
+ // eslint-disable-next-line unicorn/no-process-exit
299
+ process.exit(1);
300
+ });
301
+ };
302
+
303
+ process.on('SIGTERM', shutdownHandler);
304
+ process.on('SIGINT', shutdownHandler);
305
+ }
306
+
307
+ return sdk;
308
+ }
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { LoggedOperation, type Logger } from './logger';
3
+
4
+ describe('Logger interface', () => {
5
+ it('should work with custom logger implementations', () => {
6
+ const mockLogger: Logger = {
7
+ info: vi.fn(),
8
+ warn: vi.fn(),
9
+ error: vi.fn(),
10
+ debug: vi.fn(),
11
+ };
12
+
13
+ mockLogger.info('Test message', { key: 'value' });
14
+ expect(mockLogger.info).toHaveBeenCalledWith('Test message', {
15
+ key: 'value',
16
+ });
17
+ });
18
+
19
+ it('should support error method with optional error parameter', () => {
20
+ const mockLogger: Logger = {
21
+ info: vi.fn(),
22
+ warn: vi.fn(),
23
+ error: vi.fn(),
24
+ debug: vi.fn(),
25
+ };
26
+
27
+ const error = new Error('Test error');
28
+ mockLogger.error('Error occurred', error, { context: 'test' });
29
+ expect(mockLogger.error).toHaveBeenCalledWith('Error occurred', error, {
30
+ context: 'test',
31
+ });
32
+ });
33
+ });
34
+
35
+ describe('@LoggedOperation decorator', () => {
36
+ it('should support simple string syntax', async () => {
37
+ class TestService {
38
+ constructor(public deps: { log: Logger }) {}
39
+
40
+ @LoggedOperation('test.operation')
41
+ async testMethod() {
42
+ return 'result';
43
+ }
44
+ }
45
+
46
+ const mockLog = {
47
+ info: vi.fn(),
48
+ warn: vi.fn(),
49
+ error: vi.fn(),
50
+ debug: vi.fn(),
51
+ } as unknown as Logger;
52
+
53
+ const service = new TestService({ log: mockLog });
54
+ const result = await service.testMethod();
55
+
56
+ expect(result).toBe('result');
57
+ expect(mockLog.info).toHaveBeenCalledWith(
58
+ 'Operation started',
59
+ expect.objectContaining({ operation: 'test.operation' }),
60
+ );
61
+ expect(mockLog.info).toHaveBeenCalledWith(
62
+ 'Operation completed',
63
+ expect.objectContaining({ operation: 'test.operation' }),
64
+ );
65
+ });
66
+
67
+ it('should support advanced object syntax', async () => {
68
+ class TestService {
69
+ constructor(public deps: { log: Logger }) {}
70
+
71
+ @LoggedOperation({ operationName: 'test.operation' })
72
+ async testMethod() {
73
+ return 'result';
74
+ }
75
+ }
76
+
77
+ const mockLog = {
78
+ info: vi.fn(),
79
+ warn: vi.fn(),
80
+ error: vi.fn(),
81
+ debug: vi.fn(),
82
+ } as unknown as Logger;
83
+
84
+ const service = new TestService({ log: mockLog });
85
+ const result = await service.testMethod();
86
+
87
+ expect(result).toBe('result');
88
+ expect(mockLog.info).toHaveBeenCalled();
89
+ });
90
+
91
+ it('should record errors', async () => {
92
+ class TestService {
93
+ constructor(public deps: { log: Logger }) {}
94
+
95
+ @LoggedOperation('test.failing')
96
+ async failingMethod() {
97
+ throw new Error('Test error');
98
+ }
99
+ }
100
+
101
+ const mockLog = {
102
+ info: vi.fn(),
103
+ warn: vi.fn(),
104
+ error: vi.fn(),
105
+ debug: vi.fn(),
106
+ } as unknown as Logger;
107
+
108
+ const service = new TestService({ log: mockLog });
109
+
110
+ await expect(service.failingMethod()).rejects.toThrow('Test error');
111
+ expect(mockLog.error).toHaveBeenCalledWith(
112
+ 'Operation failed',
113
+ expect.any(Error),
114
+ expect.objectContaining({ operation: 'test.failing' }),
115
+ );
116
+ });
117
+ });