@moostjs/otel 0.4.7 → 0.4.8

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,468 @@ function useOtelPropagation() {
56
76
  };
57
77
  }
58
78
 
59
- function enableOtelForMoost() {
60
- eventContextHooks$1.onStartEvent((eventType) => {
61
- if (eventType === 'init') {
62
- return;
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(name, attrs.eventType, fn);
63
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(name, eventType, cb) {
64
149
  const { registerSpan } = useOtelContext();
65
- let span;
150
+ let span = trace.getActiveSpan();
66
151
  if (eventType === 'HTTP') {
67
- span = trace.getSpan(context.active());
152
+ this.patchRsponse();
68
153
  }
69
154
  else {
70
- const tracer = trace.getTracer('moost-tracer');
71
155
  span = tracer.startSpan(`${eventType} Event`);
72
156
  }
73
157
  if (span) {
74
158
  registerSpan(span);
159
+ return this.withSpan(span, cb, {
160
+ rootSpan: true,
161
+ endSpan: eventType !== 'HTTP',
162
+ });
75
163
  }
76
- });
77
- eventContextHooks$1.onEndEvent((eventType, abortReason) => {
78
- if (eventType === 'init') {
79
- return;
164
+ return cb();
165
+ }
166
+ getEventType() {
167
+ return useAsyncEventContext$1().getCtx().event.type;
168
+ }
169
+ getIgnoreSpan() {
170
+ const { getMethodMeta, getControllerMeta } = useControllerContext();
171
+ const cMeta = getControllerMeta();
172
+ const mMeta = getMethodMeta();
173
+ return cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan;
174
+ }
175
+ getControllerHandlerMeta() {
176
+ const { getMethod, getMethodMeta, getController, getControllerMeta, getRoute } = useControllerContext();
177
+ const methodName = getMethod();
178
+ const cMeta = getControllerMeta();
179
+ const mMeta = getMethodMeta();
180
+ return {
181
+ ignoreMeter: cMeta?.otelIgnoreMeter || mMeta?.otelIgnoreMeter,
182
+ ignoreSpan: cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
183
+ attrs: {
184
+ 'moost.controller': getConstructor$2(getController()).name,
185
+ 'moost.handler': methodName,
186
+ 'moost.handler_description': mMeta?.description,
187
+ 'moost.handler_label': mMeta?.label,
188
+ 'moost.handler_id': mMeta?.id,
189
+ 'moost.ignore': cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
190
+ 'moost.route': getRoute(),
191
+ 'moost.event_type': this.getEventType(),
192
+ },
193
+ };
194
+ }
195
+ hook(name, route) {
196
+ useAsyncEventContext$1().store('otel').set('route', route);
197
+ const chm = this.getControllerHandlerMeta();
198
+ if (!chm.ignoreMeter) {
199
+ this.startEventMetrics(chm.attrs, route);
80
200
  }
81
201
  const { getSpan } = useOtelContext();
82
202
  const span = getSpan();
83
203
  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}`);
204
+ span.setAttributes(chm.attrs);
205
+ if (chm.attrs['moost.event_type'] === 'HTTP') {
206
+ span.updateName(`${this.getRequest()?.method || ''} ${route || '<unresolved>'}`);
104
207
  }
105
208
  else {
106
- span.updateName(`${methodMeta?.label || methodName}`);
209
+ span.updateName(`${chm.attrs['moost.event_type']} ${route || '<unresolved>'}`);
210
+ }
211
+ }
212
+ }
213
+ withSpan(span, cb, opts) {
214
+ let result;
215
+ let exception;
216
+ const endSpan = (error) => {
217
+ if (error) {
218
+ span.recordException(error);
219
+ }
220
+ if (opts.rootSpan) {
221
+ const chm = this.getControllerHandlerMeta();
222
+ if (!chm.ignoreMeter) {
223
+ this.endEventMetrics(chm.attrs, error);
224
+ }
225
+ }
226
+ if (opts.endSpan) {
107
227
  span.end();
108
228
  }
229
+ };
230
+ context.with(trace.setSpan(context.active(), span), () => {
231
+ try {
232
+ result = cb();
233
+ }
234
+ catch (error) {
235
+ exception = error;
236
+ endSpan(exception);
237
+ }
238
+ });
239
+ const ret = result;
240
+ if (!exception) {
241
+ if (ret && ret instanceof Promise) {
242
+ ret
243
+ .then(r => {
244
+ endSpan();
245
+ return r;
246
+ })
247
+ .catch(error => {
248
+ endSpan(error);
249
+ });
250
+ }
251
+ else {
252
+ endSpan();
253
+ }
109
254
  }
110
- });
255
+ return ret;
256
+ }
257
+ startEventMetrics(a, route) {
258
+ if (a['moost.event_type'] === 'HTTP') {
259
+ const req = this.getRequest();
260
+ const attrs = {
261
+ ...a,
262
+ route,
263
+ url: req?.url,
264
+ };
265
+ moostMetrics.httpRequestCount.add(1, attrs);
266
+ moostMetrics.httpActiveRequests.add(1, attrs);
267
+ }
268
+ const attrs = {
269
+ ...a,
270
+ route,
271
+ };
272
+ moostMetrics.moostEventCount.add(1, attrs);
273
+ moostMetrics.moostActiveEvents.add(1, attrs);
274
+ }
275
+ endEventMetrics(a, error) {
276
+ const route = useAsyncEventContext$1().store('otel').get('route');
277
+ if (a['moost.event_type'] === 'HTTP') {
278
+ const req = this.getRequest();
279
+ const res = this.getResponse();
280
+ const attrs = {
281
+ ...a,
282
+ route,
283
+ url: req?.url,
284
+ };
285
+ moostMetrics.httpActiveRequests.add(-1, attrs);
286
+ if (error) {
287
+ moostMetrics.httpErrorCount.add(1, attrs);
288
+ }
289
+ moostMetrics.httpRequestSize.record(req?.socket.bytesRead || 0, attrs);
290
+ moostMetrics.httpResponseSize.record(res?._contentLength || 0, attrs);
291
+ moostMetrics.httpResponseCount.add(1, { ...attrs, status: res?._statusCode });
292
+ }
293
+ const attrs = {
294
+ ...a,
295
+ route,
296
+ };
297
+ moostMetrics.moostActiveEvents.add(-1, attrs);
298
+ if (error) {
299
+ moostMetrics.moostErrorCount.add(1, attrs);
300
+ }
301
+ }
302
+ getRequest() {
303
+ return useAsyncEventContext$1().store('event').get('req');
304
+ }
305
+ getResponse() {
306
+ return useAsyncEventContext$1()
307
+ .store('event')
308
+ .get('res');
309
+ }
310
+ }
311
+
312
+ function enableOtelForMoost() {
313
+ replaceContextInjector(new SpanInjector());
314
+ }
315
+
316
+ function getConstructor$1(instance) {
317
+ return isConstructor(instance) ?
318
+ instance : instance.constructor ?
319
+ instance.constructor : Object.getPrototypeOf(instance).constructor;
320
+ }
321
+ function isConstructor(v) {
322
+ return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
111
323
  }
112
324
 
325
+ const classMetadata = new WeakMap();
326
+ const paramMetadata = new WeakMap();
327
+ const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
328
+ function getMetaObject(target, prop) {
329
+ const isParam = typeof prop !== 'undefined';
330
+ const metadata = isParam ? paramMetadata : classMetadata;
331
+ const targetKey = getConstructor$1(target);
332
+ let meta = metadata.get(targetKey);
333
+ if (!meta) {
334
+ meta = {};
335
+ metadata.set(targetKey, meta);
336
+ }
337
+ if (isParam) {
338
+ meta = (meta[prop] =
339
+ meta[prop] || {});
340
+ }
341
+ return meta;
342
+ }
343
+ const _reflect = {
344
+ getOwnMetadata(key, target, prop) {
345
+ return getMetaObject(target, prop)[key];
346
+ },
347
+ defineMetadata(key, data, target, prop) {
348
+ const meta = getMetaObject(target, prop);
349
+ meta[key] = data;
350
+ },
351
+ metadata(key, data) {
352
+ return ((target, propKey) => {
353
+ Reflect$1.defineMetadata(key, data, target, propKey);
354
+ });
355
+ },
356
+ };
357
+ if (!root.Reflect) {
358
+ root.Reflect = _reflect;
359
+ }
360
+ else {
361
+ const funcs = [
362
+ 'getOwnMetadata',
363
+ 'defineMetadata',
364
+ 'metadata',
365
+ ];
366
+ const target = root.Reflect;
367
+ for (const func of funcs) {
368
+ if (typeof target[func] !== 'function') {
369
+ Object.defineProperty(target, func, { configurable: true, writable: true, value: _reflect[func] });
370
+ }
371
+ }
372
+ }
373
+ const Reflect$1 = _reflect;
374
+
375
+ const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
376
+ class Mate {
377
+ constructor(workspace, options = {}) {
378
+ this.workspace = workspace;
379
+ this.options = options;
380
+ this.logger = options.logger || console;
381
+ }
382
+ set(args, key, value, isArray) {
383
+ var _a;
384
+ let level = 'CLASS';
385
+ const newArgs = args.level === 'CLASS' ? { target: args.target }
386
+ : args.level === 'PROP' ? { target: args.target, propKey: args.propKey }
387
+ : args;
388
+ let meta = (Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
389
+ if (newArgs.propKey && this.options.readReturnType && !meta.returnType && args.descriptor) {
390
+ meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
391
+ }
392
+ if (newArgs.propKey && this.options.readType && !meta.type) {
393
+ meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
394
+ }
395
+ const { index } = newArgs;
396
+ const cb = typeof key === 'function' ? key : undefined;
397
+ let data = meta;
398
+ if (!data.params) {
399
+ data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
400
+ }
401
+ if (typeof index === 'number') {
402
+ level = 'PARAM';
403
+ data.params = data.params || [];
404
+ data.params[index] = data.params[index] || {
405
+ type: undefined,
406
+ };
407
+ if (cb) {
408
+ data.params[index] = cb(data.params[index], level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
409
+ }
410
+ else {
411
+ data = data.params[index];
412
+ }
413
+ }
414
+ else if (!index && !args.descriptor && args.propKey && this.options.collectPropKeys && args.level !== 'CLASS') {
415
+ this.set({ ...args, level: 'CLASS' }, (meta) => {
416
+ if (!meta.properties) {
417
+ meta.properties = [args.propKey];
418
+ }
419
+ else if (!meta.properties.includes(args.propKey)) {
420
+ meta.properties.push(args.propKey);
421
+ }
422
+ return meta;
423
+ });
424
+ }
425
+ level = typeof index === 'number' ? 'PARAM' : newArgs.propKey && newArgs.descriptor ? 'METHOD' : newArgs.propKey ? 'PROP' : 'CLASS';
426
+ if (typeof key !== 'function') {
427
+ if (isArray) {
428
+ const newArray = (data[key] || []);
429
+ if (!Array.isArray(newArray)) {
430
+ this.logger.error('Mate.add (isArray=true) called for non-array metadata');
431
+ }
432
+ newArray.unshift(value);
433
+ data[key] = newArray;
434
+ }
435
+ else {
436
+ data[key] = value;
437
+ }
438
+ }
439
+ else if (cb && typeof index !== 'number') {
440
+ meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
441
+ }
442
+ Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
443
+ }
444
+ read(target, propKey) {
445
+ var _a;
446
+ const isConstr = isConstructor(target);
447
+ const constructor = isConstr ? target : getConstructor$1(target);
448
+ const proto = constructor.prototype;
449
+ let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
450
+ if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
451
+ const parent = Object.getPrototypeOf(constructor);
452
+ if (typeof parent === 'function' &&
453
+ parent !== fnProto &&
454
+ parent !== constructor) {
455
+ ownMeta.params = (_a = this.read(parent)) === null || _a === void 0 ? void 0 : _a.params;
456
+ }
457
+ }
458
+ if (this.options.inherit) {
459
+ const inheritFn = typeof this.options.inherit === 'function'
460
+ ? this.options.inherit
461
+ : undefined;
462
+ let shouldInherit = this.options.inherit;
463
+ if (inheritFn) {
464
+ if (typeof propKey === 'string') {
465
+ const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
466
+ shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
467
+ }
468
+ else {
469
+ shouldInherit = inheritFn(ownMeta, ownMeta, 'CLASS');
470
+ }
471
+ }
472
+ if (shouldInherit) {
473
+ const parent = Object.getPrototypeOf(constructor);
474
+ if (typeof parent === 'function' &&
475
+ parent !== fnProto &&
476
+ parent !== constructor) {
477
+ const inheritedMeta = (this.read(parent, propKey) ||
478
+ {});
479
+ const ownParams = ownMeta === null || ownMeta === void 0 ? void 0 : ownMeta.params;
480
+ ownMeta = { ...inheritedMeta, ...ownMeta };
481
+ if (typeof propKey === 'string' &&
482
+ ownParams &&
483
+ (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
484
+ for (let i = 0; i < ownParams.length; i++) {
485
+ if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !==
486
+ 'undefined') {
487
+ const ownParam = ownParams[i];
488
+ if (ownMeta.params &&
489
+ inheritFn &&
490
+ inheritFn(ownMeta, ownParam, 'PARAM', typeof propKey === 'string'
491
+ ? propKey
492
+ : undefined)) {
493
+ ownMeta.params[i] = {
494
+ ...inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i],
495
+ ...ownParams[i],
496
+ };
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }
502
+ }
503
+ }
504
+ return ownMeta;
505
+ }
506
+ apply(...decorators) {
507
+ return ((target, propKey, descriptor) => {
508
+ for (const d of decorators) {
509
+ d(target, propKey, descriptor);
510
+ }
511
+ });
512
+ }
513
+ decorate(key, value, isArray, level) {
514
+ return ((target, propKey, descriptor) => {
515
+ const args = {
516
+ target,
517
+ propKey,
518
+ descriptor: typeof descriptor === 'number' ? undefined : descriptor,
519
+ index: typeof descriptor === 'number' ? descriptor : undefined,
520
+ level,
521
+ };
522
+ this.set(args, key, value, isArray);
523
+ });
524
+ }
525
+ decorateConditional(ccb) {
526
+ return ((target, propKey, descriptor) => {
527
+ const hasIndex = typeof descriptor === 'number';
528
+ const decoratorLevel = hasIndex ? 'PARAM' : propKey && descriptor ? 'METHOD' : propKey ? 'PROP' : 'CLASS';
529
+ const d = ccb(decoratorLevel);
530
+ if (d) {
531
+ d(target, propKey, descriptor);
532
+ }
533
+ });
534
+ }
535
+ decorateClass(key, value, isArray) {
536
+ return this.decorate(key, value, isArray, 'CLASS');
537
+ }
538
+ }
539
+ const fnProto = Object.getPrototypeOf(Function);
540
+
113
541
  const defaultLevels = [
114
542
  'fatal',
115
543
  'error',
@@ -122,54 +550,6 @@ const defaultLevels = [
122
550
  const defaultMappedLevels = new Map();
123
551
  defaultLevels.forEach((type, level) => defaultMappedLevels.set(type, level));
124
552
 
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
553
  function attachHook(target, opts, name) {
174
554
  Object.defineProperty(target, name || 'value', {
175
555
  get: opts.get,
@@ -275,12 +655,6 @@ function _getCtxHelpers(cc) {
275
655
  const hasParentCtx = () => !!cc.parentCtx;
276
656
  return {
277
657
  getCtx,
278
- endEvent: (abortReason) => {
279
- if (cc && !cc._ended) {
280
- cc._ended = true;
281
- eventContextHooks.fireEndEvent(cc.event.type, abortReason);
282
- }
283
- },
284
658
  store,
285
659
  getStore: get,
286
660
  setStore: set,
@@ -304,7 +678,7 @@ function useEventId() {
304
678
  return { getId };
305
679
  }
306
680
 
307
- function getConstructor$1(instance) {
681
+ function getConstructor(instance) {
308
682
  return Object.getPrototypeOf(instance).constructor;
309
683
  }
310
684
 
@@ -592,8 +966,8 @@ class Infact {
592
966
  case 'string':
593
967
  return `"${''}...${''}"`;
594
968
  case 'object':
595
- if (getConstructor$1(p))
596
- return getConstructor$1(p).name;
969
+ if (getConstructor(p))
970
+ return getConstructor(p).name;
597
971
  return '{}';
598
972
  default:
599
973
  return '*';
@@ -649,231 +1023,6 @@ async function runPipes(pipes, initialValue, metas, level) {
649
1023
  return v;
650
1024
  }
651
1025
 
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
1026
  const METADATA_WORKSPACE = 'moost';
878
1027
  const moostMate = new Mate(METADATA_WORKSPACE, {
879
1028
  readType: true,
@@ -996,6 +1145,7 @@ function getOtelMate() {
996
1145
 
997
1146
  const mate = getOtelMate();
998
1147
  const OtelIgnoreSpan = () => mate.decorate('otelIgnoreSpan', true);
1148
+ const OtelIgnoreMeter = () => mate.decorate('otelIgnoreMeter', true);
999
1149
 
1000
1150
  function shouldSpanBeIgnored(span) {
1001
1151
  return span.attributes['moost.ignore'] === true;
@@ -1019,4 +1169,4 @@ class MoostSimpleSpanProcessor extends SimpleSpanProcessor {
1019
1169
  }
1020
1170
  }
1021
1171
 
1022
- export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreSpan, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace };
1172
+ export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreMeter, OtelIgnoreSpan, SpanInjector, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace };