@moostjs/otel 0.4.7 → 0.4.9

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.
package/dist/index.mjs CHANGED
@@ -1,9 +1,10 @@
1
- import { trace, context, SpanStatusCode } from '@opentelemetry/api';
2
- import { useAsyncEventContext as useAsyncEventContext$1, eventContextHooks as eventContextHooks$1, useControllerContext, getConstructor as getConstructor$2 } from 'moost';
1
+ import { trace, context, metrics } from '@opentelemetry/api';
2
+ import { useAsyncEventContext as useAsyncEventContext$1, ContextInjector, useControllerContext, getConstructor as getConstructor$2, replaceContextInjector } from 'moost';
3
3
  import { randomUUID } from 'crypto';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  import { BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
6
6
 
7
+ const spanStack = [];
7
8
  function useOtelContext() {
8
9
  const store = useAsyncEventContext$1().store('otel');
9
10
  const getSpan = () => store.get('span');
@@ -23,23 +24,42 @@ function useOtelContext() {
23
24
  }
24
25
  return {};
25
26
  };
27
+ const pushSpan = (span) => {
28
+ const activeSpan = trace.getActiveSpan();
29
+ if (activeSpan) {
30
+ const origEnd = activeSpan.end;
31
+ Object.assign(activeSpan, {
32
+ end: (t) => {
33
+ popSpan();
34
+ const i = spanStack.indexOf(activeSpan);
35
+ if (i >= 0) {
36
+ spanStack.splice(i, 1);
37
+ }
38
+ origEnd.apply(span, [t]);
39
+ },
40
+ });
41
+ spanStack.push(activeSpan);
42
+ }
43
+ trace.setSpan(context.active(), span);
44
+ };
45
+ const popSpan = () => {
46
+ const span = spanStack.pop();
47
+ if (span) {
48
+ trace.setSpan(context.active(), span);
49
+ }
50
+ };
26
51
  return {
27
52
  trace,
28
53
  withChildSpan: (name, cb, opts) => {
29
- const parentSpan = getSpan();
30
- if (parentSpan) {
31
- const tracer = trace.getTracer('moost-tracer');
32
- const span = tracer.startSpan(name, opts);
33
- return () => context.with(trace.setSpan(context.active(), span), () => cb());
34
- }
35
- else {
36
- return cb();
37
- }
54
+ const tracer = trace.getTracer('moost-tracer');
55
+ const span = tracer.startSpan(name, opts);
56
+ return () => context.with(trace.setSpan(context.active(), span), cb);
38
57
  },
39
58
  getSpan,
40
59
  getSpanContext,
41
60
  getPropagationHeaders,
42
61
  registerSpan: (span) => store.set('span', span),
62
+ pushSpan,
43
63
  };
44
64
  }
45
65
  function useTrace() {
@@ -56,60 +76,472 @@ function useOtelPropagation() {
56
76
  };
57
77
  }
58
78
 
59
- function enableOtelForMoost() {
60
- eventContextHooks$1.onStartEvent((eventType) => {
79
+ const meter = metrics.getMeter('moost-meter');
80
+ const moostMetrics = {
81
+ httpRequestCount: meter.createCounter('http.server.requests', {
82
+ description: 'The number of HTTP requests received',
83
+ }),
84
+ httpResponseCount: meter.createCounter('http.server.responses', {
85
+ description: 'The number of HTTP responses sent',
86
+ }),
87
+ httpActiveRequests: meter.createUpDownCounter('http.server.active_requests', {
88
+ description: 'The number of active HTTP requests',
89
+ }),
90
+ httpRequestSize: meter.createHistogram('http.server.request.size', {
91
+ description: 'The size of HTTP request bodies',
92
+ }),
93
+ httpResponseSize: meter.createHistogram('http.server.response.size', {
94
+ description: 'The size of HTTP response bodies',
95
+ }),
96
+ httpErrorCount: meter.createCounter('http.server.errors', {
97
+ description: 'The number of HTTP requests that resulted in an error',
98
+ }),
99
+ moostEventCount: meter.createCounter('moost.events.count', {
100
+ description: 'The number of HTTP requests received',
101
+ }),
102
+ moostActiveEvents: meter.createUpDownCounter('moost.events.active', {
103
+ description: 'The number of active HTTP requests',
104
+ }),
105
+ moostErrorCount: meter.createCounter('moost.events.errors', {
106
+ description: 'The number of HTTP requests that resulted in an error',
107
+ }),
108
+ };
109
+
110
+ const tracer = trace.getTracer('moost-tracer');
111
+ class SpanInjector extends ContextInjector {
112
+ with(name, attributes, cb) {
113
+ const fn = typeof attributes === 'function' ? attributes : cb;
114
+ const attrs = typeof attributes === 'object' ? attributes : undefined;
115
+ if (name === 'Event:start' && attrs?.eventType) {
116
+ return this.startEvent(attrs.eventType, fn);
117
+ }
118
+ else if (name !== 'Event:start') {
119
+ if (this.getIgnoreSpan()) {
120
+ return fn();
121
+ }
122
+ else {
123
+ const span = tracer.startSpan(name, {
124
+ attributes: attrs,
125
+ });
126
+ return this.withSpan(span, fn, {
127
+ rootSpan: false,
128
+ endSpan: true,
129
+ });
130
+ }
131
+ }
132
+ return fn();
133
+ }
134
+ patchRsponse() {
135
+ const res = this.getResponse();
136
+ if (res) {
137
+ const originalWriteHead = res.writeHead;
138
+ Object.assign(res, {
139
+ writeHead: (arg0, arg1, arg2) => {
140
+ res._statusCode = arg0;
141
+ const headers = typeof arg2 === 'object' ? arg2 : typeof arg1 === 'object' ? arg1 : undefined;
142
+ res._contentLength = headers?.['content-length'] ? Number(headers['content-length']) : 0;
143
+ return originalWriteHead.apply(res, [arg0, arg1, arg2]);
144
+ },
145
+ });
146
+ }
147
+ }
148
+ startEvent(eventType, cb) {
61
149
  if (eventType === 'init') {
62
- return;
150
+ return cb();
63
151
  }
64
152
  const { registerSpan } = useOtelContext();
65
- let span;
153
+ let span = trace.getActiveSpan();
66
154
  if (eventType === 'HTTP') {
67
- span = trace.getSpan(context.active());
155
+ this.patchRsponse();
68
156
  }
69
157
  else {
70
- const tracer = trace.getTracer('moost-tracer');
71
158
  span = tracer.startSpan(`${eventType} Event`);
72
159
  }
73
160
  if (span) {
74
161
  registerSpan(span);
162
+ return this.withSpan(span, cb, {
163
+ rootSpan: true,
164
+ endSpan: eventType !== 'HTTP',
165
+ });
75
166
  }
76
- });
77
- eventContextHooks$1.onEndEvent((eventType, abortReason) => {
78
- if (eventType === 'init') {
79
- return;
167
+ return cb();
168
+ }
169
+ getEventType() {
170
+ return useAsyncEventContext$1().getCtx().event.type;
171
+ }
172
+ getIgnoreSpan() {
173
+ const { getMethodMeta, getControllerMeta } = useControllerContext();
174
+ const cMeta = getControllerMeta();
175
+ const mMeta = getMethodMeta();
176
+ return cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan;
177
+ }
178
+ getControllerHandlerMeta() {
179
+ const { getMethod, getMethodMeta, getController, getControllerMeta, getRoute } = useControllerContext();
180
+ const methodName = getMethod();
181
+ const controller = getController();
182
+ const cMeta = controller ? getControllerMeta() : undefined;
183
+ const mMeta = controller ? getMethodMeta() : undefined;
184
+ return {
185
+ ignoreMeter: cMeta?.otelIgnoreMeter || mMeta?.otelIgnoreMeter,
186
+ ignoreSpan: cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
187
+ attrs: {
188
+ 'moost.controller': controller ? getConstructor$2(controller).name : undefined,
189
+ 'moost.handler': methodName,
190
+ 'moost.handler_description': mMeta?.description,
191
+ 'moost.handler_label': mMeta?.label,
192
+ 'moost.handler_id': mMeta?.id,
193
+ 'moost.ignore': cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
194
+ 'moost.route': getRoute(),
195
+ 'moost.event_type': this.getEventType(),
196
+ },
197
+ };
198
+ }
199
+ hook(name, route) {
200
+ useAsyncEventContext$1().store('otel').set('route', route);
201
+ const chm = this.getControllerHandlerMeta();
202
+ if (!chm.ignoreMeter) {
203
+ this.startEventMetrics(chm.attrs, route);
80
204
  }
81
205
  const { getSpan } = useOtelContext();
82
206
  const span = getSpan();
83
207
  if (span) {
84
- const { getMethod, getMethodMeta, getController, getControllerMeta } = useControllerContext();
85
- const methodName = getMethod();
86
- const methodMeta = getMethodMeta();
87
- const cMeta = getControllerMeta();
88
- span.setAttributes({
89
- 'custom.event_type': eventType,
90
- 'custom.event_description': methodMeta?.description || methodMeta?.label || methodName,
91
- 'moost.controller': getConstructor$2(getController()).name,
92
- 'moost.handler': methodName,
93
- 'moost.ignore': cMeta?.otelIgnoreSpan || methodMeta?.otelIgnoreSpan,
94
- });
95
- if (abortReason) {
96
- span.recordException(new Error(abortReason));
97
- span.setStatus({ code: SpanStatusCode.ERROR, message: abortReason });
98
- }
99
- if (eventType === 'HTTP') {
100
- const req = useAsyncEventContext$1()
101
- .store('event')
102
- .get('req');
103
- span.updateName(`${req?.method || ''} ${methodMeta?.id || methodMeta?.label || methodName}`);
208
+ span.setAttributes(chm.attrs);
209
+ if (chm.attrs['moost.event_type'] === 'HTTP') {
210
+ span.updateName(`${this.getRequest()?.method || ''} ${route || '<unresolved>'}`);
104
211
  }
105
212
  else {
106
- span.updateName(`${methodMeta?.label || methodName}`);
213
+ span.updateName(`${chm.attrs['moost.event_type']} ${route || '<unresolved>'}`);
214
+ }
215
+ }
216
+ }
217
+ withSpan(span, cb, opts) {
218
+ let result;
219
+ let exception;
220
+ const endSpan = (error) => {
221
+ if (error) {
222
+ span.recordException(error);
223
+ }
224
+ if (opts.rootSpan) {
225
+ const chm = this.getControllerHandlerMeta();
226
+ if (!chm.ignoreMeter) {
227
+ this.endEventMetrics(chm.attrs, error);
228
+ }
229
+ }
230
+ if (opts.endSpan) {
107
231
  span.end();
108
232
  }
233
+ };
234
+ context.with(trace.setSpan(context.active(), span), () => {
235
+ try {
236
+ result = cb();
237
+ }
238
+ catch (error) {
239
+ exception = error;
240
+ endSpan(exception);
241
+ }
242
+ });
243
+ const ret = result;
244
+ if (!exception) {
245
+ if (ret && ret instanceof Promise) {
246
+ ret
247
+ .then(r => {
248
+ endSpan();
249
+ return r;
250
+ })
251
+ .catch(error => {
252
+ endSpan(error);
253
+ });
254
+ }
255
+ else {
256
+ endSpan();
257
+ }
109
258
  }
110
- });
259
+ return ret;
260
+ }
261
+ startEventMetrics(a, route) {
262
+ if (a['moost.event_type'] === 'HTTP') {
263
+ const req = this.getRequest();
264
+ const attrs = {
265
+ ...a,
266
+ route,
267
+ url: req?.url,
268
+ };
269
+ moostMetrics.httpRequestCount.add(1, attrs);
270
+ moostMetrics.httpActiveRequests.add(1, attrs);
271
+ }
272
+ const attrs = {
273
+ ...a,
274
+ route,
275
+ };
276
+ moostMetrics.moostEventCount.add(1, attrs);
277
+ moostMetrics.moostActiveEvents.add(1, attrs);
278
+ }
279
+ endEventMetrics(a, error) {
280
+ const route = useAsyncEventContext$1().store('otel').get('route');
281
+ if (a['moost.event_type'] === 'HTTP') {
282
+ const req = this.getRequest();
283
+ const res = this.getResponse();
284
+ const attrs = {
285
+ ...a,
286
+ route,
287
+ url: req?.url,
288
+ };
289
+ moostMetrics.httpActiveRequests.add(-1, attrs);
290
+ if (error) {
291
+ moostMetrics.httpErrorCount.add(1, attrs);
292
+ }
293
+ moostMetrics.httpRequestSize.record(req?.socket.bytesRead || 0, attrs);
294
+ moostMetrics.httpResponseSize.record(res?._contentLength || 0, attrs);
295
+ moostMetrics.httpResponseCount.add(1, { ...attrs, status: res?._statusCode });
296
+ }
297
+ const attrs = {
298
+ ...a,
299
+ route,
300
+ };
301
+ moostMetrics.moostActiveEvents.add(-1, attrs);
302
+ if (error) {
303
+ moostMetrics.moostErrorCount.add(1, attrs);
304
+ }
305
+ }
306
+ getRequest() {
307
+ return useAsyncEventContext$1().store('event').get('req');
308
+ }
309
+ getResponse() {
310
+ return useAsyncEventContext$1()
311
+ .store('event')
312
+ .get('res');
313
+ }
314
+ }
315
+
316
+ function enableOtelForMoost() {
317
+ replaceContextInjector(new SpanInjector());
318
+ }
319
+
320
+ function getConstructor$1(instance) {
321
+ return isConstructor(instance) ?
322
+ instance : instance.constructor ?
323
+ instance.constructor : Object.getPrototypeOf(instance).constructor;
324
+ }
325
+ function isConstructor(v) {
326
+ return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
111
327
  }
112
328
 
329
+ const classMetadata = new WeakMap();
330
+ const paramMetadata = new WeakMap();
331
+ const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
332
+ function getMetaObject(target, prop) {
333
+ const isParam = typeof prop !== 'undefined';
334
+ const metadata = isParam ? paramMetadata : classMetadata;
335
+ const targetKey = getConstructor$1(target);
336
+ let meta = metadata.get(targetKey);
337
+ if (!meta) {
338
+ meta = {};
339
+ metadata.set(targetKey, meta);
340
+ }
341
+ if (isParam) {
342
+ meta = (meta[prop] =
343
+ meta[prop] || {});
344
+ }
345
+ return meta;
346
+ }
347
+ const _reflect = {
348
+ getOwnMetadata(key, target, prop) {
349
+ return getMetaObject(target, prop)[key];
350
+ },
351
+ defineMetadata(key, data, target, prop) {
352
+ const meta = getMetaObject(target, prop);
353
+ meta[key] = data;
354
+ },
355
+ metadata(key, data) {
356
+ return ((target, propKey) => {
357
+ Reflect$1.defineMetadata(key, data, target, propKey);
358
+ });
359
+ },
360
+ };
361
+ if (!root.Reflect) {
362
+ root.Reflect = _reflect;
363
+ }
364
+ else {
365
+ const funcs = [
366
+ 'getOwnMetadata',
367
+ 'defineMetadata',
368
+ 'metadata',
369
+ ];
370
+ const target = root.Reflect;
371
+ for (const func of funcs) {
372
+ if (typeof target[func] !== 'function') {
373
+ Object.defineProperty(target, func, { configurable: true, writable: true, value: _reflect[func] });
374
+ }
375
+ }
376
+ }
377
+ const Reflect$1 = _reflect;
378
+
379
+ const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
380
+ class Mate {
381
+ constructor(workspace, options = {}) {
382
+ this.workspace = workspace;
383
+ this.options = options;
384
+ this.logger = options.logger || console;
385
+ }
386
+ set(args, key, value, isArray) {
387
+ var _a;
388
+ let level = 'CLASS';
389
+ const newArgs = args.level === 'CLASS' ? { target: args.target }
390
+ : args.level === 'PROP' ? { target: args.target, propKey: args.propKey }
391
+ : args;
392
+ let meta = (Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
393
+ if (newArgs.propKey && this.options.readReturnType && !meta.returnType && args.descriptor) {
394
+ meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
395
+ }
396
+ if (newArgs.propKey && this.options.readType && !meta.type) {
397
+ meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
398
+ }
399
+ const { index } = newArgs;
400
+ const cb = typeof key === 'function' ? key : undefined;
401
+ let data = meta;
402
+ if (!data.params) {
403
+ data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
404
+ }
405
+ if (typeof index === 'number') {
406
+ level = 'PARAM';
407
+ data.params = data.params || [];
408
+ data.params[index] = data.params[index] || {
409
+ type: undefined,
410
+ };
411
+ if (cb) {
412
+ data.params[index] = cb(data.params[index], level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
413
+ }
414
+ else {
415
+ data = data.params[index];
416
+ }
417
+ }
418
+ else if (!index && !args.descriptor && args.propKey && this.options.collectPropKeys && args.level !== 'CLASS') {
419
+ this.set({ ...args, level: 'CLASS' }, (meta) => {
420
+ if (!meta.properties) {
421
+ meta.properties = [args.propKey];
422
+ }
423
+ else if (!meta.properties.includes(args.propKey)) {
424
+ meta.properties.push(args.propKey);
425
+ }
426
+ return meta;
427
+ });
428
+ }
429
+ level = typeof index === 'number' ? 'PARAM' : newArgs.propKey && newArgs.descriptor ? 'METHOD' : newArgs.propKey ? 'PROP' : 'CLASS';
430
+ if (typeof key !== 'function') {
431
+ if (isArray) {
432
+ const newArray = (data[key] || []);
433
+ if (!Array.isArray(newArray)) {
434
+ this.logger.error('Mate.add (isArray=true) called for non-array metadata');
435
+ }
436
+ newArray.unshift(value);
437
+ data[key] = newArray;
438
+ }
439
+ else {
440
+ data[key] = value;
441
+ }
442
+ }
443
+ else if (cb && typeof index !== 'number') {
444
+ meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
445
+ }
446
+ Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
447
+ }
448
+ read(target, propKey) {
449
+ var _a;
450
+ const isConstr = isConstructor(target);
451
+ const constructor = isConstr ? target : getConstructor$1(target);
452
+ const proto = constructor.prototype;
453
+ let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
454
+ if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
455
+ const parent = Object.getPrototypeOf(constructor);
456
+ if (typeof parent === 'function' &&
457
+ parent !== fnProto &&
458
+ parent !== constructor) {
459
+ ownMeta.params = (_a = this.read(parent)) === null || _a === void 0 ? void 0 : _a.params;
460
+ }
461
+ }
462
+ if (this.options.inherit) {
463
+ const inheritFn = typeof this.options.inherit === 'function'
464
+ ? this.options.inherit
465
+ : undefined;
466
+ let shouldInherit = this.options.inherit;
467
+ if (inheritFn) {
468
+ if (typeof propKey === 'string') {
469
+ const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
470
+ shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
471
+ }
472
+ else {
473
+ shouldInherit = inheritFn(ownMeta, ownMeta, 'CLASS');
474
+ }
475
+ }
476
+ if (shouldInherit) {
477
+ const parent = Object.getPrototypeOf(constructor);
478
+ if (typeof parent === 'function' &&
479
+ parent !== fnProto &&
480
+ parent !== constructor) {
481
+ const inheritedMeta = (this.read(parent, propKey) ||
482
+ {});
483
+ const ownParams = ownMeta === null || ownMeta === void 0 ? void 0 : ownMeta.params;
484
+ ownMeta = { ...inheritedMeta, ...ownMeta };
485
+ if (typeof propKey === 'string' &&
486
+ ownParams &&
487
+ (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
488
+ for (let i = 0; i < ownParams.length; i++) {
489
+ if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !==
490
+ 'undefined') {
491
+ const ownParam = ownParams[i];
492
+ if (ownMeta.params &&
493
+ inheritFn &&
494
+ inheritFn(ownMeta, ownParam, 'PARAM', typeof propKey === 'string'
495
+ ? propKey
496
+ : undefined)) {
497
+ ownMeta.params[i] = {
498
+ ...inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i],
499
+ ...ownParams[i],
500
+ };
501
+ }
502
+ }
503
+ }
504
+ }
505
+ }
506
+ }
507
+ }
508
+ return ownMeta;
509
+ }
510
+ apply(...decorators) {
511
+ return ((target, propKey, descriptor) => {
512
+ for (const d of decorators) {
513
+ d(target, propKey, descriptor);
514
+ }
515
+ });
516
+ }
517
+ decorate(key, value, isArray, level) {
518
+ return ((target, propKey, descriptor) => {
519
+ const args = {
520
+ target,
521
+ propKey,
522
+ descriptor: typeof descriptor === 'number' ? undefined : descriptor,
523
+ index: typeof descriptor === 'number' ? descriptor : undefined,
524
+ level,
525
+ };
526
+ this.set(args, key, value, isArray);
527
+ });
528
+ }
529
+ decorateConditional(ccb) {
530
+ return ((target, propKey, descriptor) => {
531
+ const hasIndex = typeof descriptor === 'number';
532
+ const decoratorLevel = hasIndex ? 'PARAM' : propKey && descriptor ? 'METHOD' : propKey ? 'PROP' : 'CLASS';
533
+ const d = ccb(decoratorLevel);
534
+ if (d) {
535
+ d(target, propKey, descriptor);
536
+ }
537
+ });
538
+ }
539
+ decorateClass(key, value, isArray) {
540
+ return this.decorate(key, value, isArray, 'CLASS');
541
+ }
542
+ }
543
+ const fnProto = Object.getPrototypeOf(Function);
544
+
113
545
  const defaultLevels = [
114
546
  'fatal',
115
547
  'error',
@@ -122,54 +554,6 @@ const defaultLevels = [
122
554
  const defaultMappedLevels = new Map();
123
555
  defaultLevels.forEach((type, level) => defaultMappedLevels.set(type, level));
124
556
 
125
- class Hookable {
126
- constructor() {
127
- this.hooks = {};
128
- }
129
- hook(name, cb) {
130
- if (!this.hooks[name]) {
131
- this.hooks[name] = [];
132
- }
133
- this.hooks[name].push(cb);
134
- return () => {
135
- this.unhook(name, cb);
136
- };
137
- }
138
- callHook(name, ...args) {
139
- if (this.hooks[name]) {
140
- for (const cb of this.hooks[name]) {
141
- try {
142
- cb(...args);
143
- }
144
- catch (error) {
145
- console.error(`Error in hook ${name}:`, error);
146
- }
147
- }
148
- }
149
- }
150
- unhook(name, cb) {
151
- if (this.hooks[name]) {
152
- this.hooks[name] = this.hooks[name].filter(hookCb => hookCb !== cb);
153
- }
154
- }
155
- }
156
-
157
- class EventContextHooks extends Hookable {
158
- fireStartEvent(eventType) {
159
- this.callHook('start-event', eventType);
160
- }
161
- fireEndEvent(eventType, abortReason) {
162
- this.callHook('end-event', eventType, abortReason);
163
- }
164
- onStartEvent(cb) {
165
- return this.hook('start-event', cb);
166
- }
167
- onEndEvent(cb) {
168
- return this.hook('end-event', cb);
169
- }
170
- }
171
- const eventContextHooks = new EventContextHooks();
172
-
173
557
  function attachHook(target, opts, name) {
174
558
  Object.defineProperty(target, name || 'value', {
175
559
  get: opts.get,
@@ -275,12 +659,6 @@ function _getCtxHelpers(cc) {
275
659
  const hasParentCtx = () => !!cc.parentCtx;
276
660
  return {
277
661
  getCtx,
278
- endEvent: (abortReason) => {
279
- if (cc && !cc._ended) {
280
- cc._ended = true;
281
- eventContextHooks.fireEndEvent(cc.event.type, abortReason);
282
- }
283
- },
284
662
  store,
285
663
  getStore: get,
286
664
  setStore: set,
@@ -304,7 +682,7 @@ function useEventId() {
304
682
  return { getId };
305
683
  }
306
684
 
307
- function getConstructor$1(instance) {
685
+ function getConstructor(instance) {
308
686
  return Object.getPrototypeOf(instance).constructor;
309
687
  }
310
688
 
@@ -592,8 +970,8 @@ class Infact {
592
970
  case 'string':
593
971
  return `"${''}...${''}"`;
594
972
  case 'object':
595
- if (getConstructor$1(p))
596
- return getConstructor$1(p).name;
973
+ if (getConstructor(p))
974
+ return getConstructor(p).name;
597
975
  return '{}';
598
976
  default:
599
977
  return '*';
@@ -649,231 +1027,6 @@ async function runPipes(pipes, initialValue, metas, level) {
649
1027
  return v;
650
1028
  }
651
1029
 
652
- function getConstructor(instance) {
653
- return isConstructor(instance) ?
654
- instance : instance.constructor ?
655
- instance.constructor : Object.getPrototypeOf(instance).constructor;
656
- }
657
- function isConstructor(v) {
658
- return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
659
- }
660
-
661
- const classMetadata = new WeakMap();
662
- const paramMetadata = new WeakMap();
663
- const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
664
- function getMetaObject(target, prop) {
665
- const isParam = typeof prop !== 'undefined';
666
- const metadata = isParam ? paramMetadata : classMetadata;
667
- const targetKey = getConstructor(target);
668
- let meta = metadata.get(targetKey);
669
- if (!meta) {
670
- meta = {};
671
- metadata.set(targetKey, meta);
672
- }
673
- if (isParam) {
674
- meta = (meta[prop] =
675
- meta[prop] || {});
676
- }
677
- return meta;
678
- }
679
- const _reflect = {
680
- getOwnMetadata(key, target, prop) {
681
- return getMetaObject(target, prop)[key];
682
- },
683
- defineMetadata(key, data, target, prop) {
684
- const meta = getMetaObject(target, prop);
685
- meta[key] = data;
686
- },
687
- metadata(key, data) {
688
- return ((target, propKey) => {
689
- Reflect$1.defineMetadata(key, data, target, propKey);
690
- });
691
- },
692
- };
693
- if (!root.Reflect) {
694
- root.Reflect = _reflect;
695
- }
696
- else {
697
- const funcs = [
698
- 'getOwnMetadata',
699
- 'defineMetadata',
700
- 'metadata',
701
- ];
702
- const target = root.Reflect;
703
- for (const func of funcs) {
704
- if (typeof target[func] !== 'function') {
705
- Object.defineProperty(target, func, { configurable: true, writable: true, value: _reflect[func] });
706
- }
707
- }
708
- }
709
- const Reflect$1 = _reflect;
710
-
711
- const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
712
- class Mate {
713
- constructor(workspace, options = {}) {
714
- this.workspace = workspace;
715
- this.options = options;
716
- this.logger = options.logger || console;
717
- }
718
- set(args, key, value, isArray) {
719
- var _a;
720
- let level = 'CLASS';
721
- const newArgs = args.level === 'CLASS' ? { target: args.target }
722
- : args.level === 'PROP' ? { target: args.target, propKey: args.propKey }
723
- : args;
724
- let meta = (Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
725
- if (newArgs.propKey && this.options.readReturnType && !meta.returnType && args.descriptor) {
726
- meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
727
- }
728
- if (newArgs.propKey && this.options.readType && !meta.type) {
729
- meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
730
- }
731
- const { index } = newArgs;
732
- const cb = typeof key === 'function' ? key : undefined;
733
- let data = meta;
734
- if (!data.params) {
735
- data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
736
- }
737
- if (typeof index === 'number') {
738
- level = 'PARAM';
739
- data.params = data.params || [];
740
- data.params[index] = data.params[index] || {
741
- type: undefined,
742
- };
743
- if (cb) {
744
- data.params[index] = cb(data.params[index], level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
745
- }
746
- else {
747
- data = data.params[index];
748
- }
749
- }
750
- else if (!index && !args.descriptor && args.propKey && this.options.collectPropKeys && args.level !== 'CLASS') {
751
- this.set({ ...args, level: 'CLASS' }, (meta) => {
752
- if (!meta.properties) {
753
- meta.properties = [args.propKey];
754
- }
755
- else if (!meta.properties.includes(args.propKey)) {
756
- meta.properties.push(args.propKey);
757
- }
758
- return meta;
759
- });
760
- }
761
- level = typeof index === 'number' ? 'PARAM' : newArgs.propKey && newArgs.descriptor ? 'METHOD' : newArgs.propKey ? 'PROP' : 'CLASS';
762
- if (typeof key !== 'function') {
763
- if (isArray) {
764
- const newArray = (data[key] || []);
765
- if (!Array.isArray(newArray)) {
766
- this.logger.error('Mate.add (isArray=true) called for non-array metadata');
767
- }
768
- newArray.unshift(value);
769
- data[key] = newArray;
770
- }
771
- else {
772
- data[key] = value;
773
- }
774
- }
775
- else if (cb && typeof index !== 'number') {
776
- meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
777
- }
778
- Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
779
- }
780
- read(target, propKey) {
781
- var _a;
782
- const isConstr = isConstructor(target);
783
- const constructor = isConstr ? target : getConstructor(target);
784
- const proto = constructor.prototype;
785
- let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
786
- if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
787
- const parent = Object.getPrototypeOf(constructor);
788
- if (typeof parent === 'function' &&
789
- parent !== fnProto &&
790
- parent !== constructor) {
791
- ownMeta.params = (_a = this.read(parent)) === null || _a === void 0 ? void 0 : _a.params;
792
- }
793
- }
794
- if (this.options.inherit) {
795
- const inheritFn = typeof this.options.inherit === 'function'
796
- ? this.options.inherit
797
- : undefined;
798
- let shouldInherit = this.options.inherit;
799
- if (inheritFn) {
800
- if (typeof propKey === 'string') {
801
- const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
802
- shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
803
- }
804
- else {
805
- shouldInherit = inheritFn(ownMeta, ownMeta, 'CLASS');
806
- }
807
- }
808
- if (shouldInherit) {
809
- const parent = Object.getPrototypeOf(constructor);
810
- if (typeof parent === 'function' &&
811
- parent !== fnProto &&
812
- parent !== constructor) {
813
- const inheritedMeta = (this.read(parent, propKey) ||
814
- {});
815
- const ownParams = ownMeta === null || ownMeta === void 0 ? void 0 : ownMeta.params;
816
- ownMeta = { ...inheritedMeta, ...ownMeta };
817
- if (typeof propKey === 'string' &&
818
- ownParams &&
819
- (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
820
- for (let i = 0; i < ownParams.length; i++) {
821
- if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !==
822
- 'undefined') {
823
- const ownParam = ownParams[i];
824
- if (ownMeta.params &&
825
- inheritFn &&
826
- inheritFn(ownMeta, ownParam, 'PARAM', typeof propKey === 'string'
827
- ? propKey
828
- : undefined)) {
829
- ownMeta.params[i] = {
830
- ...inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i],
831
- ...ownParams[i],
832
- };
833
- }
834
- }
835
- }
836
- }
837
- }
838
- }
839
- }
840
- return ownMeta;
841
- }
842
- apply(...decorators) {
843
- return ((target, propKey, descriptor) => {
844
- for (const d of decorators) {
845
- d(target, propKey, descriptor);
846
- }
847
- });
848
- }
849
- decorate(key, value, isArray, level) {
850
- return ((target, propKey, descriptor) => {
851
- const args = {
852
- target,
853
- propKey,
854
- descriptor: typeof descriptor === 'number' ? undefined : descriptor,
855
- index: typeof descriptor === 'number' ? descriptor : undefined,
856
- level,
857
- };
858
- this.set(args, key, value, isArray);
859
- });
860
- }
861
- decorateConditional(ccb) {
862
- return ((target, propKey, descriptor) => {
863
- const hasIndex = typeof descriptor === 'number';
864
- const decoratorLevel = hasIndex ? 'PARAM' : propKey && descriptor ? 'METHOD' : propKey ? 'PROP' : 'CLASS';
865
- const d = ccb(decoratorLevel);
866
- if (d) {
867
- d(target, propKey, descriptor);
868
- }
869
- });
870
- }
871
- decorateClass(key, value, isArray) {
872
- return this.decorate(key, value, isArray, 'CLASS');
873
- }
874
- }
875
- const fnProto = Object.getPrototypeOf(Function);
876
-
877
1030
  const METADATA_WORKSPACE = 'moost';
878
1031
  const moostMate = new Mate(METADATA_WORKSPACE, {
879
1032
  readType: true,
@@ -996,6 +1149,7 @@ function getOtelMate() {
996
1149
 
997
1150
  const mate = getOtelMate();
998
1151
  const OtelIgnoreSpan = () => mate.decorate('otelIgnoreSpan', true);
1152
+ const OtelIgnoreMeter = () => mate.decorate('otelIgnoreMeter', true);
999
1153
 
1000
1154
  function shouldSpanBeIgnored(span) {
1001
1155
  return span.attributes['moost.ignore'] === true;
@@ -1019,4 +1173,4 @@ class MoostSimpleSpanProcessor extends SimpleSpanProcessor {
1019
1173
  }
1020
1174
  }
1021
1175
 
1022
- export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreSpan, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace };
1176
+ export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreMeter, OtelIgnoreSpan, SpanInjector, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace };