arvo-core 1.0.21 → 1.0.23

Sign up to get free protection for your applications and to get access to all the features.
package/CHANGELOG.md CHANGED
@@ -40,7 +40,7 @@
40
40
 
41
41
  - Fix a type bug in ArvoEvent creation
42
42
 
43
- ## [1.0.21] - 2024-09-07
43
+ ## [1.0.23] - 2024-09-07
44
44
 
45
45
  - Updated OpenTelemetry propagation and fixed propagation in the event factory
46
46
 
@@ -1,11 +1,9 @@
1
1
  import ArvoEvent from '.';
2
- import { TelemetryContext } from '../OpenTelemetry/types';
3
2
  import { ArvoEventData, CloudEventExtension, CreateArvoEvent } from './types';
4
3
  /**
5
4
  * Creates an ArvoEvent with the provided data and extensions.
6
5
  *
7
6
  * This function creates a new ArvoEvent instance using the provided event data and optional extensions.
8
- * It also supports OpenTelemetry tracing if a telemetry context is provided.
9
7
  *
10
8
  * @template TData - The type of the event data, extending ArvoEventData.
11
9
  * @template TExtension - The type of the cloud event extension, extending CloudEventExtension.
@@ -13,7 +11,6 @@ import { ArvoEventData, CloudEventExtension, CreateArvoEvent } from './types';
13
11
  *
14
12
  * @param {CreateArvoEvent<TData>} event - The event data and metadata to create the ArvoEvent.
15
13
  * @param {TExtension} [extensions] - Optional cloud event extensions.
16
- * @param {TelemetryContext} [telemetry] - Optional telemetry context for tracing.
17
14
  *
18
15
  * @returns {ArvoEvent<TData, TExtension>} The created ArvoEvent instance.
19
16
  *
@@ -35,7 +32,6 @@ import { ArvoEventData, CloudEventExtension, CreateArvoEvent } from './types';
35
32
  * data: { key: 'value' }
36
33
  * },
37
34
  * { customExtension: 'value' },
38
- * telemetryContext
39
35
  * );
40
36
  */
41
- export declare const createArvoEvent: <TData extends ArvoEventData, TExtension extends CloudEventExtension, TType extends string>(event: CreateArvoEvent<TData, TType>, extensions?: TExtension, telemetry?: TelemetryContext) => ArvoEvent<TData, TExtension, TType>;
37
+ export declare const createArvoEvent: <TData extends ArvoEventData, TExtension extends CloudEventExtension, TType extends string>(event: CreateArvoEvent<TData, TType>, extensions?: TExtension) => ArvoEvent<TData, TExtension, TType>;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createArvoEvent = void 0;
7
+ var api_1 = require("@opentelemetry/api");
7
8
  var _1 = __importDefault(require("."));
8
9
  var OpenTelemetry_1 = require("../OpenTelemetry");
9
10
  var utils_1 = require("../utils");
@@ -13,7 +14,6 @@ var uuid_1 = require("uuid");
13
14
  * Creates an ArvoEvent with the provided data and extensions.
14
15
  *
15
16
  * This function creates a new ArvoEvent instance using the provided event data and optional extensions.
16
- * It also supports OpenTelemetry tracing if a telemetry context is provided.
17
17
  *
18
18
  * @template TData - The type of the event data, extending ArvoEventData.
19
19
  * @template TExtension - The type of the cloud event extension, extending CloudEventExtension.
@@ -21,7 +21,6 @@ var uuid_1 = require("uuid");
21
21
  *
22
22
  * @param {CreateArvoEvent<TData>} event - The event data and metadata to create the ArvoEvent.
23
23
  * @param {TExtension} [extensions] - Optional cloud event extensions.
24
- * @param {TelemetryContext} [telemetry] - Optional telemetry context for tracing.
25
24
  *
26
25
  * @returns {ArvoEvent<TData, TExtension>} The created ArvoEvent instance.
27
26
  *
@@ -43,35 +42,49 @@ var uuid_1 = require("uuid");
43
42
  * data: { key: 'value' }
44
43
  * },
45
44
  * { customExtension: 'value' },
46
- * telemetryContext
47
45
  * );
48
46
  */
49
- var createArvoEvent = function (event, extensions, telemetry) {
50
- return (0, OpenTelemetry_1.createOtelSpan)(telemetry || 'ArvoEvent Creation Tracer', "createArvoEvent<".concat(event.type, ">"), {}, function (telemetryContext) {
51
- if (event.datacontenttype &&
52
- event.datacontenttype !== schema_1.ArvoDataContentType) {
53
- var warning = (0, utils_1.cleanString)("\n Warning! The provided datacontenttype(=".concat(event.datacontenttype, ")\n is not ArvoEvent compatible (=").concat(schema_1.ArvoDataContentType, "). There may \n be some limited functionality.\n "));
54
- (0, OpenTelemetry_1.logToSpan)(telemetryContext.span, {
55
- level: 'WARNING',
56
- message: warning,
47
+ var createArvoEvent = function (event, extensions) {
48
+ var span = OpenTelemetry_1.ArvoCoreTracer.startSpan("createArvoEvent<".concat(event.type, ">"), {});
49
+ return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), function () {
50
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
51
+ try {
52
+ if (event.datacontenttype &&
53
+ event.datacontenttype !== schema_1.ArvoDataContentType) {
54
+ var warning = (0, utils_1.cleanString)("\n Warning! The provided datacontenttype(=".concat(event.datacontenttype, ")\n is not ArvoEvent compatible (=").concat(schema_1.ArvoDataContentType, "). There may \n be some limited functionality.\n "));
55
+ (0, OpenTelemetry_1.logToSpan)(span, {
56
+ level: 'WARNING',
57
+ message: warning,
58
+ });
59
+ }
60
+ return new _1.default({
61
+ id: event.id || (0, uuid_1.v4)(),
62
+ type: event.type,
63
+ accesscontrol: event.accesscontrol || null,
64
+ executionunits: event.executionunits || null,
65
+ traceparent: event.traceparent || null,
66
+ tracestate: event.tracestate || null,
67
+ datacontenttype: event.datacontenttype || schema_1.ArvoDataContentType,
68
+ specversion: event.specversion || '1.0',
69
+ time: event.time || (0, utils_1.createTimestamp)(),
70
+ source: encodeURI(event.source),
71
+ subject: encodeURI(event.subject),
72
+ to: event.to ? encodeURI(event.to) : null,
73
+ redirectto: event.redirectto ? encodeURI(event.redirectto) : null,
74
+ dataschema: event.dataschema ? encodeURI(event.dataschema) : null,
75
+ }, event.data, extensions);
76
+ }
77
+ catch (error) {
78
+ (0, OpenTelemetry_1.exceptionToSpan)(span, error);
79
+ span.setStatus({
80
+ code: api_1.SpanStatusCode.ERROR,
81
+ message: error.message,
57
82
  });
83
+ throw error;
84
+ }
85
+ finally {
86
+ span.end();
58
87
  }
59
- return new _1.default({
60
- id: event.id || (0, uuid_1.v4)(),
61
- type: event.type,
62
- accesscontrol: event.accesscontrol || null,
63
- executionunits: event.executionunits || null,
64
- traceparent: event.traceparent || null,
65
- tracestate: event.tracestate || null,
66
- datacontenttype: event.datacontenttype || schema_1.ArvoDataContentType,
67
- specversion: event.specversion || '1.0',
68
- time: event.time || (0, utils_1.createTimestamp)(),
69
- source: encodeURI(event.source),
70
- subject: encodeURI(event.subject),
71
- to: event.to ? encodeURI(event.to) : null,
72
- redirectto: event.redirectto ? encodeURI(event.redirectto) : null,
73
- dataschema: event.dataschema ? encodeURI(event.dataschema) : null,
74
- }, event.data, extensions);
75
88
  });
76
89
  };
77
90
  exports.createArvoEvent = createArvoEvent;
@@ -1,5 +1,5 @@
1
- import ArvoEventFactory from ".";
2
- import ArvoContract from "../ArvoContract";
1
+ import ArvoEventFactory from '.';
2
+ import ArvoContract from '../ArvoContract';
3
3
  import { z } from 'zod';
4
4
  /**
5
5
  * Creates a ArvoEventFactory instance based on the provided contract.
@@ -1,7 +1,6 @@
1
- import ArvoContract from "../ArvoContract";
1
+ import ArvoContract from '../ArvoContract';
2
2
  import { z } from 'zod';
3
- import { CreateArvoEvent } from "../ArvoEvent/types";
4
- import { TelemetryContext } from "../OpenTelemetry/types";
3
+ import { CreateArvoEvent } from '../ArvoEvent/types';
5
4
  /**
6
5
  * A factory class for creating contractual ArvoEvents based on a given ArvoContract.
7
6
  *
@@ -13,7 +12,7 @@ import { TelemetryContext } from "../OpenTelemetry/types";
13
12
  export default class ArvoEventFactory<TUri extends string = string, TType extends string = string, TAcceptSchema extends z.ZodTypeAny = z.ZodTypeAny, TEmits extends Record<string, z.ZodTypeAny> = Record<string, z.ZodTypeAny>> {
14
13
  private contract;
15
14
  /**
16
- * Creates an instance of ContractualArvoEventFactory.
15
+ * Creates an instance of ArvoEventFactory.
17
16
  *
18
17
  * @param contract - The ArvoContract to base the events on.
19
18
  */
@@ -24,13 +23,12 @@ export default class ArvoEventFactory<TUri extends string = string, TType extend
24
23
  * @template TExtension - The type of extensions to add to the event.
25
24
  * @param event - The event to create. The field 'type' is automatically infered
26
25
  * @param [extensions] - Optional extensions to add to the event.
27
- * @param [telemetry] - Optional telemetry context for tracing.
28
26
  * @returns The created ArvoEvent as per the accept record of the contract.
29
27
  * @throws If the event data fails validation against the contract.
30
28
  */
31
29
  accepts<TExtension extends Record<string, any>>(event: Omit<CreateArvoEvent<z.infer<TAcceptSchema>, TType>, 'type'> & {
32
30
  to: string;
33
- }, extensions?: TExtension, telemetry?: TelemetryContext): import("..").ArvoEvent<z.TypeOf<TAcceptSchema>, TExtension, TType>;
31
+ }, extensions?: TExtension): import("..").ArvoEvent<z.TypeOf<TAcceptSchema>, TExtension, TType>;
34
32
  /**
35
33
  * Creates an ArvoEvent as per one of the emits record in the contract.
36
34
  *
@@ -38,26 +36,24 @@ export default class ArvoEventFactory<TUri extends string = string, TType extend
38
36
  * @template TExtension - The type of extensions to add to the event.
39
37
  * @param event - The event to create.
40
38
  * @param [extensions] - Optional extensions to add to the event.
41
- * @param [telemetry] - Optional telemetry context for tracing.
42
39
  * @returns The created ArvoEvent as per one of the emits records of the contract.
43
40
  * @throws If the event data fails validation against the contract.
44
41
  */
45
42
  emits<U extends keyof TEmits & string, TExtension extends Record<string, any>>(event: CreateArvoEvent<z.infer<TEmits[U]>, U> & {
46
43
  to: string;
47
- }, extensions?: TExtension, telemetry?: TelemetryContext): import("..").ArvoEvent<z.TypeOf<TEmits[U]>, TExtension, U>;
44
+ }, extensions?: TExtension): import("..").ArvoEvent<z.TypeOf<TEmits[U]>, TExtension, U>;
48
45
  /**
49
46
  * Creates a system error ArvoEvent.
50
47
  *
51
48
  * @template TExtension - The type of extensions to add to the event.
52
49
  * @param event - The event to create, including the error.
53
50
  * @param [extensions] - Optional extensions to add to the event.
54
- * @param [telemetry] - Optional telemetry context for tracing.
55
51
  * @returns The created system error ArvoEvent.
56
52
  */
57
53
  systemError<TExtension extends Record<string, any>>(event: Omit<CreateArvoEvent<any, any>, 'data' | 'type'> & {
58
54
  error: Error;
59
55
  to: string;
60
- }, extensions?: TExtension, telemetry?: TelemetryContext): import("..").ArvoEvent<{
56
+ }, extensions?: TExtension): import("..").ArvoEvent<{
61
57
  errorName: string;
62
58
  errorMessage: string;
63
59
  errorStack: string | null;
@@ -25,6 +25,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
25
25
  var helpers_1 = require("../ArvoEvent/helpers");
26
26
  var schema_1 = require("../ArvoEvent/schema");
27
27
  var OpenTelemetry_1 = require("../OpenTelemetry");
28
+ var api_1 = require("@opentelemetry/api");
28
29
  /**
29
30
  * A factory class for creating contractual ArvoEvents based on a given ArvoContract.
30
31
  *
@@ -35,7 +36,7 @@ var OpenTelemetry_1 = require("../OpenTelemetry");
35
36
  */
36
37
  var ArvoEventFactory = /** @class */ (function () {
37
38
  /**
38
- * Creates an instance of ContractualArvoEventFactory.
39
+ * Creates an instance of ArvoEventFactory.
39
40
  *
40
41
  * @param contract - The ArvoContract to base the events on.
41
42
  */
@@ -48,18 +49,32 @@ var ArvoEventFactory = /** @class */ (function () {
48
49
  * @template TExtension - The type of extensions to add to the event.
49
50
  * @param event - The event to create. The field 'type' is automatically infered
50
51
  * @param [extensions] - Optional extensions to add to the event.
51
- * @param [telemetry] - Optional telemetry context for tracing.
52
52
  * @returns The created ArvoEvent as per the accept record of the contract.
53
53
  * @throws If the event data fails validation against the contract.
54
54
  */
55
- ArvoEventFactory.prototype.accepts = function (event, extensions, telemetry) {
55
+ ArvoEventFactory.prototype.accepts = function (event, extensions) {
56
56
  var _this = this;
57
- return (0, OpenTelemetry_1.createOtelSpan)(telemetry || 'ArvoEvent Creation Tracer', "ContractualArvoEventFactory<".concat(this.contract.uri, ">.accepts<").concat(this.contract.accepts.type, ">.create"), {}, function (telemetryContext) {
58
- var validationResult = _this.contract.validateInput(_this.contract.accepts.type, event.data);
59
- if (!validationResult.success) {
60
- throw new Error("Accept Event data validation failed: ".concat(validationResult.error.message));
57
+ var span = OpenTelemetry_1.ArvoCoreTracer.startSpan("ArvoEventFactory<".concat(this.contract.uri, ">.accepts<").concat(this.contract.accepts.type, ">.create"));
58
+ return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), function () {
59
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
60
+ try {
61
+ var validationResult = _this.contract.validateInput(_this.contract.accepts.type, event.data);
62
+ if (!validationResult.success) {
63
+ throw new Error("Accept Event data validation failed: ".concat(validationResult.error.message));
64
+ }
65
+ return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { type: _this.contract.accepts.type, datacontenttype: schema_1.ArvoDataContentType, dataschema: _this.contract.uri, data: validationResult.data }), extensions);
66
+ }
67
+ catch (error) {
68
+ (0, OpenTelemetry_1.exceptionToSpan)(span, error);
69
+ span.setStatus({
70
+ code: api_1.SpanStatusCode.ERROR,
71
+ message: error.message,
72
+ });
73
+ throw error;
74
+ }
75
+ finally {
76
+ span.end();
61
77
  }
62
- return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { type: _this.contract.accepts.type, datacontenttype: schema_1.ArvoDataContentType, dataschema: _this.contract.uri, data: validationResult.data }), extensions, telemetryContext);
63
78
  });
64
79
  };
65
80
  /**
@@ -69,18 +84,32 @@ var ArvoEventFactory = /** @class */ (function () {
69
84
  * @template TExtension - The type of extensions to add to the event.
70
85
  * @param event - The event to create.
71
86
  * @param [extensions] - Optional extensions to add to the event.
72
- * @param [telemetry] - Optional telemetry context for tracing.
73
87
  * @returns The created ArvoEvent as per one of the emits records of the contract.
74
88
  * @throws If the event data fails validation against the contract.
75
89
  */
76
- ArvoEventFactory.prototype.emits = function (event, extensions, telemetry) {
90
+ ArvoEventFactory.prototype.emits = function (event, extensions) {
77
91
  var _this = this;
78
- return (0, OpenTelemetry_1.createOtelSpan)(telemetry || 'ArvoEvent Creation Tracer', "ContractualArvoEventFactory<".concat(this.contract.uri, ">.emits<").concat(event.type, ">.create"), {}, function (telemetryContext) {
79
- var validationResult = _this.contract.validateOutput(event.type, event.data);
80
- if (!validationResult.success) {
81
- throw new Error("Emit Event data validation failed: ".concat(validationResult.error.message));
92
+ var span = OpenTelemetry_1.ArvoCoreTracer.startSpan("ArvoEventFactory<".concat(this.contract.uri, ">.emits<").concat(event.type, ">.create"));
93
+ return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), function () {
94
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
95
+ try {
96
+ var validationResult = _this.contract.validateOutput(event.type, event.data);
97
+ if (!validationResult.success) {
98
+ throw new Error("Emit Event data validation failed: ".concat(validationResult.error.message));
99
+ }
100
+ return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { datacontenttype: schema_1.ArvoDataContentType, dataschema: _this.contract.uri, data: validationResult.data }), extensions);
101
+ }
102
+ catch (error) {
103
+ (0, OpenTelemetry_1.exceptionToSpan)(span, error);
104
+ span.setStatus({
105
+ code: api_1.SpanStatusCode.ERROR,
106
+ message: error.message,
107
+ });
108
+ throw error;
109
+ }
110
+ finally {
111
+ span.end();
82
112
  }
83
- return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { datacontenttype: schema_1.ArvoDataContentType, dataschema: _this.contract.uri, data: validationResult.data }), extensions, telemetryContext);
84
113
  });
85
114
  };
86
115
  /**
@@ -89,18 +118,32 @@ var ArvoEventFactory = /** @class */ (function () {
89
118
  * @template TExtension - The type of extensions to add to the event.
90
119
  * @param event - The event to create, including the error.
91
120
  * @param [extensions] - Optional extensions to add to the event.
92
- * @param [telemetry] - Optional telemetry context for tracing.
93
121
  * @returns The created system error ArvoEvent.
94
122
  */
95
- ArvoEventFactory.prototype.systemError = function (event, extensions, telemetry) {
123
+ ArvoEventFactory.prototype.systemError = function (event, extensions) {
96
124
  var _this = this;
97
- return (0, OpenTelemetry_1.createOtelSpan)(telemetry || 'ArvoEvent Creation Tracer', "ContractualArvoEventFactory<".concat(this.contract.uri, ">.systemError<sys.").concat(this.contract.accepts.type, ".error>.create"), {}, function (telemetryContext) {
98
- var error = event.error, _events = __rest(event, ["error"]);
99
- return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { type: "sys.".concat(_this.contract.accepts.type, ".error"), data: {
100
- errorName: error.name,
101
- errorMessage: error.message,
102
- errorStack: error.stack || null,
103
- }, datacontenttype: schema_1.ArvoDataContentType, dataschema: _this.contract.uri }), extensions, telemetryContext);
125
+ var span = OpenTelemetry_1.ArvoCoreTracer.startSpan("ArvoEventFactory<".concat(this.contract.uri, ">.systemError<sys.").concat(this.contract.accepts.type, ".error>.create"));
126
+ return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), function () {
127
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
128
+ try {
129
+ var error = event.error, _events = __rest(event, ["error"]);
130
+ return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { type: "sys.".concat(_this.contract.accepts.type, ".error"), data: {
131
+ errorName: error.name,
132
+ errorMessage: error.message,
133
+ errorStack: error.stack || null,
134
+ }, datacontenttype: schema_1.ArvoDataContentType, dataschema: _this.contract.uri }), extensions);
135
+ }
136
+ catch (error) {
137
+ (0, OpenTelemetry_1.exceptionToSpan)(span, error);
138
+ span.setStatus({
139
+ code: api_1.SpanStatusCode.ERROR,
140
+ message: error.message,
141
+ });
142
+ throw error;
143
+ }
144
+ finally {
145
+ span.end();
146
+ }
104
147
  });
105
148
  };
106
149
  return ArvoEventFactory;
@@ -1,18 +1,9 @@
1
- import { Context, Span, SpanOptions } from '@opentelemetry/api';
2
- import { TelemetryCarrier, TelemetryLogLevel, TelemetryContext } from './types';
1
+ import { Span } from '@opentelemetry/api';
2
+ import { TelemetryLogLevel, OpenTelemetryHeaders } from './types';
3
3
  /**
4
- * Retrieves the active context based on the provided trace header.
5
- * @param traceparent - The trace header string.
6
- * @returns The active context.
4
+ * A tracer instance for the ArvoCore package.
7
5
  */
8
- export declare const getTelemetryContext: (carrier?: TelemetryCarrier) => Context;
9
- /**
10
- * Parses the context from a span and active context.
11
- * @param span - The span to parse the context from.
12
- * @param activeContext - The active context (optional, defaults to the current active context).
13
- * @returns The parsed telemetry context.
14
- */
15
- export declare const getTelemetryCarrier: (span: Span, activeContext?: Context) => TelemetryCarrier;
6
+ export declare const ArvoCoreTracer: import("@opentelemetry/api").Tracer;
16
7
  /**
17
8
  * Logs a message to a span with additional parameters.
18
9
  * @param span - The span to log the message to.
@@ -30,67 +21,13 @@ export declare const logToSpan: (span: Span, params: {
30
21
  * @param level - The log level for the exception.
31
22
  * @param error - The error object to be logged.
32
23
  */
33
- export declare const exceptionToSpan: (span: Span, level: TelemetryLogLevel, error: Error) => void;
34
- /**
35
- * Creates a new OpenTelemetry span and executes the provided function within its context.
36
- *
37
- * This function enhances tracing by creating a new span, executing the given function within
38
- * that span's context, and properly handling any errors that may occur. It also ensures that
39
- * the wrapped function has access to the current span.
40
- *
41
- * @template TArgs - The type of the arguments array for the wrapped function.
42
- * @template TReturn - The return type of the wrapped function.
43
- *
44
- * @param {TelemetryContext | string} telemetryContext - The OpenTelemetry context object or a tracer name.
45
- * If a string is provided, it will be used as the tracer name to retrieve the tracer.
46
- * If a `TelemetryContext` object is provided, it should contain the span, tracer, and carrier information.
47
- * @param {string} spanName - The name of the span to be created.
48
- * @param {SpanOptions} [spanOptions] - Optional configuration for the span, such as attributes, links, and sampling.
49
- * @param {(telemetryContext: TelemetryContext, ...args: TArgs) => TReturn} wrappedFunction - The function to be executed within the new span.
50
- * This function will receive the `TelemetryContext` object as its first argument, containing the current span, tracer, and carrier.
51
- * The rest of the arguments will be passed as additional parameters to the wrapped function.
52
- * @param {ThisParameterType<TFunction>} [thisArg] - The 'this' context to be used when calling the wrapped function.
53
- * @param {...TArgs} args - The arguments to be passed to the wrapped function.
54
- *
55
- * @returns {TReturn} The result of the wrapped function execution.
56
- *
57
- * @throws {Error} Rethrows any error that occurs during the execution of the wrapped function.
58
- * The error will be logged to the span with an 'ERROR' level, and the span status will be set to `SpanStatusCode.ERROR`.
59
- *
60
- * @example
61
- * // Using with TelemetryContext
62
- * const telemetryContext: TelemetryContext = {
63
- * span: currentSpan,
64
- * tracer: currentTracer,
65
- * carrier: { traceparent: 'traceparent-value', tracestate: 'tracestate-value' }
66
- * };
67
- * const result = createOtelSpan(
68
- * telemetryContext,
69
- * 'ProcessOrder',
70
- * { attributes: { orderId: '12345' } },
71
- * (telemetryContext, orderId) => {
72
- * telemetryContext.span.addEvent('Processing order');
73
- * return processOrder(orderId);
74
- * },
75
- * null,
76
- * '12345'
77
- * );
78
- *
79
- * @example
80
- * // Using with tracer name
81
- * const result = createOtelSpan(
82
- * 'OrderService',
83
- * 'FetchOrderDetails',
84
- * undefined,
85
- * (telemetryContext, orderId) => {
86
- * telemetryContext.span.setAttribute('orderId', orderId);
87
- * return fetchOrderDetails(orderId);
88
- * },
89
- * null,
90
- * '12345'
91
- * );
92
- */ export declare const createOtelSpan: <TArgs extends unknown[], TReturn>(telemetryContext: TelemetryContext | string, spanName: string, spanOptions: SpanOptions | undefined, wrappedFunction: (telemetryContext: TelemetryContext, ...args: TArgs) => TReturn, thisArg?: ThisParameterType<typeof wrappedFunction>, ...args: TArgs) => TReturn;
24
+ export declare const exceptionToSpan: (span: Span, error: Error) => void;
93
25
  /**
94
26
  * A constant representing a null or not applicable value in OpenTelemetry context.
95
27
  */
96
28
  export declare const OTelNull = "N/A";
29
+ /**
30
+ * Retrieves the current OpenTelemetry headers from the active context.
31
+ * @returns An object containing the traceparent and tracestate headers.
32
+ */
33
+ export declare function currentOpenTelemetryHeaders(): OpenTelemetryHeaders;
@@ -10,49 +10,17 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
14
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
15
- if (ar || !(i in from)) {
16
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
17
- ar[i] = from[i];
18
- }
19
- }
20
- return to.concat(ar || Array.prototype.slice.call(from));
21
- };
22
13
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.OTelNull = exports.createOtelSpan = exports.exceptionToSpan = exports.logToSpan = exports.getTelemetryCarrier = exports.getTelemetryContext = void 0;
14
+ exports.OTelNull = exports.exceptionToSpan = exports.logToSpan = exports.ArvoCoreTracer = void 0;
15
+ exports.currentOpenTelemetryHeaders = currentOpenTelemetryHeaders;
24
16
  var api_1 = require("@opentelemetry/api");
17
+ var utils_1 = require("./utils");
18
+ var core_1 = require("@opentelemetry/core");
19
+ var pkg = (0, utils_1.getPackageInfo)();
25
20
  /**
26
- * Retrieves the active context based on the provided trace header.
27
- * @param traceparent - The trace header string.
28
- * @returns The active context.
29
- */
30
- var getTelemetryContext = function (carrier) {
31
- if (carrier && (carrier.traceparent || carrier.tracestate)) {
32
- return api_1.propagation.extract(api_1.ROOT_CONTEXT, carrier);
33
- }
34
- return api_1.context.active();
35
- };
36
- exports.getTelemetryContext = getTelemetryContext;
37
- /**
38
- * Parses the context from a span and active context.
39
- * @param span - The span to parse the context from.
40
- * @param activeContext - The active context (optional, defaults to the current active context).
41
- * @returns The parsed telemetry context.
21
+ * A tracer instance for the ArvoCore package.
42
22
  */
43
- var getTelemetryCarrier = function (span, activeContext) {
44
- if (activeContext === void 0) { activeContext = api_1.context.active(); }
45
- var carrier = {
46
- traceparent: null,
47
- tracestate: null,
48
- };
49
- api_1.propagation.inject(activeContext, carrier);
50
- if (!carrier.traceparent) {
51
- carrier.traceparent = "00-".concat(span.spanContext().traceId, "-").concat(span.spanContext().spanId, "-0").concat(span.spanContext().traceFlags);
52
- }
53
- return carrier;
54
- };
55
- exports.getTelemetryCarrier = getTelemetryCarrier;
23
+ exports.ArvoCoreTracer = api_1.trace.getTracer(pkg.name, pkg.version);
56
24
  /**
57
25
  * Logs a message to a span with additional parameters.
58
26
  * @param span - The span to log the message to.
@@ -70,118 +38,38 @@ exports.logToSpan = logToSpan;
70
38
  * @param level - The log level for the exception.
71
39
  * @param error - The error object to be logged.
72
40
  */
73
- var exceptionToSpan = function (span, level, error) {
74
- (0, exports.logToSpan)(span, {
75
- level: level,
76
- message: error.message,
77
- });
41
+ var exceptionToSpan = function (span, error) {
78
42
  span.setAttributes({
79
- 'exception.type': "[".concat(level, "] ").concat(error.name),
43
+ 'exception.type': error.name,
80
44
  'exception.message': error.message,
81
- 'exception.stacktrace': error.stack || exports.OTelNull,
82
45
  });
46
+ span.recordException(error);
83
47
  };
84
48
  exports.exceptionToSpan = exceptionToSpan;
85
- /**
86
- * Creates a new OpenTelemetry span and executes the provided function within its context.
87
- *
88
- * This function enhances tracing by creating a new span, executing the given function within
89
- * that span's context, and properly handling any errors that may occur. It also ensures that
90
- * the wrapped function has access to the current span.
91
- *
92
- * @template TArgs - The type of the arguments array for the wrapped function.
93
- * @template TReturn - The return type of the wrapped function.
94
- *
95
- * @param {TelemetryContext | string} telemetryContext - The OpenTelemetry context object or a tracer name.
96
- * If a string is provided, it will be used as the tracer name to retrieve the tracer.
97
- * If a `TelemetryContext` object is provided, it should contain the span, tracer, and carrier information.
98
- * @param {string} spanName - The name of the span to be created.
99
- * @param {SpanOptions} [spanOptions] - Optional configuration for the span, such as attributes, links, and sampling.
100
- * @param {(telemetryContext: TelemetryContext, ...args: TArgs) => TReturn} wrappedFunction - The function to be executed within the new span.
101
- * This function will receive the `TelemetryContext` object as its first argument, containing the current span, tracer, and carrier.
102
- * The rest of the arguments will be passed as additional parameters to the wrapped function.
103
- * @param {ThisParameterType<TFunction>} [thisArg] - The 'this' context to be used when calling the wrapped function.
104
- * @param {...TArgs} args - The arguments to be passed to the wrapped function.
105
- *
106
- * @returns {TReturn} The result of the wrapped function execution.
107
- *
108
- * @throws {Error} Rethrows any error that occurs during the execution of the wrapped function.
109
- * The error will be logged to the span with an 'ERROR' level, and the span status will be set to `SpanStatusCode.ERROR`.
110
- *
111
- * @example
112
- * // Using with TelemetryContext
113
- * const telemetryContext: TelemetryContext = {
114
- * span: currentSpan,
115
- * tracer: currentTracer,
116
- * carrier: { traceparent: 'traceparent-value', tracestate: 'tracestate-value' }
117
- * };
118
- * const result = createOtelSpan(
119
- * telemetryContext,
120
- * 'ProcessOrder',
121
- * { attributes: { orderId: '12345' } },
122
- * (telemetryContext, orderId) => {
123
- * telemetryContext.span.addEvent('Processing order');
124
- * return processOrder(orderId);
125
- * },
126
- * null,
127
- * '12345'
128
- * );
129
- *
130
- * @example
131
- * // Using with tracer name
132
- * const result = createOtelSpan(
133
- * 'OrderService',
134
- * 'FetchOrderDetails',
135
- * undefined,
136
- * (telemetryContext, orderId) => {
137
- * telemetryContext.span.setAttribute('orderId', orderId);
138
- * return fetchOrderDetails(orderId);
139
- * },
140
- * null,
141
- * '12345'
142
- * );
143
- */ var createOtelSpan = function (telemetryContext, spanName, spanOptions, wrappedFunction, thisArg) {
144
- var args = [];
145
- for (var _i = 5; _i < arguments.length; _i++) {
146
- args[_i - 5] = arguments[_i];
147
- }
148
- var activeContext = api_1.ROOT_CONTEXT;
149
- var activeTracer;
150
- if (typeof telemetryContext === 'string') {
151
- activeTracer = api_1.trace.getTracer(telemetryContext);
152
- }
153
- else {
154
- activeContext = (0, exports.getTelemetryContext)(telemetryContext.carrier);
155
- activeTracer = telemetryContext.tracer;
156
- }
157
- var newSpan = activeTracer.startSpan(spanName, spanOptions, activeContext);
158
- newSpan.setStatus({
159
- code: api_1.SpanStatusCode.OK,
160
- });
161
- try {
162
- var result = api_1.context.with(api_1.trace.setSpan(activeContext, newSpan), function () {
163
- return wrappedFunction.call.apply(wrappedFunction, __spreadArray([thisArg,
164
- {
165
- span: newSpan,
166
- tracer: activeTracer,
167
- carrier: (0, exports.getTelemetryCarrier)(newSpan, activeContext),
168
- }], args, false));
169
- });
170
- newSpan.end();
171
- return result;
172
- }
173
- catch (error) {
174
- (0, exports.exceptionToSpan)(newSpan, 'ERROR', error);
175
- newSpan.setStatus({
176
- code: api_1.SpanStatusCode.ERROR,
177
- message: error.message,
178
- });
179
- newSpan.end();
180
- throw error;
181
- }
182
- };
183
- exports.createOtelSpan = createOtelSpan;
184
49
  /**
185
50
  * A constant representing a null or not applicable value in OpenTelemetry context.
186
51
  */
187
52
  exports.OTelNull = 'N/A';
53
+ /**
54
+ * Retrieves the current OpenTelemetry headers from the active context.
55
+ * @returns An object containing the traceparent and tracestate headers.
56
+ */
57
+ function currentOpenTelemetryHeaders() {
58
+ var propagator = new core_1.W3CTraceContextPropagator();
59
+ var carrier = {
60
+ traceparent: null,
61
+ tracestate: null
62
+ };
63
+ var setter = {
64
+ set: function (carrier, key, value) {
65
+ if (carrier && typeof carrier === 'object') {
66
+ carrier[key] = value;
67
+ }
68
+ },
69
+ };
70
+ propagator.inject(api_1.context.active(), carrier, setter);
71
+ return {
72
+ traceparent: carrier.traceparent,
73
+ tracestate: carrier.tracestate
74
+ };
75
+ }
@@ -1,4 +1,3 @@
1
- import { Span, Tracer } from '@opentelemetry/api';
2
1
  /**
3
2
  * Represents the available log levels for telemetry.
4
3
  * - DEBUG: Used for detailed information, typically of interest only when diagnosing problems.
@@ -12,29 +11,9 @@ export type TelemetryLogLevel = 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'CRITIC
12
11
  * Represents the context for telemetry.
13
12
  * See reference standard documentation [here](https://www.w3.org/TR/trace-context/#design-overview)
14
13
  */
15
- export type TelemetryCarrier = {
14
+ export type OpenTelemetryHeaders = {
16
15
  /** The traceparent header value */
17
16
  traceparent: string | null;
18
17
  /** The tracestate header value */
19
18
  tracestate: string | null;
20
19
  };
21
- /**
22
- * Represents the OpenTelemetry context for a handler.
23
- * See reference documentation [here](https://opentelemetry.io/docs/languages/js/instrumentation/#traces)
24
- */
25
- export type TelemetryContext = {
26
- /**
27
- * The current OpenTelemetry Span. If passed to a function,
28
- * then for that function, this is the parent span object
29
- */
30
- span: Span;
31
- /**
32
- * The current OpenTelemetry tracer object being
33
- * used.
34
- */
35
- tracer: Tracer;
36
- /**
37
- * The telemetry headers
38
- */
39
- carrier: TelemetryCarrier;
40
- };
@@ -0,0 +1,4 @@
1
+ export declare function getPackageInfo(): {
2
+ name: string;
3
+ version: string;
4
+ };
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getPackageInfo = getPackageInfo;
27
+ var fs = __importStar(require("fs"));
28
+ var path = __importStar(require("path"));
29
+ function getPackageInfo() {
30
+ try {
31
+ // Read the package.json file
32
+ var packageJsonPath = path.resolve(__dirname, '../../package.json');
33
+ var packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');
34
+ // Parse the JSON content
35
+ var packageJson = JSON.parse(packageJsonContent);
36
+ // Extract name and version
37
+ var name_1 = packageJson.name, version = packageJson.version;
38
+ return { name: name_1, version: version };
39
+ }
40
+ catch (error) {
41
+ console.error('Error reading package.json:', error);
42
+ return { name: 'Unknown', version: 'Unknown' };
43
+ }
44
+ }
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import ArvoEvent from './ArvoEvent';
2
2
  import { ArvoDataContentType } from './ArvoEvent/schema';
3
3
  import { createArvoEvent } from './ArvoEvent/helpers';
4
4
  import { CloudEventContext, CloudEventExtension, ArvoEventData, ArvoExtension, OpenTelemetryExtension, CreateArvoEvent } from './ArvoEvent/types';
5
- import { exceptionToSpan, logToSpan, getTelemetryContext, getTelemetryCarrier, createOtelSpan, OTelNull } from './OpenTelemetry';
6
- import { TelemetryCarrier, TelemetryContext, TelemetryLogLevel } from './OpenTelemetry/types';
5
+ import { exceptionToSpan, logToSpan, OTelNull } from './OpenTelemetry';
6
+ import { OpenTelemetryHeaders, TelemetryLogLevel } from './OpenTelemetry/types';
7
7
  import { validateURI, cleanString } from './utils';
8
8
  import ArvoContract from './ArvoContract';
9
9
  import { createArvoContract, InferArvoContract } from './ArvoContract/helpers';
@@ -80,4 +80,4 @@ declare const ArvoEventSchemas: {
80
80
  tracestate: string | null;
81
81
  }>;
82
82
  };
83
- export { ArvoEvent, createArvoEvent, ArvoDataContentType, ArvoEventData, CloudEventExtension, ArvoEventSchemas, CloudEventContext, ArvoExtension, OpenTelemetryExtension, CreateArvoEvent, exceptionToSpan, logToSpan, getTelemetryCarrier, getTelemetryContext, createOtelSpan, TelemetryCarrier, TelemetryContext, TelemetryLogLevel, OTelNull, validateURI, cleanString, ArvoContract, createArvoContract, ArvoContractValidators, ArvoContractRecord, InferArvoContract, IArvoContract, ResolveArvoContractRecord, ArvoContractLibrary, createArvoContractLibrary, ArvoEventFactory, createArvoEventFactory, ArvoErrorSchema };
83
+ export { ArvoEvent, createArvoEvent, ArvoDataContentType, ArvoEventData, CloudEventExtension, ArvoEventSchemas, CloudEventContext, ArvoExtension, OpenTelemetryExtension, CreateArvoEvent, exceptionToSpan, logToSpan, OpenTelemetryHeaders, TelemetryLogLevel, OTelNull, validateURI, cleanString, ArvoContract, createArvoContract, ArvoContractValidators, ArvoContractRecord, InferArvoContract, IArvoContract, ResolveArvoContractRecord, ArvoContractLibrary, createArvoContractLibrary, ArvoEventFactory, createArvoEventFactory, ArvoErrorSchema, };
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ArvoErrorSchema = exports.createArvoEventFactory = exports.ArvoEventFactory = exports.createArvoContractLibrary = exports.ArvoContractLibrary = exports.ArvoContractValidators = exports.createArvoContract = exports.ArvoContract = exports.cleanString = exports.validateURI = exports.OTelNull = exports.createOtelSpan = exports.getTelemetryContext = exports.getTelemetryCarrier = exports.logToSpan = exports.exceptionToSpan = exports.ArvoEventSchemas = exports.ArvoDataContentType = exports.createArvoEvent = exports.ArvoEvent = void 0;
6
+ exports.ArvoErrorSchema = exports.createArvoEventFactory = exports.ArvoEventFactory = exports.createArvoContractLibrary = exports.ArvoContractLibrary = exports.ArvoContractValidators = exports.createArvoContract = exports.ArvoContract = exports.cleanString = exports.validateURI = exports.OTelNull = exports.logToSpan = exports.exceptionToSpan = exports.ArvoEventSchemas = exports.ArvoDataContentType = exports.createArvoEvent = exports.ArvoEvent = void 0;
7
7
  var ArvoEvent_1 = __importDefault(require("./ArvoEvent"));
8
8
  exports.ArvoEvent = ArvoEvent_1.default;
9
9
  var schema_1 = require("./ArvoEvent/schema");
@@ -13,9 +13,6 @@ Object.defineProperty(exports, "createArvoEvent", { enumerable: true, get: funct
13
13
  var OpenTelemetry_1 = require("./OpenTelemetry");
14
14
  Object.defineProperty(exports, "exceptionToSpan", { enumerable: true, get: function () { return OpenTelemetry_1.exceptionToSpan; } });
15
15
  Object.defineProperty(exports, "logToSpan", { enumerable: true, get: function () { return OpenTelemetry_1.logToSpan; } });
16
- Object.defineProperty(exports, "getTelemetryContext", { enumerable: true, get: function () { return OpenTelemetry_1.getTelemetryContext; } });
17
- Object.defineProperty(exports, "getTelemetryCarrier", { enumerable: true, get: function () { return OpenTelemetry_1.getTelemetryCarrier; } });
18
- Object.defineProperty(exports, "createOtelSpan", { enumerable: true, get: function () { return OpenTelemetry_1.createOtelSpan; } });
19
16
  Object.defineProperty(exports, "OTelNull", { enumerable: true, get: function () { return OpenTelemetry_1.OTelNull; } });
20
17
  var utils_1 = require("./utils");
21
18
  Object.defineProperty(exports, "validateURI", { enumerable: true, get: function () { return utils_1.validateURI; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arvo-core",
3
- "version": "1.0.21",
3
+ "version": "1.0.23",
4
4
  "description": "This core package contains all the core classes and components of the Arvo Event Driven System",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {