@dxos/tracing 0.8.3 → 0.8.4-main.f9ba587

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.
@@ -1,1111 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var node_exports = {};
20
- __export(node_exports, {
21
- BaseCounter: () => BaseCounter,
22
- CustomCounter: () => CustomCounter,
23
- DIAGNOSTICS_TIMEOUT: () => DIAGNOSTICS_TIMEOUT,
24
- DiagnosticsChannel: () => DiagnosticsChannel,
25
- DiagnosticsManager: () => DiagnosticsManager,
26
- MapCounter: () => MapCounter,
27
- RemoteMetrics: () => RemoteMetrics,
28
- RemoteTracing: () => RemoteTracing,
29
- ResourceEntry: () => ResourceEntry,
30
- TRACE_PROCESSOR: () => TRACE_PROCESSOR,
31
- TRACE_SPAN_ATTRIBUTE: () => TRACE_SPAN_ATTRIBUTE,
32
- TimeSeriesCounter: () => TimeSeriesCounter,
33
- TimeUsageCounter: () => TimeUsageCounter,
34
- TraceDiagnosticImpl: () => TraceDiagnosticImpl,
35
- TraceProcessor: () => TraceProcessor,
36
- TraceSender: () => TraceSender,
37
- TracingSpan: () => TracingSpan,
38
- UnaryCounter: () => UnaryCounter,
39
- getTracingContext: () => getTracingContext,
40
- sanitizeClassName: () => sanitizeClassName,
41
- symbolTracingContext: () => symbolTracingContext,
42
- trace: () => trace
43
- });
44
- module.exports = __toCommonJS(node_exports);
45
- var import_context = require("@dxos/context");
46
- var import_async = require("@dxos/async");
47
- var import_log = require("@dxos/log");
48
- var import_util = require("@dxos/util");
49
- var import_async2 = require("@dxos/async");
50
- var import_invariant = require("@dxos/invariant");
51
- var import_async3 = require("@dxos/async");
52
- var import_context2 = require("@dxos/context");
53
- var import_invariant2 = require("@dxos/invariant");
54
- var import_stream = require("@dxos/codec-protobuf/stream");
55
- var symbolTracingContext = Symbol("dxos.tracing.context");
56
- var getTracingContext = (target) => {
57
- return target[symbolTracingContext] ??= {
58
- infoProperties: {},
59
- metricsProperties: {}
60
- };
61
- };
62
- var TRACE_SPAN_ATTRIBUTE = "dxos.trace-span";
63
- var createId = () => Math.random().toString(36).slice(2);
64
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/tracing/src/diagnostic.ts";
65
- var DIAGNOSTICS_TIMEOUT = 1e4;
66
- var TraceDiagnosticImpl = class {
67
- constructor(id, fetch, name, _onUnregister) {
68
- this.id = id;
69
- this.fetch = fetch;
70
- this.name = name;
71
- this._onUnregister = _onUnregister;
72
- }
73
- unregister() {
74
- this._onUnregister();
75
- }
76
- };
77
- var DiagnosticsManager = class {
78
- constructor() {
79
- this.instanceId = createId();
80
- this.registry = /* @__PURE__ */ new Map();
81
- this._instanceTag = null;
82
- }
83
- get instanceTag() {
84
- return this._instanceTag;
85
- }
86
- setInstanceTag(tag) {
87
- this._instanceTag = tag;
88
- }
89
- registerDiagnostic(params) {
90
- const impl = new TraceDiagnosticImpl(params.id, params.fetch, params.name ?? params.id, () => {
91
- if (this.registry.get(params.id) === impl) {
92
- this.registry.delete(params.id);
93
- }
94
- });
95
- this.registry.set(params.id, impl);
96
- return impl;
97
- }
98
- list() {
99
- return Array.from(this.registry.values()).map((diagnostic2) => ({
100
- id: diagnostic2.id,
101
- instanceId: this.instanceId,
102
- instanceTag: this._instanceTag,
103
- name: diagnostic2.name
104
- }));
105
- }
106
- async fetch(request) {
107
- if (request.instanceId != null) {
108
- (0, import_invariant.invariant)(request.instanceId === this.instanceId, "Invalid instance id", {
109
- F: __dxlog_file,
110
- L: 82,
111
- S: this,
112
- A: [
113
- "request.instanceId === this.instanceId",
114
- "'Invalid instance id'"
115
- ]
116
- });
117
- }
118
- const { id } = request;
119
- const diagnostic2 = this.registry.get(id);
120
- (0, import_invariant.invariant)(diagnostic2, "Diagnostic not found", {
121
- F: __dxlog_file,
122
- L: 86,
123
- S: this,
124
- A: [
125
- "diagnostic",
126
- "'Diagnostic not found'"
127
- ]
128
- });
129
- try {
130
- const data = await (0, import_async2.asyncTimeout)(diagnostic2.fetch(), DIAGNOSTICS_TIMEOUT);
131
- return {
132
- id,
133
- instanceId: this.instanceId,
134
- data
135
- };
136
- } catch (err) {
137
- return {
138
- id,
139
- instanceId: this.instanceId,
140
- data: null,
141
- error: err.stack
142
- };
143
- }
144
- }
145
- };
146
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/common/tracing/src/diagnostics-channel.ts";
147
- var DEFAULT_CHANNEL_NAME = "dxos-diagnostics";
148
- var DISCOVER_TIME = 500;
149
- var DiagnosticsChannel = class _DiagnosticsChannel {
150
- static get supported() {
151
- return globalThis.BroadcastChannel != null;
152
- }
153
- constructor(_channelName = DEFAULT_CHANNEL_NAME) {
154
- this._channelName = _channelName;
155
- this._ctx = new import_context2.Context(void 0, {
156
- F: __dxlog_file2,
157
- L: 46
158
- });
159
- this._serveChannel = void 0;
160
- this._clientChannel = void 0;
161
- if (_DiagnosticsChannel.supported) {
162
- this._serveChannel = new BroadcastChannel(_channelName);
163
- this._clientChannel = new BroadcastChannel(_channelName);
164
- }
165
- }
166
- destroy() {
167
- void this._ctx.dispose();
168
- this._serveChannel?.close();
169
- this._clientChannel?.close();
170
- }
171
- /**
172
- * In node.js, the channel will keep the process alive.
173
- * This method allows the process to exit.
174
- * Noop in the browser.
175
- */
176
- unref() {
177
- if (this._serveChannel && typeof this._serveChannel.unref === "function") {
178
- this._serveChannel.unref();
179
- this._clientChannel.unref();
180
- }
181
- }
182
- serve(manager) {
183
- (0, import_invariant2.invariant)(this._serveChannel, void 0, {
184
- F: __dxlog_file2,
185
- L: 78,
186
- S: this,
187
- A: [
188
- "this._serveChannel",
189
- ""
190
- ]
191
- });
192
- const listener = async (event) => {
193
- switch (event.data.type) {
194
- case "DIAGNOSTICS_DISCOVER": {
195
- const diagnostics = manager.list();
196
- this._serveChannel.postMessage({
197
- type: "DIAGNOSTICS_ANNOUNCE",
198
- diagnostics
199
- });
200
- break;
201
- }
202
- case "DIAGNOSTICS_FETCH": {
203
- const { requestId, request } = event.data;
204
- if (request.instanceId != null && request.instanceId !== manager.instanceId) {
205
- break;
206
- } else if (request.instanceTag != null && request.instanceTag !== manager.instanceTag) {
207
- break;
208
- }
209
- const data = await manager.fetch(request);
210
- this._serveChannel.postMessage({
211
- type: "DIAGNOSTICS_RESPONSE",
212
- requestId,
213
- data
214
- });
215
- break;
216
- }
217
- }
218
- };
219
- this._serveChannel.addEventListener("message", listener);
220
- this._ctx.onDispose(() => this._serveChannel.removeEventListener("message", listener));
221
- }
222
- async discover() {
223
- (0, import_invariant2.invariant)(this._clientChannel, void 0, {
224
- F: __dxlog_file2,
225
- L: 114,
226
- S: this,
227
- A: [
228
- "this._clientChannel",
229
- ""
230
- ]
231
- });
232
- const diagnostics = [];
233
- const collector = (event) => {
234
- const data = event.data;
235
- switch (data.type) {
236
- case "DIAGNOSTICS_ANNOUNCE":
237
- diagnostics.push(...data.diagnostics);
238
- break;
239
- }
240
- };
241
- try {
242
- this._clientChannel.addEventListener("message", collector);
243
- this._clientChannel.postMessage({
244
- type: "DIAGNOSTICS_DISCOVER"
245
- });
246
- await (0, import_async3.sleep)(DISCOVER_TIME);
247
- const result = [];
248
- for (const diagnostic2 of diagnostics) {
249
- if (!result.some((d) => d.id === diagnostic2.id && d.instanceId === diagnostic2.instanceId)) {
250
- result.push(diagnostic2);
251
- }
252
- }
253
- return diagnostics;
254
- } finally {
255
- this._clientChannel.removeEventListener("message", collector);
256
- }
257
- }
258
- async fetch(request) {
259
- (0, import_invariant2.invariant)(this._clientChannel, void 0, {
260
- F: __dxlog_file2,
261
- L: 147,
262
- S: this,
263
- A: [
264
- "this._clientChannel",
265
- ""
266
- ]
267
- });
268
- const requestId = createId();
269
- const trigger = new import_async3.Trigger();
270
- const listener = (event) => {
271
- const data = event.data;
272
- if (data.type === "DIAGNOSTICS_RESPONSE" && data.requestId === requestId) {
273
- trigger.wake(data.data);
274
- }
275
- };
276
- try {
277
- this._clientChannel.addEventListener("message", listener);
278
- this._clientChannel.postMessage({
279
- type: "DIAGNOSTICS_FETCH",
280
- requestId,
281
- request
282
- });
283
- const result = await trigger.wait({
284
- timeout: DIAGNOSTICS_TIMEOUT
285
- });
286
- return result;
287
- } finally {
288
- this._clientChannel.removeEventListener("message", listener);
289
- }
290
- }
291
- };
292
- var RemoteMetrics = class {
293
- constructor() {
294
- this._metrics = /* @__PURE__ */ new Set();
295
- }
296
- registerProcessor(processor) {
297
- this._metrics.add(processor);
298
- }
299
- increment(name, value, data) {
300
- return Array.from(this._metrics.values()).map((processor) => processor.increment(name, value, data));
301
- }
302
- distribution(name, value, data) {
303
- return Array.from(this._metrics.values()).map((processor) => processor.distribution(name, value, data));
304
- }
305
- set(name, value, data) {
306
- return Array.from(this._metrics.values()).map((processor) => processor.set(name, value, data));
307
- }
308
- gauge(name, value, data) {
309
- return Array.from(this._metrics.values()).map((processor) => processor.gauge(name, value, data));
310
- }
311
- };
312
- var RemoteTracing = class {
313
- constructor() {
314
- this._spanMap = /* @__PURE__ */ new Map();
315
- }
316
- registerProcessor(processor) {
317
- this._tracing = processor;
318
- }
319
- flushSpan(span2) {
320
- if (!this._tracing) {
321
- return;
322
- }
323
- if (!span2.endTs) {
324
- const remoteSpan = this._tracing.startSpan({
325
- name: span2.methodName,
326
- op: span2.op ?? "function",
327
- attributes: span2.attributes
328
- });
329
- this._spanMap.set(span2, remoteSpan);
330
- } else {
331
- const remoteSpan = this._spanMap.get(span2);
332
- if (remoteSpan) {
333
- remoteSpan.end();
334
- this._spanMap.delete(span2);
335
- }
336
- }
337
- }
338
- };
339
- var TraceSender = class {
340
- constructor(_traceProcessor) {
341
- this._traceProcessor = _traceProcessor;
342
- }
343
- streamTrace(request) {
344
- return new import_stream.Stream(({ ctx, next }) => {
345
- const flushEvents = (resources, spans2, logs) => {
346
- const event = {
347
- resourceAdded: [],
348
- resourceRemoved: [],
349
- spanAdded: [],
350
- logAdded: []
351
- };
352
- if (resources) {
353
- for (const id of resources) {
354
- const entry = this._traceProcessor.resources.get(id);
355
- if (entry) {
356
- event.resourceAdded.push({
357
- resource: entry.data
358
- });
359
- } else {
360
- event.resourceRemoved.push({
361
- id
362
- });
363
- }
364
- }
365
- } else {
366
- for (const entry of this._traceProcessor.resources.values()) {
367
- event.resourceAdded.push({
368
- resource: entry.data
369
- });
370
- }
371
- }
372
- if (spans2) {
373
- for (const id of spans2) {
374
- const span2 = this._traceProcessor.spans.get(id);
375
- if (span2) {
376
- event.spanAdded.push({
377
- span: span2
378
- });
379
- }
380
- }
381
- } else {
382
- for (const span2 of this._traceProcessor.spans.values()) {
383
- event.spanAdded.push({
384
- span: span2
385
- });
386
- }
387
- }
388
- if (logs) {
389
- for (const log2 of logs) {
390
- event.logAdded.push({
391
- log: log2
392
- });
393
- }
394
- } else {
395
- for (const log2 of this._traceProcessor.logs) {
396
- event.logAdded.push({
397
- log: log2
398
- });
399
- }
400
- }
401
- if (event.resourceAdded.length > 0 || event.resourceRemoved.length > 0 || event.spanAdded.length > 0) {
402
- next(event);
403
- }
404
- };
405
- const flush = () => {
406
- flushEvents(subscription.dirtyResources, subscription.dirtySpans, subscription.newLogs);
407
- subscription.dirtyResources.clear();
408
- subscription.dirtySpans.clear();
409
- subscription.newLogs.length = 0;
410
- };
411
- const subscription = {
412
- flush,
413
- dirtyResources: /* @__PURE__ */ new Set(),
414
- dirtySpans: /* @__PURE__ */ new Set(),
415
- newLogs: []
416
- };
417
- this._traceProcessor.subscriptions.add(subscription);
418
- ctx.onDispose(() => {
419
- this._traceProcessor.subscriptions.delete(subscription);
420
- });
421
- flushEvents(null, null, null);
422
- });
423
- }
424
- };
425
- var WeakRefMock = class {
426
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
427
- constructor(target) {
428
- }
429
- deref() {
430
- return void 0;
431
- }
432
- };
433
- var WeakRef = globalThis.WeakRef ?? WeakRefMock;
434
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/common/tracing/src/trace-processor.ts";
435
- var ResourceEntry = class {
436
- constructor(data, instance, annotation) {
437
- this.data = data;
438
- this.instance = instance;
439
- this.annotation = annotation;
440
- this.sanitizedClassName = sanitizeClassName(data.className);
441
- }
442
- getMetric(name) {
443
- return this.data.metrics?.find((metric) => metric.name === name);
444
- }
445
- };
446
- var MAX_RESOURCE_RECORDS = 2e3;
447
- var MAX_SPAN_RECORDS = 1e3;
448
- var MAX_LOG_RECORDS = 1e3;
449
- var REFRESH_INTERVAL = 1e3;
450
- var MAX_INFO_OBJECT_DEPTH = 8;
451
- var IS_CLOUDFLARE_WORKERS = !!globalThis?.navigator?.userAgent?.includes("Cloudflare-Workers");
452
- var TraceProcessor = class {
453
- constructor() {
454
- this.diagnostics = new DiagnosticsManager();
455
- this.diagnosticsChannel = new DiagnosticsChannel();
456
- this.remoteMetrics = new RemoteMetrics();
457
- this.remoteTracing = new RemoteTracing();
458
- this.subscriptions = /* @__PURE__ */ new Set();
459
- this.resources = /* @__PURE__ */ new Map();
460
- this.resourceInstanceIndex = /* @__PURE__ */ new WeakMap();
461
- this.resourceIdList = [];
462
- this.spans = /* @__PURE__ */ new Map();
463
- this.spanIdList = [];
464
- this.logs = [];
465
- this._instanceTag = null;
466
- this._logProcessor = (config, entry) => {
467
- switch (entry.level) {
468
- case import_log.LogLevel.ERROR:
469
- case import_log.LogLevel.WARN:
470
- case import_log.LogLevel.TRACE: {
471
- const scope = entry.meta?.S;
472
- const resource2 = this.resourceInstanceIndex.get(scope);
473
- if (!resource2) {
474
- return;
475
- }
476
- const context = (0, import_log.getContextFromEntry)(entry) ?? {};
477
- for (const key of Object.keys(context)) {
478
- context[key] = sanitizeValue(context[key], 0, this);
479
- }
480
- const entryToPush = {
481
- level: entry.level,
482
- message: entry.message,
483
- context,
484
- timestamp: /* @__PURE__ */ new Date(),
485
- meta: {
486
- file: entry.meta?.F ?? "",
487
- line: entry.meta?.L ?? 0,
488
- resourceId: resource2.data.id
489
- }
490
- };
491
- this._pushLog(entryToPush);
492
- break;
493
- }
494
- default:
495
- }
496
- };
497
- import_log.log.addProcessor(this._logProcessor.bind(this), void 0, {
498
- F: __dxlog_file3,
499
- L: 103,
500
- S: this,
501
- C: (f, a) => f(...a)
502
- });
503
- if (!IS_CLOUDFLARE_WORKERS) {
504
- const refreshInterval = setInterval(this.refresh.bind(this), REFRESH_INTERVAL);
505
- (0, import_async.unrefTimeout)(refreshInterval);
506
- }
507
- if (DiagnosticsChannel.supported) {
508
- this.diagnosticsChannel.serve(this.diagnostics);
509
- }
510
- this.diagnosticsChannel.unref();
511
- }
512
- setInstanceTag(tag) {
513
- this._instanceTag = tag;
514
- this.diagnostics.setInstanceTag(tag);
515
- }
516
- /**
517
- * @internal
518
- */
519
- // TODO(burdon): Comment.
520
- createTraceResource(params) {
521
- const id = this.resources.size;
522
- const tracingContext = getTracingContext(Object.getPrototypeOf(params.instance));
523
- for (const key of Object.keys(tracingContext.metricsProperties)) {
524
- params.instance[key]._assign(params.instance, key);
525
- }
526
- const entry = new ResourceEntry({
527
- id,
528
- className: params.constructor.name,
529
- instanceId: (0, import_util.getPrototypeSpecificInstanceId)(params.instance),
530
- info: this.getResourceInfo(params.instance),
531
- links: [],
532
- metrics: this.getResourceMetrics(params.instance)
533
- }, new WeakRef(params.instance), params.annotation);
534
- this.resources.set(id, entry);
535
- this.resourceInstanceIndex.set(params.instance, entry);
536
- this.resourceIdList.push(id);
537
- if (this.resourceIdList.length > MAX_RESOURCE_RECORDS) {
538
- this._clearResources();
539
- }
540
- this._markResourceDirty(id);
541
- }
542
- createTraceSender() {
543
- return new TraceSender(this);
544
- }
545
- traceSpan(params) {
546
- const span2 = new TracingSpan(this, params);
547
- this._flushSpan(span2);
548
- return span2;
549
- }
550
- // TODO(burdon): Not implemented.
551
- addLink(parent, child, opts) {
552
- }
553
- //
554
- // Getters
555
- //
556
- // TODO(burdon): Define type.
557
- // TODO(burdon): Reconcile with system service.
558
- getDiagnostics() {
559
- this.refresh();
560
- return {
561
- resources: Object.fromEntries(Array.from(this.resources.entries()).map(([id, entry]) => [
562
- `${entry.sanitizedClassName}#${entry.data.instanceId}`,
563
- entry.data
564
- ])),
565
- spans: Array.from(this.spans.values()),
566
- logs: this.logs.filter((log2) => log2.level >= import_log.LogLevel.INFO)
567
- };
568
- }
569
- getResourceInfo(instance) {
570
- const res = {};
571
- const tracingContext = getTracingContext(Object.getPrototypeOf(instance));
572
- for (const [key, { options }] of Object.entries(tracingContext.infoProperties)) {
573
- try {
574
- const value = typeof instance[key] === "function" ? instance[key]() : instance[key];
575
- if (options.enum) {
576
- res[key] = options.enum[value];
577
- } else {
578
- res[key] = sanitizeValue(value, options.depth === void 0 ? 1 : options.depth ?? MAX_INFO_OBJECT_DEPTH, this);
579
- }
580
- } catch (err) {
581
- res[key] = err.message;
582
- }
583
- }
584
- return res;
585
- }
586
- getResourceMetrics(instance) {
587
- const res = [];
588
- const tracingContext = getTracingContext(Object.getPrototypeOf(instance));
589
- for (const [key, _opts] of Object.entries(tracingContext.metricsProperties)) {
590
- res.push(instance[key].getData());
591
- }
592
- return res;
593
- }
594
- getResourceId(instance) {
595
- const entry = this.resourceInstanceIndex.get(instance);
596
- return entry ? entry.data.id : null;
597
- }
598
- findResourcesByClassName(className) {
599
- return [
600
- ...this.resources.values()
601
- ].filter((res) => res.data.className === className || res.sanitizedClassName === className);
602
- }
603
- findResourcesByAnnotation(annotation) {
604
- return [
605
- ...this.resources.values()
606
- ].filter((res) => res.annotation === annotation);
607
- }
608
- refresh() {
609
- for (const resource2 of this.resources.values()) {
610
- const instance = resource2.instance.deref();
611
- if (!instance) {
612
- continue;
613
- }
614
- const tracingContext = getTracingContext(Object.getPrototypeOf(instance));
615
- const time = performance.now();
616
- instance.tick?.(time);
617
- for (const key of Object.keys(tracingContext.metricsProperties)) {
618
- instance[key]._tick?.(time);
619
- }
620
- let _changed = false;
621
- const oldInfo = resource2.data.info;
622
- resource2.data.info = this.getResourceInfo(instance);
623
- _changed ||= !areEqualShallow(oldInfo, resource2.data.info);
624
- const oldMetrics = resource2.data.metrics;
625
- resource2.data.metrics = this.getResourceMetrics(instance);
626
- _changed ||= !areEqualShallow(oldMetrics, resource2.data.metrics);
627
- this._markResourceDirty(resource2.data.id);
628
- }
629
- for (const subscription of this.subscriptions) {
630
- subscription.flush();
631
- }
632
- }
633
- //
634
- // Implementation
635
- //
636
- /**
637
- * @internal
638
- */
639
- _flushSpan(runtimeSpan) {
640
- const span2 = runtimeSpan.serialize();
641
- this.spans.set(span2.id, span2);
642
- this.spanIdList.push(span2.id);
643
- if (this.spanIdList.length > MAX_SPAN_RECORDS) {
644
- this._clearSpans();
645
- }
646
- this._markSpanDirty(span2.id);
647
- this.remoteTracing.flushSpan(runtimeSpan);
648
- }
649
- _markResourceDirty(id) {
650
- for (const subscription of this.subscriptions) {
651
- subscription.dirtyResources.add(id);
652
- }
653
- }
654
- _markSpanDirty(id) {
655
- for (const subscription of this.subscriptions) {
656
- subscription.dirtySpans.add(id);
657
- }
658
- }
659
- _clearResources() {
660
- while (this.resourceIdList.length > MAX_RESOURCE_RECORDS) {
661
- const id = this.resourceIdList.shift();
662
- this.resources.delete(id);
663
- }
664
- }
665
- _clearSpans() {
666
- while (this.spanIdList.length > MAX_SPAN_RECORDS) {
667
- const id = this.spanIdList.shift();
668
- this.spans.delete(id);
669
- }
670
- }
671
- _pushLog(log2) {
672
- this.logs.push(log2);
673
- if (this.logs.length > MAX_LOG_RECORDS) {
674
- this.logs.shift();
675
- }
676
- for (const subscription of this.subscriptions) {
677
- subscription.newLogs.push(log2);
678
- }
679
- }
680
- };
681
- var TracingSpan = class _TracingSpan {
682
- static {
683
- this.nextId = 0;
684
- }
685
- constructor(_traceProcessor, params) {
686
- this._traceProcessor = _traceProcessor;
687
- this.parentId = null;
688
- this.resourceId = null;
689
- this.endTs = null;
690
- this.error = null;
691
- this._ctx = null;
692
- this.id = _TracingSpan.nextId++;
693
- this.methodName = params.methodName;
694
- this.resourceId = _traceProcessor.getResourceId(params.instance);
695
- this.startTs = performance.now();
696
- this._showInBrowserTimeline = params.showInBrowserTimeline;
697
- this.op = params.op;
698
- this.attributes = params.attributes ?? {};
699
- if (params.parentCtx) {
700
- this._ctx = params.parentCtx.derive({
701
- attributes: {
702
- [TRACE_SPAN_ATTRIBUTE]: this.id
703
- }
704
- });
705
- const parentId = params.parentCtx.getAttribute(TRACE_SPAN_ATTRIBUTE);
706
- if (typeof parentId === "number") {
707
- this.parentId = parentId;
708
- }
709
- }
710
- }
711
- get name() {
712
- const resource2 = this._traceProcessor.resources.get(this.resourceId);
713
- return resource2 ? `${resource2.sanitizedClassName}#${resource2.data.instanceId}.${this.methodName}` : this.methodName;
714
- }
715
- get ctx() {
716
- return this._ctx;
717
- }
718
- markSuccess() {
719
- this.endTs = performance.now();
720
- this._traceProcessor._flushSpan(this);
721
- if (this._showInBrowserTimeline) {
722
- this._markInBrowserTimeline();
723
- }
724
- }
725
- markError(err) {
726
- this.endTs = performance.now();
727
- this.error = serializeError(err);
728
- this._traceProcessor._flushSpan(this);
729
- if (this._showInBrowserTimeline) {
730
- this._markInBrowserTimeline();
731
- }
732
- }
733
- serialize() {
734
- return {
735
- id: this.id,
736
- resourceId: this.resourceId ?? void 0,
737
- methodName: this.methodName,
738
- parentId: this.parentId ?? void 0,
739
- startTs: this.startTs.toFixed(3),
740
- endTs: this.endTs?.toFixed(3) ?? void 0,
741
- error: this.error ?? void 0
742
- };
743
- }
744
- _markInBrowserTimeline() {
745
- if (typeof globalThis?.performance?.measure === "function") {
746
- performance.measure(this.name, {
747
- start: this.startTs,
748
- end: this.endTs
749
- });
750
- }
751
- }
752
- };
753
- var serializeError = (err) => {
754
- if (err instanceof Error) {
755
- return {
756
- name: err.name,
757
- message: err.message
758
- };
759
- }
760
- return {
761
- message: String(err)
762
- };
763
- };
764
- var TRACE_PROCESSOR = globalThis.TRACE_PROCESSOR ??= new TraceProcessor();
765
- var sanitizeValue = (value, depth, traceProcessor) => {
766
- switch (typeof value) {
767
- case "string":
768
- case "number":
769
- case "boolean":
770
- case "undefined":
771
- return value;
772
- case "object":
773
- case "function":
774
- if (value === null) {
775
- return value;
776
- }
777
- {
778
- const resourceEntry = traceProcessor.resourceInstanceIndex.get(value);
779
- if (resourceEntry) {
780
- return `${resourceEntry.sanitizedClassName}#${resourceEntry.data.instanceId}`;
781
- }
782
- }
783
- if (typeof value.toJSON === "function") {
784
- return sanitizeValue(value.toJSON(), depth, traceProcessor);
785
- }
786
- if (depth > 0) {
787
- if (isSetLike(value)) {
788
- return Object.fromEntries(Array.from(value.entries()).map((value2) => sanitizeValue(value2, depth - 1, traceProcessor)));
789
- } else if (isMapLike(value)) {
790
- return Object.fromEntries(Array.from(value.entries()).map(([key, value2]) => [
791
- key,
792
- sanitizeValue(value2, depth - 1, traceProcessor)
793
- ]));
794
- } else if (Array.isArray(value)) {
795
- return value.map((item) => sanitizeValue(item, depth - 1, traceProcessor));
796
- } else if (typeof value === "object") {
797
- const res = {};
798
- for (const key of Object.keys(value)) {
799
- res[key] = sanitizeValue(value[key], depth - 1, traceProcessor);
800
- }
801
- return res;
802
- }
803
- }
804
- if (typeof value.truncate === "function") {
805
- return value.truncate();
806
- }
807
- return value.toString();
808
- }
809
- };
810
- var areEqualShallow = (a, b) => {
811
- for (const key in a) {
812
- if (!(key in b) || a[key] !== b[key]) {
813
- return false;
814
- }
815
- }
816
- for (const key in b) {
817
- if (!(key in a) || a[key] !== b[key]) {
818
- return false;
819
- }
820
- }
821
- return true;
822
- };
823
- var sanitizeClassName = (className) => {
824
- const SANITIZE_REGEX = /[^_](\d+)$/;
825
- const m = className.match(SANITIZE_REGEX);
826
- if (!m) {
827
- return className;
828
- } else {
829
- return className.slice(0, -m[1].length);
830
- }
831
- };
832
- var isSetLike = (value) => value instanceof Set || typeof value === "object" && value !== null && Object.getPrototypeOf(value).constructor.name === "ComplexSet";
833
- var isMapLike = (value) => value instanceof Map || typeof value === "object" && value !== null && Object.getPrototypeOf(value).constructor.name === "ComplexMap";
834
- var resource = (options) => (constructor) => {
835
- const klass = /* @__PURE__ */ (() => class extends constructor {
836
- constructor(...rest) {
837
- super(...rest);
838
- TRACE_PROCESSOR.createTraceResource({
839
- constructor,
840
- annotation: options?.annotation,
841
- instance: this
842
- });
843
- }
844
- })();
845
- Object.defineProperty(klass, "name", {
846
- value: constructor.name
847
- });
848
- return klass;
849
- };
850
- var info = (opts = {}) => (target, propertyKey, descriptor) => {
851
- getTracingContext(target).infoProperties[propertyKey] = {
852
- options: opts
853
- };
854
- };
855
- var mark = (name) => {
856
- performance.mark(name);
857
- };
858
- var span = ({ showInBrowserTimeline = false, op, attributes } = {}) => (target, propertyKey, descriptor) => {
859
- const method = descriptor.value;
860
- descriptor.value = async function(...args) {
861
- const parentCtx = args[0] instanceof import_context.Context ? args[0] : null;
862
- const span2 = TRACE_PROCESSOR.traceSpan({
863
- parentCtx,
864
- methodName: propertyKey,
865
- instance: this,
866
- showInBrowserTimeline,
867
- op,
868
- attributes
869
- });
870
- const callArgs = span2.ctx ? [
871
- span2.ctx,
872
- ...args.slice(1)
873
- ] : args;
874
- try {
875
- return await method.apply(this, callArgs);
876
- } catch (err) {
877
- span2.markError(err);
878
- throw err;
879
- } finally {
880
- span2.markSuccess();
881
- }
882
- };
883
- };
884
- var spans = /* @__PURE__ */ new Map();
885
- var spanStart = (params) => {
886
- if (spans.has(params.id)) {
887
- return;
888
- }
889
- const span2 = TRACE_PROCESSOR.traceSpan(params);
890
- spans.set(params.id, span2);
891
- };
892
- var spanEnd = (id) => {
893
- const span2 = spans.get(id);
894
- if (span2) {
895
- span2.markSuccess();
896
- spans.delete(id);
897
- }
898
- };
899
- var metricsCounter = () => (target, propertyKey, descriptor) => {
900
- getTracingContext(target).metricsProperties[propertyKey] = {};
901
- };
902
- var addLink = (parent, child, opts = {}) => {
903
- TRACE_PROCESSOR.addLink(parent, child, opts);
904
- };
905
- var diagnostic = (params) => {
906
- return TRACE_PROCESSOR.diagnostics.registerDiagnostic(params);
907
- };
908
- var trace = {
909
- addLink,
910
- diagnostic,
911
- info,
912
- mark,
913
- metricsCounter,
914
- resource,
915
- span,
916
- spanStart,
917
- spanEnd,
918
- metrics: TRACE_PROCESSOR.remoteMetrics
919
- };
920
- var BaseCounter = class {
921
- /**
922
- * @internal
923
- */
924
- _assign(instance, name) {
925
- this._instance = instance;
926
- this.name = name;
927
- }
928
- _tick(time) {
929
- }
930
- };
931
- var UnaryCounter = class extends BaseCounter {
932
- constructor({ units } = {}) {
933
- super();
934
- this.value = 0;
935
- this.units = units;
936
- }
937
- inc(by = 1) {
938
- this.value += by;
939
- }
940
- getData() {
941
- return {
942
- name: this.name,
943
- counter: {
944
- value: this.value,
945
- units: this.units
946
- }
947
- };
948
- }
949
- };
950
- var MAX_BUCKETS = 60;
951
- var TimeSeriesCounter = class extends BaseCounter {
952
- constructor({ units } = {}) {
953
- super();
954
- this._currentValue = 0;
955
- this._totalValue = 0;
956
- this._buckets = [];
957
- this.units = units;
958
- }
959
- inc(by = 1) {
960
- this._currentValue += by;
961
- this._totalValue += by;
962
- }
963
- _tick(time) {
964
- this._buckets.push(this._currentValue);
965
- if (this._buckets.length > MAX_BUCKETS) {
966
- this._buckets.shift();
967
- }
968
- this._currentValue = 0;
969
- }
970
- getData() {
971
- return {
972
- name: this.name,
973
- timeSeries: {
974
- tracks: [
975
- {
976
- name: this.name,
977
- units: this.units,
978
- points: this._buckets.map((value, index) => ({
979
- value
980
- })),
981
- total: this._totalValue
982
- }
983
- ]
984
- }
985
- };
986
- }
987
- };
988
- var MAX_BUCKETS2 = 60;
989
- var TimeUsageCounter = class extends BaseCounter {
990
- constructor() {
991
- super(...arguments);
992
- this._currentValue = 0;
993
- this._totalValue = 0;
994
- this._buckets = [];
995
- this._lastTickTime = performance.now();
996
- }
997
- record(time) {
998
- this._currentValue += time;
999
- this._totalValue += time;
1000
- }
1001
- beginRecording() {
1002
- const start = performance.now();
1003
- return {
1004
- end: () => {
1005
- const end = performance.now();
1006
- this.record(end - start);
1007
- }
1008
- };
1009
- }
1010
- _tick(time) {
1011
- const delta = time - this._lastTickTime;
1012
- this._lastTickTime = time;
1013
- const percentage = this._currentValue / delta * 100;
1014
- this._buckets.push(percentage);
1015
- if (this._buckets.length > MAX_BUCKETS2) {
1016
- this._buckets.shift();
1017
- }
1018
- this._currentValue = 0;
1019
- }
1020
- getData() {
1021
- return {
1022
- name: this.name,
1023
- timeSeries: {
1024
- tracks: [
1025
- {
1026
- name: this.name,
1027
- units: "%",
1028
- points: this._buckets.map((value, index) => ({
1029
- value
1030
- })),
1031
- total: this._totalValue
1032
- }
1033
- ]
1034
- }
1035
- };
1036
- }
1037
- };
1038
- var MapCounter = class extends BaseCounter {
1039
- constructor({ units } = {}) {
1040
- super();
1041
- this.values = /* @__PURE__ */ new Map();
1042
- this.units = units;
1043
- }
1044
- inc(key, by = 1) {
1045
- const prev = this.values.get(key) ?? 0;
1046
- this.values.set(key, prev + by);
1047
- }
1048
- getData() {
1049
- return {
1050
- name: this.name,
1051
- multiCounter: {
1052
- records: Array.from(this.values.entries()).map(([key, value]) => ({
1053
- key,
1054
- value
1055
- })),
1056
- units: this.units
1057
- }
1058
- };
1059
- }
1060
- };
1061
- var CustomCounter = class extends BaseCounter {
1062
- constructor(_getData) {
1063
- super(), this._getData = _getData;
1064
- }
1065
- getData() {
1066
- return {
1067
- name: this.name,
1068
- custom: {
1069
- payload: this._getData()
1070
- }
1071
- };
1072
- }
1073
- };
1074
- trace.diagnostic({
1075
- id: "process-info",
1076
- name: "Process Info",
1077
- fetch: async () => {
1078
- return {
1079
- platform: globalThis.process?.platform,
1080
- arch: globalThis.process?.arch,
1081
- versions: globalThis.process?.versions,
1082
- href: globalThis.location?.href
1083
- };
1084
- }
1085
- });
1086
- // Annotate the CommonJS export names for ESM import in node:
1087
- 0 && (module.exports = {
1088
- BaseCounter,
1089
- CustomCounter,
1090
- DIAGNOSTICS_TIMEOUT,
1091
- DiagnosticsChannel,
1092
- DiagnosticsManager,
1093
- MapCounter,
1094
- RemoteMetrics,
1095
- RemoteTracing,
1096
- ResourceEntry,
1097
- TRACE_PROCESSOR,
1098
- TRACE_SPAN_ATTRIBUTE,
1099
- TimeSeriesCounter,
1100
- TimeUsageCounter,
1101
- TraceDiagnosticImpl,
1102
- TraceProcessor,
1103
- TraceSender,
1104
- TracingSpan,
1105
- UnaryCounter,
1106
- getTracingContext,
1107
- sanitizeClassName,
1108
- symbolTracingContext,
1109
- trace
1110
- });
1111
- //# sourceMappingURL=index.cjs.map