@elysia/opentelemetry 1.4.11

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.
@@ -0,0 +1,70 @@
1
+ import { Elysia } from 'elysia';
2
+ import { type ContextManager, type Context, type SpanOptions, type Span, type Attributes, TraceAPI, TracerProvider } from '@opentelemetry/api';
3
+ import { NodeSDK } from '@opentelemetry/sdk-node';
4
+ type OpenTeleMetryOptions = NonNullable<ConstructorParameters<typeof NodeSDK>[0]>;
5
+ /**
6
+ * Initialize OpenTelemetry SDK
7
+ *
8
+ * For best practice, you should be using preload OpenTelemetry SDK if possible
9
+ * however, this is a simple way to initialize OpenTelemetry SDK
10
+ */
11
+ export interface ElysiaOpenTelemetryOptions extends OpenTeleMetryOptions {
12
+ contextManager?: ContextManager;
13
+ /**
14
+ * Optional function to determine whether a given request should be traced.
15
+ *
16
+ * @param req - The incoming request object to evaluate.
17
+ * @returns A boolean indicating whether tracing should be enabled for this request.
18
+ */
19
+ checkIfShouldTrace?: (req: Request) => boolean;
20
+ }
21
+ export type ActiveSpanArgs<F extends (span: Span) => unknown = (span: Span) => unknown> = [name: string, fn: F] | [name: string, options: SpanOptions, fn: F] | [name: string, options: SpanOptions, context: Context, fn: F];
22
+ export declare const shouldStartNodeSDK: (provider: TracerProvider) => boolean;
23
+ export type Tracer = ReturnType<TraceAPI['getTracer']>;
24
+ export type StartSpan = Tracer['startSpan'];
25
+ export type StartActiveSpan = Tracer['startActiveSpan'];
26
+ export declare const contextKeySpan: unique symbol;
27
+ export declare const getTracer: () => ReturnType<TraceAPI["getTracer"]>;
28
+ export declare const startSpan: (name: string, options?: SpanOptions, context?: Context) => Span;
29
+ export declare const startActiveSpan: StartActiveSpan;
30
+ export declare const record: {
31
+ <F extends (span: Span) => unknown>(name: string, fn: F): ReturnType<F>;
32
+ <F extends (span: Span) => unknown>(name: string, options: SpanOptions, fn: F): ReturnType<F>;
33
+ <F extends (span: Span) => unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType<F>;
34
+ };
35
+ export declare const getCurrentSpan: () => Span | undefined;
36
+ /**
37
+ * Set attributes to the current span
38
+ *
39
+ * @returns boolean - whether the attributes are set or not
40
+ */
41
+ export declare const setAttributes: (attributes: Attributes) => boolean;
42
+ export declare const opentelemetry: ({ serviceName, instrumentations, contextManager, checkIfShouldTrace, ...options }?: ElysiaOpenTelemetryOptions) => Elysia<"", {
43
+ decorator: {};
44
+ store: {};
45
+ derive: {};
46
+ resolve: {};
47
+ }, {
48
+ typebox: {};
49
+ error: {};
50
+ }, {
51
+ schema: {};
52
+ standaloneSchema: {};
53
+ macro: {};
54
+ macroFn: {};
55
+ parser: {};
56
+ response: {};
57
+ }, {}, {
58
+ derive: {};
59
+ resolve: {};
60
+ schema: {};
61
+ standaloneSchema: {};
62
+ response: {};
63
+ }, {
64
+ derive: {};
65
+ resolve: {};
66
+ schema: {};
67
+ standaloneSchema: {};
68
+ response: {};
69
+ }>;
70
+ export {};
package/dist/index.mjs ADDED
@@ -0,0 +1,606 @@
1
+ // src/index.ts
2
+ import { Elysia, StatusMap } from "elysia";
3
+ import {
4
+ trace,
5
+ context as otelContext,
6
+ propagation,
7
+ SpanStatusCode,
8
+ SpanKind,
9
+ ProxyTracerProvider
10
+ } from "@opentelemetry/api";
11
+ import { NodeSDK } from "@opentelemetry/sdk-node";
12
+ var headerHasToJSON = typeof new Headers().toJSON === "function";
13
+ var parseNumericString = (message) => {
14
+ if (message.length < 16) {
15
+ if (message.length === 0) return null;
16
+ const length = Number(message);
17
+ if (Number.isNaN(length)) return null;
18
+ return length;
19
+ }
20
+ if (message.length === 16) {
21
+ const number = Number(message);
22
+ if (number.toString() !== message || message.trim().length === 0 || Number.isNaN(number))
23
+ return null;
24
+ return number;
25
+ }
26
+ return null;
27
+ };
28
+ var createActiveSpanHandler = (fn) => function(span) {
29
+ try {
30
+ const result = fn(span);
31
+ if (result instanceof Promise || typeof result?.then === "function")
32
+ return Promise.resolve(result).then(
33
+ (value) => {
34
+ span.end();
35
+ return value;
36
+ },
37
+ (rejectResult) => {
38
+ span.setStatus({
39
+ code: SpanStatusCode.ERROR,
40
+ message: rejectResult instanceof Error ? rejectResult.message : JSON.stringify(
41
+ rejectResult ?? "Unknown error"
42
+ )
43
+ });
44
+ span.recordException(rejectResult);
45
+ span.end();
46
+ throw rejectResult;
47
+ }
48
+ );
49
+ span.end();
50
+ return result;
51
+ } catch (error) {
52
+ const err = error;
53
+ span.setStatus({
54
+ code: SpanStatusCode.ERROR,
55
+ message: err?.message
56
+ });
57
+ span.recordException(err);
58
+ span.end();
59
+ throw error;
60
+ }
61
+ };
62
+ var createContext = (parent) => ({
63
+ getValue() {
64
+ return parent;
65
+ },
66
+ setValue() {
67
+ return otelContext.active();
68
+ },
69
+ deleteValue() {
70
+ return otelContext.active();
71
+ }
72
+ });
73
+ var shouldStartNodeSDK = (provider) => {
74
+ return provider instanceof ProxyTracerProvider && provider.getDelegateTracer("check") === void 0;
75
+ };
76
+ var contextKeySpan = Symbol.for("OpenTelemetry Context Key SPAN");
77
+ var getTracer = () => {
78
+ const tracer = trace.getTracer("Elysia");
79
+ return {
80
+ ...tracer,
81
+ startSpan(name, options, context) {
82
+ return tracer.startSpan(name, options, context);
83
+ },
84
+ startActiveSpan(...args) {
85
+ switch (args.length) {
86
+ case 2:
87
+ return tracer.startActiveSpan(
88
+ args[0],
89
+ createActiveSpanHandler(args[1])
90
+ );
91
+ case 3:
92
+ return tracer.startActiveSpan(
93
+ args[0],
94
+ args[1],
95
+ createActiveSpanHandler(args[2])
96
+ );
97
+ case 4:
98
+ return tracer.startActiveSpan(
99
+ args[0],
100
+ args[1],
101
+ args[2],
102
+ createActiveSpanHandler(args[3])
103
+ );
104
+ }
105
+ }
106
+ };
107
+ };
108
+ var startSpan = (name, options, context) => {
109
+ const tracer = getTracer();
110
+ return tracer.startSpan(name, options, context);
111
+ };
112
+ var startActiveSpan = (...args) => {
113
+ const tracer = getTracer();
114
+ switch (args.length) {
115
+ case 2:
116
+ return tracer.startActiveSpan(
117
+ args[0],
118
+ createActiveSpanHandler(args[1])
119
+ );
120
+ case 3:
121
+ return tracer.startActiveSpan(
122
+ args[0],
123
+ args[1],
124
+ createActiveSpanHandler(args[2])
125
+ );
126
+ case 4:
127
+ return tracer.startActiveSpan(
128
+ args[0],
129
+ args[1],
130
+ args[2],
131
+ createActiveSpanHandler(args[3])
132
+ );
133
+ }
134
+ };
135
+ var record = startActiveSpan;
136
+ var getCurrentSpan = () => trace.getActiveSpan();
137
+ var setAttributes = (attributes) => !!getCurrentSpan()?.setAttributes(attributes);
138
+ var opentelemetry = ({
139
+ serviceName = "Elysia",
140
+ instrumentations,
141
+ contextManager,
142
+ checkIfShouldTrace,
143
+ ...options
144
+ } = {}) => {
145
+ let tracer = trace.getTracer(serviceName);
146
+ if (shouldStartNodeSDK(trace.getTracerProvider())) {
147
+ const sdk = new NodeSDK({
148
+ ...options,
149
+ serviceName,
150
+ instrumentations
151
+ });
152
+ sdk.start();
153
+ tracer = trace.getTracer(serviceName);
154
+ } else {
155
+ }
156
+ if (!otelContext._getContextManager?.() && contextManager)
157
+ try {
158
+ contextManager.enable();
159
+ otelContext.setGlobalContextManager(contextManager);
160
+ } catch {
161
+ }
162
+ return new Elysia({
163
+ name: "@elysia/opentelemetry"
164
+ }).wrap((fn, request) => {
165
+ const shouldTrace = checkIfShouldTrace ? checkIfShouldTrace(request) : true;
166
+ if (!shouldTrace) return fn;
167
+ const headers = headerHasToJSON ? (
168
+ // @ts-ignore bun only
169
+ request.headers.toJSON()
170
+ ) : Object.fromEntries(request.headers.entries());
171
+ const ctx = propagation.extract(otelContext.active(), headers);
172
+ return tracer.startActiveSpan(
173
+ "Root",
174
+ { kind: SpanKind.SERVER },
175
+ ctx,
176
+ (rootSpan) => {
177
+ const spanContext = trace.setSpan(ctx, rootSpan);
178
+ return (...args) => {
179
+ return otelContext.with(spanContext, () => fn(...args));
180
+ };
181
+ }
182
+ );
183
+ }).trace(
184
+ { as: "global" },
185
+ ({
186
+ id,
187
+ onRequest,
188
+ onParse,
189
+ onTransform,
190
+ onBeforeHandle,
191
+ onHandle,
192
+ onAfterHandle,
193
+ onError,
194
+ onAfterResponse,
195
+ onMapResponse,
196
+ context,
197
+ context: {
198
+ path,
199
+ request: { method }
200
+ }
201
+ }) => {
202
+ const rootSpan = trace.getActiveSpan();
203
+ if (!rootSpan) return;
204
+ function setParent(span) {
205
+ if (span.ended) return;
206
+ if (rootSpan.ended) return void span.end();
207
+ const newContext = trace.setSpan(otelContext.active(), span);
208
+ const currentContext = (
209
+ // @ts-expect-error private property
210
+ otelContext.active()._currentContext
211
+ );
212
+ currentContext?.set(
213
+ contextKeySpan,
214
+ newContext.getValue(contextKeySpan)
215
+ );
216
+ }
217
+ function inspect(name) {
218
+ return function inspect2({
219
+ onEvent,
220
+ total,
221
+ onStop
222
+ }) {
223
+ if (total === 0 || // @ts-ignore
224
+ rootSpan.ended)
225
+ return;
226
+ tracer.startActiveSpan(
227
+ name,
228
+ {},
229
+ createContext(rootSpan),
230
+ (event) => {
231
+ if (
232
+ // @ts-ignore
233
+ rootSpan.ended
234
+ )
235
+ return;
236
+ onEvent(({ name: name2, onStop: onStop2 }) => {
237
+ const useChildSpan = total > 1;
238
+ let span;
239
+ if (useChildSpan) {
240
+ span = tracer.startSpan(
241
+ name2,
242
+ {},
243
+ createContext(event)
244
+ );
245
+ setParent(span);
246
+ } else {
247
+ setParent(event);
248
+ span = event;
249
+ }
250
+ onStop2(({ error }) => {
251
+ setParent(rootSpan);
252
+ if (span.ended || rootSpan.ended) return;
253
+ if (error) {
254
+ rootSpan.setStatus({
255
+ code: SpanStatusCode.ERROR,
256
+ message: error.message
257
+ });
258
+ span.setAttributes({
259
+ "error.type": error.constructor?.name ?? error.name,
260
+ "error.stack": error.stack
261
+ });
262
+ span.setStatus({
263
+ code: SpanStatusCode.ERROR,
264
+ message: error.message
265
+ });
266
+ } else {
267
+ rootSpan.setStatus({
268
+ code: SpanStatusCode.OK
269
+ });
270
+ span.setStatus({
271
+ code: SpanStatusCode.OK
272
+ });
273
+ }
274
+ if (useChildSpan) span.end();
275
+ });
276
+ });
277
+ onStop(() => {
278
+ setParent(rootSpan);
279
+ if (event.ended) return;
280
+ event.end();
281
+ });
282
+ }
283
+ );
284
+ };
285
+ }
286
+ const url = context.url;
287
+ const attributes = Object.assign(/* @__PURE__ */ Object.create(null), {
288
+ // ? Elysia Custom attribute
289
+ "http.request.id": id,
290
+ "http.request.method": method,
291
+ "url.path": path,
292
+ "url.full": url
293
+ });
294
+ if (context.qi && context.qi !== -1)
295
+ attributes["url.query"] = url.slice(
296
+ // @ts-ignore private property
297
+ context.qi + 1
298
+ );
299
+ const protocolSeparator = url.indexOf("://");
300
+ if (protocolSeparator > 0)
301
+ attributes["url.scheme"] = url.slice(0, protocolSeparator);
302
+ onRequest(inspect("Request"));
303
+ onParse(inspect("Parse"));
304
+ onTransform(inspect("Transform"));
305
+ onBeforeHandle(inspect("BeforeHandle"));
306
+ onHandle(({ onStop }) => {
307
+ const span = tracer.startSpan(
308
+ "Handle",
309
+ {},
310
+ createContext(rootSpan)
311
+ );
312
+ setParent(span);
313
+ onStop(({ error }) => {
314
+ setParent(rootSpan);
315
+ if (span.ended || rootSpan.ended) return;
316
+ if (error) {
317
+ rootSpan.setStatus({
318
+ code: SpanStatusCode.ERROR,
319
+ message: error.message
320
+ });
321
+ span.setStatus({
322
+ code: SpanStatusCode.ERROR,
323
+ message: error.message
324
+ });
325
+ span.recordException(error);
326
+ rootSpan.recordException(error);
327
+ } else {
328
+ rootSpan.setStatus({
329
+ code: SpanStatusCode.OK
330
+ });
331
+ span.setStatus({
332
+ code: SpanStatusCode.OK
333
+ });
334
+ }
335
+ span.end();
336
+ });
337
+ });
338
+ onAfterHandle(inspect("AfterHandle"));
339
+ onError((event) => {
340
+ inspect("Error")(event);
341
+ event.onStop(({ error }) => {
342
+ setParent(rootSpan);
343
+ if (rootSpan.ended) return;
344
+ {
345
+ let status = context.set.status;
346
+ if (typeof status === "string") {
347
+ status = StatusMap[status];
348
+ } else if (typeof status !== "number" && // @ts-ignore
349
+ typeof error?.status === "number")
350
+ status = error.status;
351
+ if (typeof status === "number") {
352
+ attributes["http.response.status_code"] = status;
353
+ if (status >= 500)
354
+ rootSpan.setStatus({
355
+ code: SpanStatusCode.ERROR
356
+ });
357
+ }
358
+ rootSpan.setAttributes(attributes);
359
+ }
360
+ if (
361
+ // @ts-ignore
362
+ !rootSpan.ended
363
+ )
364
+ rootSpan.end();
365
+ });
366
+ });
367
+ onMapResponse(inspect("MapResponse"));
368
+ onTransform(() => {
369
+ const { cookie, request, route, path: path2 } = context;
370
+ if (route)
371
+ rootSpan.updateName(
372
+ // @ts-ignore private property
373
+ `${method} ${route || path2}`
374
+ );
375
+ if (context.route) attributes["http.route"] = context.route;
376
+ {
377
+ let contentLength = request.headers.get("content-length");
378
+ if (contentLength) {
379
+ const number = parseNumericString(contentLength);
380
+ if (number)
381
+ attributes["http.request_content_length"] = number;
382
+ }
383
+ }
384
+ {
385
+ const userAgent = request.headers.get("User-Agent");
386
+ if (userAgent)
387
+ attributes["user_agent.original"] = userAgent;
388
+ }
389
+ const server = context.server;
390
+ if (server) {
391
+ attributes["server.port"] = server.port ?? 80;
392
+ attributes["server.address"] = server.url.hostname;
393
+ attributes["server.address"] = server.url.hostname;
394
+ }
395
+ let headers;
396
+ {
397
+ let hasHeaders;
398
+ let _headers;
399
+ if (context.headers) {
400
+ hasHeaders = true;
401
+ headers = context.headers;
402
+ _headers = Object.entries(context.headers);
403
+ } else if (hasHeaders = headerHasToJSON) {
404
+ headers = request.headers.toJSON();
405
+ _headers = Object.entries(headers);
406
+ } else {
407
+ headers = {};
408
+ _headers = request.headers.entries();
409
+ }
410
+ for (let [key, value] of _headers) {
411
+ key = key.toLowerCase();
412
+ if (hasHeaders) {
413
+ if (key === "user-agent") continue;
414
+ if (typeof value === "object")
415
+ attributes[`http.request.header.${key}`] = JSON.stringify(value);
416
+ else if (value !== void 0)
417
+ attributes[`http.request.header.${key}`] = value;
418
+ continue;
419
+ }
420
+ if (typeof value === "object")
421
+ headers[key] = attributes[`http.request.header.${key}`] = JSON.stringify(value);
422
+ else if (value !== void 0) {
423
+ if (key === "user-agent") {
424
+ headers[key] = value;
425
+ continue;
426
+ }
427
+ headers[key] = attributes[`http.request.header.${key}`] = value;
428
+ }
429
+ }
430
+ }
431
+ {
432
+ let headers2;
433
+ if (context.set.headers instanceof Headers) {
434
+ if (headerHasToJSON)
435
+ headers2 = Object.entries(
436
+ // @ts-ignore bun only
437
+ context.set.headers.toJSON()
438
+ );
439
+ else headers2 = context.set.headers.entries();
440
+ } else headers2 = Object.entries(context.set.headers);
441
+ for (let [key, value] of headers2) {
442
+ key = key.toLowerCase();
443
+ if (typeof value === "object")
444
+ attributes[`http.response.header.${key}`] = JSON.stringify(value);
445
+ else
446
+ attributes[`http.response.header.${key}`] = value;
447
+ }
448
+ }
449
+ if (context.ip)
450
+ attributes["client.address"] = context.ip;
451
+ else {
452
+ const ip = headers["true-client-ip"] ?? headers["cf-connection-ip"] ?? headers["x-forwarded-for"] ?? headers["x-real-ip"] ?? server?.requestIP(request);
453
+ if (ip)
454
+ attributes["client.address"] = typeof ip === "string" ? ip : ip.address ?? ip.toString();
455
+ }
456
+ if (cookie) {
457
+ const _cookie = {};
458
+ for (const [key, { value }] of Object.entries(cookie))
459
+ _cookie[key] = JSON.stringify(value);
460
+ attributes["http.request.cookie"] = JSON.stringify(_cookie);
461
+ }
462
+ rootSpan.setAttributes(attributes);
463
+ });
464
+ onParse(() => {
465
+ const body = context.body;
466
+ if (body !== void 0 && body !== null) {
467
+ const value = typeof body === "object" ? JSON.stringify(body) : body.toString();
468
+ attributes["http.request.body"] = value;
469
+ if (typeof body === "object") {
470
+ if (body instanceof Uint8Array)
471
+ attributes["http.request.body.size"] = body.length;
472
+ else if (body instanceof ArrayBuffer)
473
+ attributes["http.request.body.size"] = body.byteLength;
474
+ else if (body instanceof Blob)
475
+ attributes["http.request.body.size"] = body.size;
476
+ attributes["http.request.body.size"] = value.length;
477
+ } else {
478
+ attributes["http.request.body.size"] = value.length;
479
+ }
480
+ }
481
+ });
482
+ onMapResponse(() => {
483
+ const body = context.body;
484
+ if (body !== void 0 && body !== null) {
485
+ const value = typeof body === "object" ? JSON.stringify(body) : body.toString();
486
+ attributes["http.request.body"] = value;
487
+ if (typeof body === "object") {
488
+ if (body instanceof Uint8Array)
489
+ attributes["http.request.body.size"] = body.length;
490
+ else if (body instanceof ArrayBuffer)
491
+ attributes["http.request.body.size"] = body.byteLength;
492
+ else if (body instanceof Blob)
493
+ attributes["http.request.body.size"] = body.size;
494
+ attributes["http.request.body.size"] = value.length;
495
+ } else {
496
+ attributes["http.request.body.size"] = value.length;
497
+ }
498
+ }
499
+ {
500
+ let status = context.set.status ?? 200;
501
+ if (typeof status === "string")
502
+ status = StatusMap[status] ?? 200;
503
+ attributes["http.response.status_code"] = status;
504
+ }
505
+ const response = context.responseValue;
506
+ if (response !== void 0)
507
+ switch (typeof response) {
508
+ case "object":
509
+ if (response instanceof Response) {
510
+ } else if (response instanceof Uint8Array)
511
+ attributes["http.response.body.size"] = response.length;
512
+ else if (response instanceof ArrayBuffer)
513
+ attributes["http.response.body.size"] = response.byteLength;
514
+ else if (response instanceof Blob)
515
+ attributes["http.response.body.size"] = response.size;
516
+ else {
517
+ const value = JSON.stringify(response);
518
+ attributes["http.response.body"] = value;
519
+ attributes["http.response.body.size"] = value.length;
520
+ }
521
+ break;
522
+ default:
523
+ if (response === void 0 || response === null)
524
+ attributes["http.response.body.size"] = 0;
525
+ else {
526
+ const value = response.toString();
527
+ attributes["http.response.body"] = value;
528
+ attributes["http.response.body.size"] = value.length;
529
+ }
530
+ }
531
+ if (!rootSpan.ended) {
532
+ const statusCode = attributes["http.response.status_code"];
533
+ if (typeof statusCode === "number" && statusCode >= 500) {
534
+ rootSpan.setStatus({
535
+ code: SpanStatusCode.ERROR
536
+ });
537
+ }
538
+ rootSpan.setAttributes(attributes);
539
+ }
540
+ });
541
+ onAfterResponse((event) => {
542
+ inspect("AfterResponse")(event);
543
+ {
544
+ let status = context.set.status ?? 200;
545
+ if (typeof status === "string")
546
+ status = StatusMap[status] ?? 200;
547
+ attributes["http.response.status_code"] = status;
548
+ }
549
+ const body = context.body;
550
+ if (body !== void 0 && body !== null) {
551
+ const value = typeof body === "object" ? JSON.stringify(body) : body.toString();
552
+ attributes["http.request.body"] = value;
553
+ if (typeof body === "object") {
554
+ if (body instanceof Uint8Array)
555
+ attributes["http.request.body.size"] = body.length;
556
+ else if (body instanceof ArrayBuffer)
557
+ attributes["http.request.body.size"] = body.byteLength;
558
+ else if (body instanceof Blob)
559
+ attributes["http.request.body.size"] = body.size;
560
+ attributes["http.request.body.size"] = value.length;
561
+ } else {
562
+ attributes["http.request.body.size"] = value.length;
563
+ }
564
+ }
565
+ if (!rootSpan.ended) {
566
+ const statusCode = attributes["http.response.status_code"];
567
+ if (typeof statusCode === "number" && statusCode >= 500)
568
+ rootSpan.setStatus({
569
+ code: SpanStatusCode.ERROR
570
+ });
571
+ rootSpan.setAttributes(attributes);
572
+ }
573
+ event.onStop(() => {
574
+ setParent(rootSpan);
575
+ if (rootSpan.ended) return;
576
+ if (
577
+ // @ts-ignore
578
+ !rootSpan.ended
579
+ )
580
+ rootSpan.end();
581
+ });
582
+ });
583
+ context.request.signal.addEventListener("abort", () => {
584
+ const active = trace.getActiveSpan();
585
+ if (active && !active.ended) active.end();
586
+ if (rootSpan.ended) return;
587
+ rootSpan.setStatus({
588
+ code: SpanStatusCode.ERROR,
589
+ message: "Request aborted"
590
+ });
591
+ rootSpan.end();
592
+ });
593
+ }
594
+ );
595
+ };
596
+ export {
597
+ contextKeySpan,
598
+ getCurrentSpan,
599
+ getTracer,
600
+ opentelemetry,
601
+ record,
602
+ setAttributes,
603
+ shouldStartNodeSDK,
604
+ startActiveSpan,
605
+ startSpan
606
+ };