@dxos/observability 0.4.7-next.f4b92be → 0.4.8-main.00e6f19

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.
Files changed (58) hide show
  1. package/dist/lib/browser/{chunk-6KUJPLEH.mjs → chunk-G5DKURIM.mjs} +38 -16
  2. package/dist/lib/browser/chunk-G5DKURIM.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-XF67HMEA.mjs → chunk-Y66LFYI5.mjs} +161 -36
  4. package/dist/lib/browser/chunk-Y66LFYI5.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +2 -1
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/browser/observability-A5P77DUJ.mjs +8 -0
  8. package/dist/lib/browser/segment/index.mjs +1 -1
  9. package/dist/lib/browser/sentry/index.mjs +7 -5
  10. package/dist/lib/node/{chunk-T2S7C5J2.cjs → chunk-3OQ7O6O7.cjs} +157 -39
  11. package/dist/lib/node/chunk-3OQ7O6O7.cjs.map +7 -0
  12. package/dist/lib/node/{chunk-FSAOBKO2.cjs → chunk-VYXPK6C2.cjs} +38 -51
  13. package/dist/lib/node/chunk-VYXPK6C2.cjs.map +7 -0
  14. package/dist/lib/node/datadog/index.cjs +1 -1
  15. package/dist/lib/node/datadog/index.cjs.map +2 -2
  16. package/dist/lib/node/index.cjs +16 -15
  17. package/dist/lib/node/index.cjs.map +2 -2
  18. package/dist/lib/node/meta.json +1 -1
  19. package/dist/lib/node/{observability-M64E2QBA.cjs → observability-T3HIK77L.cjs} +7 -6
  20. package/dist/lib/node/observability-T3HIK77L.cjs.map +7 -0
  21. package/dist/lib/node/segment/index.cjs +2 -2
  22. package/dist/lib/node/sentry/index.cjs +13 -13
  23. package/dist/lib/node/sentry/index.cjs.map +1 -1
  24. package/dist/types/src/datadog/metrics.js +1 -1
  25. package/dist/types/src/datadog/metrics.js.map +1 -1
  26. package/dist/types/src/helpers/node-observability.d.ts.map +1 -1
  27. package/dist/types/src/helpers/node-observability.js +0 -1
  28. package/dist/types/src/helpers/node-observability.js.map +1 -1
  29. package/dist/types/src/observability.d.ts +1 -2
  30. package/dist/types/src/observability.d.ts.map +1 -1
  31. package/dist/types/src/observability.js +21 -20
  32. package/dist/types/src/observability.js.map +1 -1
  33. package/dist/types/src/sentry/browser.d.ts +3 -2
  34. package/dist/types/src/sentry/browser.d.ts.map +1 -1
  35. package/dist/types/src/sentry/browser.js +15 -5
  36. package/dist/types/src/sentry/browser.js.map +1 -1
  37. package/dist/types/src/sentry/node.d.ts +3 -4
  38. package/dist/types/src/sentry/node.d.ts.map +1 -1
  39. package/dist/types/src/sentry/node.js +11 -43
  40. package/dist/types/src/sentry/node.js.map +1 -1
  41. package/dist/types/src/sentry/sentry-log-processor.d.ts +9 -0
  42. package/dist/types/src/sentry/sentry-log-processor.d.ts.map +1 -0
  43. package/dist/types/src/sentry/sentry-log-processor.js +133 -0
  44. package/dist/types/src/sentry/sentry-log-processor.js.map +1 -0
  45. package/package.json +14 -14
  46. package/src/datadog/metrics.ts +1 -1
  47. package/src/helpers/node-observability.ts +0 -1
  48. package/src/observability.ts +23 -21
  49. package/src/sentry/browser.ts +17 -4
  50. package/src/sentry/node.ts +11 -48
  51. package/src/sentry/sentry-log-processor.ts +144 -0
  52. package/dist/lib/browser/chunk-6KUJPLEH.mjs.map +0 -7
  53. package/dist/lib/browser/chunk-XF67HMEA.mjs.map +0 -7
  54. package/dist/lib/browser/observability-MK4LFDOW.mjs +0 -7
  55. package/dist/lib/node/chunk-FSAOBKO2.cjs.map +0 -7
  56. package/dist/lib/node/chunk-T2S7C5J2.cjs.map +0 -7
  57. package/dist/lib/node/observability-M64E2QBA.cjs.map +0 -7
  58. /package/dist/lib/browser/{observability-MK4LFDOW.mjs.map → observability-A5P77DUJ.mjs.map} +0 -0
@@ -17,10 +17,10 @@ import { type DatadogMetrics } from './datadog';
17
17
  import { type IPData, getTelemetryIdentifier, mapSpaces } from './helpers';
18
18
  import { type SegmentTelemetry, type EventOptions, type PageOptions } from './segment';
19
19
  import { type InitOptions, type captureException as SentryCaptureException } from './sentry';
20
+ import { SentryLogProcessor } from './sentry/sentry-log-processor';
20
21
 
21
22
  const SPACE_METRICS_MIN_INTERVAL = 1000 * 60;
22
- // const DATADOG_IDLE_INTERVAL = 1000 * 60 * 5;
23
- const DATADOG_IDLE_INTERVAL = 1000 * 60 * 1;
23
+ const NETWORK_METRICS_MIN_INTERVAL = 1000 * 60 * 5;
24
24
 
25
25
  // Secrets? EnvironmentConfig?
26
26
 
@@ -55,7 +55,6 @@ export type ObservabilityOptions = {
55
55
 
56
56
  errorLog?: {
57
57
  sentryInitOptions?: InitOptions;
58
- logProcessor?: boolean;
59
58
  };
60
59
  };
61
60
 
@@ -71,7 +70,6 @@ export class Observability {
71
70
  private _telemetry?: SegmentTelemetry;
72
71
  // TODO(wittjosiah): Generic error logging interface.
73
72
  private _errorReportingOptions?: InitOptions;
74
- private _errorLogProcessor: boolean;
75
73
  private _captureException?: typeof SentryCaptureException;
76
74
  private _setTag?: (key: string, value: string) => void;
77
75
 
@@ -83,6 +81,7 @@ export class Observability {
83
81
  // TODO(nf): accept upstream context?
84
82
  private _ctx = new Context();
85
83
  private _tags = new Map<string, { value: string; scope: TagScope }>();
84
+ private _lastNetworkStatus?: NetworkStatus;
86
85
 
87
86
  // TODO(nf): make platform a required extension?
88
87
  constructor({
@@ -103,7 +102,6 @@ export class Observability {
103
102
  this._secrets = this._loadSecrets(config, secrets);
104
103
  this._telemetryBatchSize = telemetry?.batchSize ?? 30;
105
104
  this._errorReportingOptions = errorLog?.sentryInitOptions;
106
- this._errorLogProcessor = errorLog?.logProcessor ?? false;
107
105
 
108
106
  if (this._group) {
109
107
  this.setTag('group', this._group);
@@ -246,7 +244,7 @@ export class Observability {
246
244
  })
247
245
  .map(([key, value]) => [key, value.value]),
248
246
  ),
249
- // TODO(nf): move/refactor from telementryContext, needed to read CORS proxy
247
+ // TODO(nf): move/refactor from telemetryContext, needed to read CORS proxy
250
248
  config: this._config!,
251
249
  });
252
250
  } else {
@@ -266,12 +264,11 @@ export class Observability {
266
264
  // TODO(nf): Refactor into ObservabilityExtensions.
267
265
 
268
266
  startNetworkMetrics(client: Client) {
269
- const updateSignalMetrics = new Event<NetworkStatus>();
270
-
271
- // const lcsh = (csp as LocalClientServices).host;
272
- updateSignalMetrics.on(this._ctx, async (networkStatus) => {
267
+ // TODO(nf): support type in debounce()
268
+ const updateSignalMetrics = new Event<NetworkStatus>().debounce(NETWORK_METRICS_MIN_INTERVAL);
269
+ updateSignalMetrics.on(this._ctx, async () => {
273
270
  log('send signal metrics');
274
- (networkStatus.signaling as NetworkStatus.Signal[]).forEach(({ server, state }) => {
271
+ (this._lastNetworkStatus?.signaling as NetworkStatus.Signal[]).forEach(({ server, state }) => {
275
272
  this.gauge('dxos.client.network.signal.connectionState', state, { server });
276
273
  });
277
274
 
@@ -285,7 +282,7 @@ export class Observability {
285
282
  let totalWriteBufferSize = 0;
286
283
  let totalChannelBufferSize = 0;
287
284
 
288
- networkStatus.connectionInfo?.forEach((connectionInfo) => {
285
+ this._lastNetworkStatus?.connectionInfo?.forEach((connectionInfo) => {
289
286
  swarmCount++;
290
287
 
291
288
  for (const conn of connectionInfo.connections ?? []) {
@@ -302,20 +299,22 @@ export class Observability {
302
299
  for (const state in ConnectionState) {
303
300
  this.gauge('dxos.client.network.connection.count', connectionStates.get(state) ?? 0, { state });
304
301
  }
305
- this.gauge('dxox.client.network.totalReadBufferSize', totalReadBufferSize);
302
+ this.gauge('dxos.client.network.totalReadBufferSize', totalReadBufferSize);
306
303
  this.gauge('dxos.client.network.totalWriteBufferSize', totalWriteBufferSize);
307
304
  this.gauge('dxos.client.network.totalChannelBufferSize', totalChannelBufferSize);
308
305
  });
309
306
  });
310
307
 
311
308
  client.services.services.NetworkService?.queryStatus().subscribe((networkStatus) => {
312
- updateSignalMetrics.emit(networkStatus);
309
+ this._lastNetworkStatus = networkStatus;
310
+ updateSignalMetrics.emit();
313
311
  });
314
312
 
315
- // scheduleTaskInterval(ctx, async () => updateSignalMetrics.emit(), DATADOG_IDLE_INTERVAL);
313
+ scheduleTaskInterval(this._ctx, async () => updateSignalMetrics.emit(), NETWORK_METRICS_MIN_INTERVAL);
316
314
  }
317
315
 
318
316
  startSpacesMetrics(client: Client, namespace: string) {
317
+ // TODO(nf): update subscription on new spaces
319
318
  const spaces = client.spaces.get();
320
319
  const subscriptions = new Map<string, { unsubscribe: () => void }>();
321
320
  this._ctx.onDispose(() => subscriptions.forEach((subscription) => subscription.unsubscribe()));
@@ -360,10 +359,10 @@ export class Observability {
360
359
  },
361
360
  });
362
361
 
363
- scheduleTaskInterval(this._ctx, async () => updateSpaceMetrics.emit(), DATADOG_IDLE_INTERVAL);
362
+ scheduleTaskInterval(this._ctx, async () => updateSpaceMetrics.emit(), NETWORK_METRICS_MIN_INTERVAL);
364
363
  }
365
364
 
366
- async startRuntimeMetrics(client: Client, frequency: number = DATADOG_IDLE_INTERVAL) {
365
+ async startRuntimeMetrics(client: Client, frequency: number = NETWORK_METRICS_MIN_INTERVAL) {
367
366
  const platform = await client.services.services.SystemService?.getPlatform();
368
367
  invariant(platform, 'platform is required');
369
368
 
@@ -447,7 +446,7 @@ export class Observability {
447
446
 
448
447
  private async _initErrorLogs() {
449
448
  if (this._secrets.SENTRY_DESTINATION && this._mode !== 'disabled') {
450
- const { captureException, enableSentryLogProcessor, configureTracing, init, setTag } = await import('./sentry');
449
+ const { captureException, configureTracing, init, setTag } = await import('./sentry');
451
450
  this._captureException = captureException;
452
451
  this._setTag = setTag;
453
452
 
@@ -456,18 +455,21 @@ export class Observability {
456
455
  dest: this._secrets.SENTRY_DESTINATION,
457
456
  options: this._errorReportingOptions,
458
457
  });
458
+
459
+ const logProcessor = new SentryLogProcessor();
459
460
  init({
460
461
  ...this._errorReportingOptions,
461
462
  destination: this._secrets.SENTRY_DESTINATION,
462
463
  scrubFilenames: this._mode !== 'full',
464
+ onError: (event) => logProcessor.addLogBreadcrumbsTo(event),
463
465
  });
464
466
  if (this._errorReportingOptions?.tracing) {
465
467
  configureTracing();
466
468
  }
469
+
467
470
  // TODO(nf): set platform at instantiation? needed for node.
468
- if (this._errorLogProcessor) {
469
- enableSentryLogProcessor();
470
- }
471
+ log.runtimeConfig.processors.push(logProcessor.logProcessor);
472
+
471
473
  // TODO(nf): is this different than passing as properties in options?
472
474
  this._tags.forEach((v, k) => {
473
475
  if (v.scope === 'all' || v.scope === 'errors') {
@@ -7,10 +7,13 @@ import {
7
7
  setTag,
8
8
  addBreadcrumb as naturalAddBreadcrumb,
9
9
  captureException as naturalCaptureException,
10
+ captureMessage as naturalCaptureMessage,
11
+ withScope as naturalWithScope,
10
12
  BrowserTracing,
11
13
  replayIntegration,
14
+ breadcrumbsIntegration,
12
15
  } from '@sentry/browser';
13
- import { captureConsoleIntegration, httpClientIntegration } from '@sentry/integrations';
16
+ import { httpClientIntegration } from '@sentry/integrations';
14
17
 
15
18
  import { log } from '@dxos/log';
16
19
 
@@ -37,7 +40,7 @@ export const init = (options: InitOptions) => {
37
40
  release: options.release,
38
41
  environment: options.environment,
39
42
  integrations: [
40
- captureConsoleIntegration({ levels: ['error', 'warn'] }),
43
+ breadcrumbsIntegration({ console: false, fetch: false }),
41
44
  httpClientIntegration({ failedRequestStatusCodes: [[400, 599]] }),
42
45
  ...(options.tracing ? [new BrowserTracing()] : []),
43
46
  ...(options.replay ? [replayIntegration({ blockAllMedia: true, maskAllText: true })] : []),
@@ -96,5 +99,15 @@ export const captureException: typeof naturalCaptureException = (exception, capt
96
99
  }
97
100
  };
98
101
 
99
- // Not needed for browser.
100
- export const enableSentryLogProcessor = () => {};
102
+ export const captureMessage: typeof naturalCaptureMessage = (exception, captureContext) => {
103
+ try {
104
+ const eventId = naturalCaptureMessage(exception, captureContext);
105
+ log('capture message', { exception, eventId, captureContext });
106
+ return eventId;
107
+ } catch (err) {
108
+ log.catch('Failed to capture message', err);
109
+ return 'unknown';
110
+ }
111
+ };
112
+
113
+ export const withScope = naturalWithScope;
@@ -9,12 +9,11 @@ import {
9
9
  addBreadcrumb as naturalAddBreadcrumb,
10
10
  captureException as naturalCaptureException,
11
11
  captureMessage as naturalCaptureMessage,
12
- withScope,
12
+ withScope as naturalWithScope,
13
13
  } from '@sentry/node';
14
14
  import type { Event } from '@sentry/node';
15
- import type { SeverityLevel } from '@sentry/types';
16
15
 
17
- import { log, LogLevel, shouldLog } from '@dxos/log';
16
+ import { log } from '@dxos/log';
18
17
 
19
18
  import { type InitOptions } from './types';
20
19
 
@@ -103,51 +102,15 @@ export const captureException: typeof naturalCaptureException = (exception, capt
103
102
  }
104
103
  };
105
104
 
106
- // TODO(nf): move to log package as a first-class processor.
107
- export const enableSentryLogProcessor = (filter?: string | string[] | LogLevel) => {
108
- log.runtimeConfig.processors.push(SENTRY_LOG_PROCESSOR);
109
- };
110
-
111
- export const SENTRY_LOG_PROCESSOR = (config: any, entry: any) => {
112
- const { message, level, meta, error } = entry;
113
- if (!shouldLog(entry, config.captureFilters)) {
114
- return;
115
- }
116
- // TODO(nf): add rate limiting to avoid spamming Sentry/consuming excessive quota.
117
- withScope((scope) => {
118
- scope.setLevel(convertLevel(level));
119
- scope.setContext('dxoslog', entry.context);
120
- if (meta) {
121
- scope.setTransactionName(`${getRelativeFilename(meta.F)}:${meta.L}`);
122
- }
123
- // Is this ever used?
124
- if (error) {
125
- scope.setExtra('message', message);
126
- return naturalCaptureException(error);
127
- }
128
-
129
- naturalCaptureMessage(message);
130
- });
131
- };
132
-
133
- const convertLevel = (level: LogLevel): SeverityLevel => {
134
- if (level === LogLevel.TRACE) {
135
- return 'debug';
136
- }
137
- if (level === LogLevel.WARN) {
138
- return 'warning';
105
+ export const captureMessage: typeof naturalCaptureMessage = (exception, captureContext) => {
106
+ try {
107
+ const eventId = naturalCaptureMessage(exception, captureContext);
108
+ log('capture message', { exception, eventId, captureContext });
109
+ return eventId;
110
+ } catch (err) {
111
+ log.catch('Failed to capture message', err);
112
+ return 'unknown';
139
113
  }
140
- return LogLevel[level].toLowerCase() as SeverityLevel;
141
114
  };
142
115
 
143
- const getRelativeFilename = (filename: string) => {
144
- // TODO(burdon): Hack uses "packages" as an anchor (pre-parse NX?)
145
- // Including `packages/` part of the path so that excluded paths (e.g. from dist) are clickable in vscode.
146
- const match = filename.match(/.+\/(packages\/.+\/.+)/);
147
- if (match) {
148
- const [, filePath] = match;
149
- return filePath;
150
- }
151
-
152
- return filename;
153
- };
116
+ export const withScope = naturalWithScope;
@@ -0,0 +1,144 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import type { Breadcrumb, SeverityLevel, Event } from '@sentry/types';
6
+
7
+ import { type LogConfig, type LogEntry, LogLevel, type LogProcessor, shouldLog } from '@dxos/log';
8
+ import { CircularBuffer, getDebugName } from '@dxos/util';
9
+
10
+ import { withScope, captureException, captureMessage } from './';
11
+
12
+ const MAX_LOG_BREADCRUMBS = 80;
13
+
14
+ export class SentryLogProcessor {
15
+ private _breadcrumbs = new CircularBuffer<Breadcrumb>(MAX_LOG_BREADCRUMBS);
16
+
17
+ public readonly logProcessor: LogProcessor = (config: LogConfig, entry: LogEntry) => {
18
+ const { level, meta, error } = entry;
19
+ if (!shouldLog(entry, config.captureFilters)) {
20
+ return;
21
+ }
22
+ if (entry.level !== LogLevel.WARN && entry.level !== LogLevel.ERROR) {
23
+ return;
24
+ }
25
+ // TODO(nf): add rate limiting to avoid spamming Sentry/consuming excessive quota.
26
+ withScope((scope) => {
27
+ const severity = convertLevel(level);
28
+ scope.setLevel(severity);
29
+ scope.setContext('dxoslog', entry.context ?? null);
30
+ if (meta) {
31
+ scope.setTag('transaction', `${getRelativeFilename(meta.F)}:${meta.L}`);
32
+
33
+ if (meta.S?.hostSessionId) {
34
+ scope.setTags({
35
+ service_host_issue: true,
36
+ service_host_session: meta.S?.hostSessionId,
37
+ });
38
+ }
39
+
40
+ if (!Number.isNaN(meta.S?.uptimeSeconds)) {
41
+ scope.setExtra('uptime_seconds', meta.S?.uptimeSeconds);
42
+ }
43
+ }
44
+
45
+ const extendedMessage = formatMessageForSentry(entry);
46
+ let capturedError = error;
47
+ if (capturedError == null && entry.level === LogLevel.ERROR) {
48
+ capturedError = Object.values(entry.context ?? {}).find((v): v is Error => v instanceof Error);
49
+ }
50
+ if (capturedError) {
51
+ const isMessageDifferentFromStackTrace = error == null;
52
+ if (isMessageDifferentFromStackTrace) {
53
+ scope.setExtra('message', extendedMessage);
54
+ }
55
+ const eventId = captureException(capturedError);
56
+ this._addBreadcrumb(eventId, extendedMessage, severity, entry.context);
57
+ return;
58
+ }
59
+
60
+ scope.setFingerprint([entry.message]);
61
+ const eventId = captureMessage(extendedMessage);
62
+ this._addBreadcrumb(eventId, extendedMessage, severity, entry.context);
63
+ });
64
+ };
65
+
66
+ public addLogBreadcrumbsTo(event: Event) {
67
+ event.breadcrumbs ??= [];
68
+ for (const breadcrumb of this._breadcrumbs) {
69
+ event.breadcrumbs.push(breadcrumb);
70
+ }
71
+ event.breadcrumbs.sort((b1, b2) => {
72
+ if (b1.timestamp === undefined || b2.timestamp === undefined) {
73
+ return b1.timestamp === b2.timestamp ? 0 : b1.timestamp === undefined ? -1 : 1;
74
+ }
75
+ return b1.timestamp - b2.timestamp;
76
+ });
77
+ }
78
+
79
+ private _addBreadcrumb(
80
+ eventId: string,
81
+ message: string,
82
+ severity: SeverityLevel,
83
+ context: { [key: string]: any } | undefined,
84
+ ): void {
85
+ const breadcrumb: Breadcrumb = {
86
+ type: 'console',
87
+ level: severity,
88
+ event_id: eventId,
89
+ category: 'log',
90
+ message,
91
+ data: context,
92
+ timestamp: Math.floor(Date.now() / 1000),
93
+ };
94
+ const lastRecorded = this._breadcrumbs.getLast();
95
+ if (lastRecorded && lastRecorded.message === breadcrumb.message) {
96
+ const firstBreadcrumbData = lastRecorded.data?.firstBreadcrumbData ?? lastRecorded.data ?? {};
97
+ const mergedBreadcrumbCount = Number.isNaN(lastRecorded.data?.mergedBreadcrumbCount)
98
+ ? 1
99
+ : Number(lastRecorded.data?.mergedBreadcrumbCount);
100
+ lastRecorded.data = {
101
+ mergedBreadcrumbCount: mergedBreadcrumbCount + 1,
102
+ firstBreadcrumbData,
103
+ lastBreadcrumbData: breadcrumb.data,
104
+ };
105
+ return;
106
+ }
107
+ this._breadcrumbs.push(breadcrumb);
108
+ }
109
+ }
110
+
111
+ const formatMessageForSentry = (entry: LogEntry) => {
112
+ let scopePrefix: string | undefined;
113
+ if (entry.meta?.S) {
114
+ const scope = entry.meta?.S;
115
+ scopePrefix = scope.name || getDebugName(scope);
116
+ }
117
+ if (scopePrefix == null) {
118
+ return entry.message;
119
+ }
120
+ const workerPrefix = entry.meta?.S?.hostSessionId ? '[worker] ' : '';
121
+ return `${workerPrefix}${scopePrefix} ${entry.message}`;
122
+ };
123
+
124
+ const convertLevel = (level: LogLevel): SeverityLevel => {
125
+ if (level === LogLevel.TRACE) {
126
+ return 'debug';
127
+ }
128
+ if (level === LogLevel.WARN) {
129
+ return 'warning';
130
+ }
131
+ return LogLevel[level].toLowerCase() as SeverityLevel;
132
+ };
133
+
134
+ const getRelativeFilename = (filename: string) => {
135
+ // TODO(burdon): Hack uses "packages" as an anchor (pre-parse NX?)
136
+ // Including `packages/` part of the path so that excluded paths (e.g. from dist) are clickable in vscode.
137
+ const match = filename.match(/.+\/(packages\/.+\/.+)/);
138
+ if (match) {
139
+ const [, filePath] = match;
140
+ return filePath;
141
+ }
142
+
143
+ return filename;
144
+ };
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/sentry/browser.ts", "../../../src/sentry/tracing.ts"],
4
- "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport {\n init as naturalInit,\n setTag,\n addBreadcrumb as naturalAddBreadcrumb,\n captureException as naturalCaptureException,\n BrowserTracing,\n replayIntegration,\n} from '@sentry/browser';\nimport { captureConsoleIntegration, httpClientIntegration } from '@sentry/integrations';\n\nimport { log } from '@dxos/log';\n\nimport { type InitOptions } from './types';\n\n// Browser only feature.\nexport * from './tracing';\n\n// Polyfill export.\nexport { setTag, setTags, setUser } from '@sentry/browser';\n\n/**\n * To use this SDK, call the init function as early as possible when loading the web page.\n * To set context information or send manual events, use the provided methods.\n *\n * @param options {InitOptions}\n */\nexport const init = (options: InitOptions) => {\n try {\n log('sentry init', options);\n naturalInit({\n enabled: options.enable ?? true,\n dsn: options.destination,\n release: options.release,\n environment: options.environment,\n integrations: [\n captureConsoleIntegration({ levels: ['error', 'warn'] }),\n httpClientIntegration({ failedRequestStatusCodes: [[400, 599]] }),\n ...(options.tracing ? [new BrowserTracing()] : []),\n ...(options.replay ? [replayIntegration({ blockAllMedia: true, maskAllText: true })] : []),\n ],\n replaysSessionSampleRate: options.replaySampleRate,\n replaysOnErrorSampleRate: options.replaySampleRateOnError,\n tracesSampleRate: options.sampleRate,\n transport: options.transport,\n beforeSend: (event) => {\n options.onError?.(event);\n return event;\n },\n });\n\n Object.entries(options.properties ?? {}).forEach(([key, value]) => {\n setTag(key, value);\n });\n } catch (err) {\n log.catch('Failed to initialize sentry', err);\n }\n};\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on user's actions prior to an error or crash.\n *\n * https://docs.sentry.io/platforms/javascript/enriching-events/breadcrumbs/\n *\n * @param breadcrumb — The breadcrumb to record.\n */\nexport const addBreadcrumb: typeof naturalAddBreadcrumb = (breadcrumb) => {\n try {\n naturalAddBreadcrumb(breadcrumb);\n log('add breadcrumb', breadcrumb);\n } catch (err) {\n log.catch('Failed to add breadcrumb', err);\n }\n};\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception — An exception-like object.\n * @param captureContext — Additional scope data to apply to exception event.\n * @returns — The generated eventId.\n */\nexport const captureException: typeof naturalCaptureException = (exception, captureContext) => {\n try {\n const eventId = naturalCaptureException(exception, captureContext);\n log('capture exception', { exception, eventId, ...captureContext });\n return eventId;\n } catch (err) {\n log.catch('Failed to capture exception', err);\n return 'unknown';\n }\n};\n\n// Not needed for browser.\nexport const enableSentryLogProcessor = () => {};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// NOTE: Browser only API. There is no node polyfill.\n\nimport { getCurrentHub } from '@sentry/browser';\nimport { type Transaction, type Span } from '@sentry/types';\n\nimport { runInContext, scheduleMicroTask, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { getContextFromEntry, log, LogLevel, type LogProcessor } from '@dxos/log';\n\nconst REPORT_SPANS = false;\n\nlet TX!: Transaction;\nconst SPAN_MAP = new Map<string, Span>();\nconst SENTRY_INITIALIZED = new Trigger();\nconst ctx = new Context({ onError: (err) => log.warn('Unhandled error in Sentry context', err) });\nctx.maxSafeDisposeCallbacks = 10_000;\n\nlet tracingConfigured = false;\n\nexport const configureTracing = () => {\n tracingConfigured = true;\n runInContext(ctx, () => {\n // Configure root transaction.\n TX = getCurrentHub().startTransaction({\n name: 'DXOS Core Tracing',\n op: 'dxos',\n });\n invariant(TX, 'Failed to create trace');\n if (typeof window !== 'undefined') {\n window.addEventListener('beforeunload', () => {\n finish();\n });\n }\n if (typeof process !== 'undefined') {\n process.on('exit', () => {\n finish();\n });\n }\n\n SENTRY_INITIALIZED.wake();\n });\n};\n\nexport const finish = () => {\n for (const span of Array.from(SPAN_MAP.values()).reverse()) {\n try {\n span.finish();\n } catch (err) {\n log.warn('Failed to finish span', err);\n }\n }\n TX.finish();\n};\n\nexport const SENTRY_PROCESSOR: LogProcessor = (config, entry) => {\n if (!tracingConfigured) {\n return;\n }\n\n const { message, level, error } = entry;\n const context = getContextFromEntry(entry);\n\n if (level !== LogLevel.TRACE) {\n return;\n }\n\n // NOTE: Make sure `entry` is not captured in this closure to avoid a memory leak.\n scheduleMicroTask(ctx, async () => {\n await SENTRY_INITIALIZED.wait();\n\n if (REPORT_SPANS && context?.span) {\n switch (context.span.command) {\n case 'begin': {\n const id = context.span.id;\n\n if (!id || SPAN_MAP.has(id)) {\n log.warn('Cannot begin span', id);\n return;\n }\n\n let parentSpan: Span = TX;\n if (context.span.parent) {\n parentSpan = SPAN_MAP.get(context.span.parent) ?? TX;\n }\n\n let logContext: string;\n try {\n logContext = JSON.stringify({ ...context, message, level, error });\n } catch (err) {\n logContext = JSON.stringify(context);\n }\n\n const span = parentSpan.startChild({\n op: message,\n data: {\n ...context.span.data,\n '@dxos/log': logContext,\n },\n });\n SPAN_MAP.set(context.span.id, span);\n break;\n }\n\n case 'end': {\n const span = SPAN_MAP.get(context.span.id);\n if (span) {\n span.setStatus(getSpanStatus(context.span.status));\n context.span.data && Object.entries(context.span.data).forEach(([key, value]) => span.setData(key, value));\n span.finish();\n SPAN_MAP.delete(context.span.id);\n } else {\n log.warn('Cannot end span', context.span.id);\n }\n break;\n }\n\n case 'update': {\n const span = SPAN_MAP.get(context.span.id);\n if (span) {\n context.span.data && Object.entries(context.span.data).forEach(([key, value]) => span.setData(key, value));\n } else {\n log.warn('Cannot update span', context.span.id);\n }\n break;\n }\n\n default: {\n log.warn('Unknown span command', context.span.command);\n }\n }\n }\n });\n};\n\nlog.runtimeConfig.processors.push(SENTRY_PROCESSOR);\n\n/**\n * @see https://develop.sentry.dev/sdk/event-payloads/span/#:~:text=this%20value%20explicitly.-,status,-Optional.%20Describes%20the\n */\nconst getSpanStatus = (status?: 'ok' | 'error') => {\n switch (status) {\n case 'ok':\n return 'ok';\n case 'error':\n return 'not_found';\n }\n return status ?? 'ok';\n};\n"],
5
- "mappings": ";AAIA,SACEA,QAAQC,aACRC,QACAC,iBAAiBC,sBACjBC,oBAAoBC,yBACpBC,gBACAC,yBACK;AACP,SAASC,2BAA2BC,6BAA6B;AAEjE,SAASC,OAAAA,YAAW;;;ACRpB,SAASC,qBAAqB;AAG9B,SAASC,cAAcC,mBAAmBC,eAAe;AACzD,SAASC,eAAe;AACxB,SAASC,iBAAiB;AAC1B,SAASC,qBAAqBC,KAAKC,gBAAmC;;AAEtE,IAAMC,eAAe;AAErB,IAAIC;AAC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AAA,EAAGC,QAAQ,CAAC,CAACC,KAAKC,KAAAA,MAAM;AAC5DvC,aAAOsC,KAAKC,KAAAA;IACd,CAAA;EACF,SAASC,KAAK;AACZnC,IAAAA,KAAIoC,MAAM,+BAA+BD,KAAAA;;;;;;EAC3C;AACF;AAWO,IAAME,gBAA6C,CAACC,eAAAA;AACzD,MAAI;AACFC,yBAAqBD,UAAAA;AACrBtC,IAAAA,KAAI,kBAAkBsC,YAAAA;;;;;;EACxB,SAASH,KAAK;AACZnC,IAAAA,KAAIoC,MAAM,4BAA4BD,KAAAA;;;;;;EACxC;AACF;AASO,IAAMK,mBAAmD,CAACC,WAAWC,mBAAAA;AAC1E,MAAI;AACF,UAAMC,UAAUC,wBAAwBH,WAAWC,cAAAA;AACnD1C,IAAAA,KAAI,qBAAqB;MAAEyC;MAAWE;MAAS,GAAGD;IAAe,GAAA;;;;;;AACjE,WAAOC;EACT,SAASR,KAAK;AACZnC,IAAAA,KAAIoC,MAAM,+BAA+BD,KAAAA;;;;;;AACzC,WAAO;EACT;AACF;AAGO,IAAMU,2BAA2B,MAAA;AAAO;",
6
- "names": ["init", "naturalInit", "setTag", "addBreadcrumb", "naturalAddBreadcrumb", "captureException", "naturalCaptureException", "BrowserTracing", "replayIntegration", "captureConsoleIntegration", "httpClientIntegration", "log", "getCurrentHub", "runInContext", "scheduleMicroTask", "Trigger", "Context", "invariant", "getContextFromEntry", "log", "LogLevel", "REPORT_SPANS", "TX", "SPAN_MAP", "Map", "SENTRY_INITIALIZED", "ctx", "onError", "err", "warn", "maxSafeDisposeCallbacks", "tracingConfigured", "configureTracing", "startTransaction", "name", "op", "window", "addEventListener", "finish", "process", "on", "wake", "span", "Array", "from", "values", "reverse", "SENTRY_PROCESSOR", "config", "entry", "message", "level", "error", "context", "TRACE", "wait", "command", "id", "has", "parentSpan", "parent", "get", "logContext", "JSON", "stringify", "startChild", "data", "set", "setStatus", "getSpanStatus", "status", "Object", "entries", "forEach", "key", "value", "setData", "delete", "runtimeConfig", "processors", "push", "setTag", "setTags", "setUser", "init", "options", "log", "naturalInit", "enabled", "enable", "dsn", "destination", "release", "environment", "integrations", "captureConsoleIntegration", "levels", "httpClientIntegration", "failedRequestStatusCodes", "tracing", "BrowserTracing", "replay", "replayIntegration", "blockAllMedia", "maskAllText", "replaysSessionSampleRate", "replaySampleRate", "replaysOnErrorSampleRate", "replaySampleRateOnError", "tracesSampleRate", "sampleRate", "transport", "beforeSend", "event", "onError", "Object", "entries", "properties", "forEach", "key", "value", "err", "catch", "addBreadcrumb", "breadcrumb", "naturalAddBreadcrumb", "captureException", "exception", "captureContext", "eventId", "naturalCaptureException", "enableSentryLogProcessor"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/observability.ts", "../../../src/cli-observability-secrets.json", "../../../src/helpers/browser-observability.ts", "../../../src/helpers/common.ts", "../../../src/helpers/node-observability.ts", "../../../src/helpers/map-spaces.ts", "../../../src/helpers/setup-telemetry-listeners.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Event, scheduleTaskInterval } from '@dxos/async';\nimport { type Client, type Config } from '@dxos/client';\nimport { type Space } from '@dxos/client-protocol';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { ConnectionState } from '@dxos/network-manager';\nimport { DeviceKind, type NetworkStatus, Platform } from '@dxos/protocols/proto/dxos/client/services';\nimport { isNode } from '@dxos/util';\n\nimport buildSecrets from './cli-observability-secrets.json';\nimport { type DatadogMetrics } from './datadog';\nimport { type IPData, getTelemetryIdentifier, mapSpaces } from './helpers';\nimport { type SegmentTelemetry, type EventOptions, type PageOptions } from './segment';\nimport { type InitOptions, type captureException as SentryCaptureException } from './sentry';\n\nconst SPACE_METRICS_MIN_INTERVAL = 1000 * 60;\n// const DATADOG_IDLE_INTERVAL = 1000 * 60 * 5;\nconst DATADOG_IDLE_INTERVAL = 1000 * 60 * 1;\n\n// Secrets? EnvironmentConfig?\n\nexport type ObservabilitySecrets = {\n DX_ENVIRONMENT: string | null;\n DX_RELEASE: string | null;\n SENTRY_DESTINATION: string | null;\n TELEMETRY_API_KEY: string | null;\n IPDATA_API_KEY: string | null;\n DATADOG_API_KEY: string | null;\n DATADOG_APP_KEY: string | null;\n};\n\nexport type Mode = 'basic' | 'full' | 'disabled';\nexport type TagScope = 'errors' | 'telemetry' | 'metrics' | 'all';\n\nexport type ObservabilityOptions = {\n /// The webapp (e.g. 'composer.dxos.org'), 'cli', or 'agent'.\n namespace: string;\n mode: Mode;\n // TODO(nf): make platform a required extension?\n // platform: Platform;\n release?: string;\n environment?: string;\n config?: Config;\n secrets?: Record<string, string>;\n group?: string;\n\n telemetry?: {\n batchSize?: number;\n };\n\n errorLog?: {\n sentryInitOptions?: InitOptions;\n logProcessor?: boolean;\n };\n};\n\n/*\n * Observability provides a common interface for error logging, metrics, and telemetry.\n * It currently provides these capabilities using Sentry, Datadog, and Segment.\n */\nexport class Observability {\n // TODO(wittjosiah): Generic metrics interface.\n private _metrics?: DatadogMetrics;\n // TODO(wittjosiah): Generic telemetry interface.\n private _telemetryBatchSize: number;\n private _telemetry?: SegmentTelemetry;\n // TODO(wittjosiah): Generic error logging interface.\n private _errorReportingOptions?: InitOptions;\n private _errorLogProcessor: boolean;\n private _captureException?: typeof SentryCaptureException;\n private _setTag?: (key: string, value: string) => void;\n\n private _secrets: ObservabilitySecrets;\n private _namespace: string;\n private _mode: Mode;\n private _config?: Config;\n private _group?: string;\n // TODO(nf): accept upstream context?\n private _ctx = new Context();\n private _tags = new Map<string, { value: string; scope: TagScope }>();\n\n // TODO(nf): make platform a required extension?\n constructor({\n namespace,\n environment,\n release,\n config,\n secrets,\n group,\n mode,\n telemetry,\n errorLog,\n }: ObservabilityOptions) {\n this._namespace = namespace;\n this._mode = mode;\n this._config = config;\n this._group = group;\n this._secrets = this._loadSecrets(config, secrets);\n this._telemetryBatchSize = telemetry?.batchSize ?? 30;\n this._errorReportingOptions = errorLog?.sentryInitOptions;\n this._errorLogProcessor = errorLog?.logProcessor ?? false;\n\n if (this._group) {\n this.setTag('group', this._group);\n }\n this.setTag('namespace', this._namespace);\n environment && this.setTag('environment', environment);\n release && this.setTag('release', release);\n this.setTag('mode', this._mode);\n }\n\n private _loadSecrets(config: Config | undefined, secrets?: Record<string, string>) {\n if (isNode()) {\n const mergedSecrets = {\n ...(buildSecrets as ObservabilitySecrets),\n ...secrets,\n };\n\n process.env.DX_ENVIRONMENT && (mergedSecrets.DX_ENVIRONMENT = process.env.DX_ENVIRONMENT);\n process.env.DX_RELEASE && (mergedSecrets.DX_RELEASE = process.env.DX_RELEASE);\n process.env.SENTRY_DESTINATION && (mergedSecrets.SENTRY_DESTINATION = process.env.SENTRY_DESTINATION);\n process.env.TELEMETRY_API_KEY && (mergedSecrets.TELEMETRY_API_KEY = process.env.TELEMETRY_API_KEY);\n process.env.IPDATA_API_KEY && (mergedSecrets.IPDATA_API_KEY = process.env.IPDATA_API_KEY);\n process.env.DATADOG_API_KEY && (mergedSecrets.DATADOG_API_KEY = process.env.DATADOG_API_KEY);\n process.env.DATADOG_APP_KEY && (mergedSecrets.DATADOG_APP_KEY = process.env.DATADOG_APP_KEY);\n\n return mergedSecrets;\n } else {\n log('config', { rtc: this._secrets, config });\n return {\n DX_ENVIRONMENT: config?.get('runtime.app.env.DX_ENVIRONMENT'),\n DX_RELEASE: config?.get('runtime.app.env.DX_RELEASE'),\n SENTRY_DESTINATION: config?.get('runtime.app.env.DX_SENTRY_DESTINATION'),\n TELEMETRY_API_KEY: config?.get('runtime.app.env.DX_TELEMETRY_API_KEY'),\n IPDATA_API_KEY: config?.get('runtime.app.env.DX_IPDATA_API_KEY'),\n DATADOG_API_KEY: config?.get('runtime.app.env.DX_DATADOG_API_KEY'),\n DATADOG_APP_KEY: config?.get('runtime.app.env.DX_DATADOG_APP_KEY'),\n ...secrets,\n };\n }\n }\n\n async initialize() {\n await this._initMetrics();\n await this._initTelemetry();\n await this._initErrorLogs();\n }\n\n async close() {\n await this._ctx.dispose();\n\n // TODO(wittjosiah): Remove telemetry, etc. scripts.\n }\n\n setMode(mode: Mode) {\n this._mode = mode;\n }\n\n get mode() {\n return this._mode;\n }\n\n get group() {\n return this._group;\n }\n\n get enabled() {\n return this._mode !== 'disabled';\n }\n\n //\n // Tags\n //\n\n setTag(key: string, value: string, scope?: TagScope) {\n if (this.enabled && (scope === undefined || scope === 'all' || scope === 'errors')) {\n this._setTag?.(key, value);\n }\n if (!scope) {\n scope = 'all';\n }\n this._tags.set(key, { value, scope });\n }\n\n getTag(key: string) {\n return this._tags.get(key);\n }\n\n addIPDataTelemetryTags = (ipData: IPData) => {\n this.setTag('city', ipData.city, 'telemetry');\n this.setTag('region', ipData.region, 'telemetry');\n this.setTag('country', ipData.country, 'telemetry');\n ipData.latitude && this.setTag('latitude', ipData.latitude.toString(), 'telemetry');\n ipData.longitude && this.setTag('longitude', ipData.longitude.toString(), 'telemetry');\n };\n\n // TODO(wittjosiah): Improve privacy of telemetry identifiers. See `getTelemetryIdentifier`.\n async setIdentityTags(client: Client) {\n client.services.services.IdentityService!.queryIdentity().subscribe((idqr) => {\n if (!idqr?.identity?.identityKey) {\n log('empty response from identity service', { idqr });\n return;\n }\n\n this.setTag('identityKey', idqr.identity.identityKey.truncate());\n });\n\n client.services.services.DevicesService!.queryDevices().subscribe((dqr) => {\n if (!dqr || !dqr.devices || dqr.devices.length === 0) {\n log('empty response from device service', { device: dqr });\n return;\n }\n invariant(dqr, 'empty response from device service');\n\n const thisDevice = dqr.devices.find((device) => device.kind === DeviceKind.CURRENT);\n if (!thisDevice) {\n log('no current device', { device: dqr });\n return;\n }\n this.setTag('deviceKey', thisDevice.deviceKey.truncate());\n if (thisDevice.profile?.label) {\n this.setTag('deviceProfile', thisDevice.profile.label);\n }\n });\n }\n\n //\n // Metrics\n //\n\n private async _initMetrics() {\n if (this.enabled && this._secrets.DATADOG_API_KEY) {\n const { DatadogMetrics } = await import('./datadog');\n this._metrics = new DatadogMetrics({\n apiKey: this._secrets.DATADOG_API_KEY,\n getTags: () =>\n Object.fromEntries(\n Array.from(this._tags)\n .filter(([key, value]) => {\n return value.scope === 'all' || value.scope === 'metrics';\n })\n .map(([key, value]) => [key, value.value]),\n ),\n // TODO(nf): move/refactor from telementryContext, needed to read CORS proxy\n config: this._config!,\n });\n } else {\n log('datadog disabled');\n }\n }\n\n /**\n * Gauge metric.\n *\n * The default implementation uses Datadog.\n */\n gauge(name: string, value: number | any, extraTags?: any) {\n this._metrics?.gauge(name, value, extraTags);\n }\n\n // TODO(nf): Refactor into ObservabilityExtensions.\n\n startNetworkMetrics(client: Client) {\n const updateSignalMetrics = new Event<NetworkStatus>();\n\n // const lcsh = (csp as LocalClientServices).host;\n updateSignalMetrics.on(this._ctx, async (networkStatus) => {\n log('send signal metrics');\n (networkStatus.signaling as NetworkStatus.Signal[]).forEach(({ server, state }) => {\n this.gauge('dxos.client.network.signal.connectionState', state, { server });\n });\n\n let swarmCount = 0;\n const connectionStates = new Map<string, number>();\n for (const state in ConnectionState) {\n connectionStates.set(state, 0);\n }\n\n let totalReadBufferSize = 0;\n let totalWriteBufferSize = 0;\n let totalChannelBufferSize = 0;\n\n networkStatus.connectionInfo?.forEach((connectionInfo) => {\n swarmCount++;\n\n for (const conn of connectionInfo.connections ?? []) {\n connectionStates.set(conn.state, (connectionStates.get(conn.state) ?? 0) + 1);\n totalReadBufferSize += conn.readBufferSize ?? 0;\n totalWriteBufferSize += conn.writeBufferSize ?? 0;\n\n for (const stream of conn.streams ?? []) {\n totalChannelBufferSize += stream.writeBufferSize ?? 0;\n }\n }\n\n this.gauge('dxos.client.network.swarm.count', swarmCount);\n for (const state in ConnectionState) {\n this.gauge('dxos.client.network.connection.count', connectionStates.get(state) ?? 0, { state });\n }\n this.gauge('dxox.client.network.totalReadBufferSize', totalReadBufferSize);\n this.gauge('dxos.client.network.totalWriteBufferSize', totalWriteBufferSize);\n this.gauge('dxos.client.network.totalChannelBufferSize', totalChannelBufferSize);\n });\n });\n\n client.services.services.NetworkService?.queryStatus().subscribe((networkStatus) => {\n updateSignalMetrics.emit(networkStatus);\n });\n\n // scheduleTaskInterval(ctx, async () => updateSignalMetrics.emit(), DATADOG_IDLE_INTERVAL);\n }\n\n startSpacesMetrics(client: Client, namespace: string) {\n const spaces = client.spaces.get();\n const subscriptions = new Map<string, { unsubscribe: () => void }>();\n this._ctx.onDispose(() => subscriptions.forEach((subscription) => subscription.unsubscribe()));\n\n const updateSpaceMetrics = new Event<Space>().debounce(SPACE_METRICS_MIN_INTERVAL);\n updateSpaceMetrics.on(this._ctx, async () => {\n log('send space update');\n for (const data of mapSpaces(spaces, { truncateKeys: true })) {\n // Metrics\n this.gauge('dxos.client.space.members', data.members, { key: data.key });\n this.gauge('dxos.client.space.objects', data.objects, { key: data.key });\n this.gauge('dxos.client.space.epoch', data.epoch, { key: data.key });\n this.gauge('dxos.client.space.currentDataMutations', data.currentDataMutations, { key: data.key });\n\n // Telemetry\n this.event({\n identityId: getTelemetryIdentifier(client),\n name: `${namespace}.space.update`,\n properties: data,\n });\n }\n });\n\n const subscribeToSpaceUpdate = (space: Space) =>\n space.pipeline.subscribe({\n next: () => {\n updateSpaceMetrics.emit();\n },\n });\n\n spaces.forEach((space) => {\n subscriptions.set(space.key.toHex(), subscribeToSpaceUpdate(space));\n });\n\n client.spaces.subscribe({\n next: async (spaces) => {\n spaces\n .filter((space) => !subscriptions.has(space.key.toHex()))\n .forEach((space) => {\n subscriptions.set(space.key.toHex(), subscribeToSpaceUpdate(space));\n });\n },\n });\n\n scheduleTaskInterval(this._ctx, async () => updateSpaceMetrics.emit(), DATADOG_IDLE_INTERVAL);\n }\n\n async startRuntimeMetrics(client: Client, frequency: number = DATADOG_IDLE_INTERVAL) {\n const platform = await client.services.services.SystemService?.getPlatform();\n invariant(platform, 'platform is required');\n\n this.setTag('platform_type', Platform.PLATFORM_TYPE[platform.type as number].toLowerCase());\n if (this._mode === 'full') {\n // platform[foo] does not work?\n if (platform.platform) {\n this.setTag('platform', platform.platform);\n }\n if (platform.arch) {\n this.setTag('arch', platform.arch);\n }\n if (platform.runtime) {\n this.setTag('runtime', platform.runtime);\n }\n }\n scheduleTaskInterval(\n this._ctx,\n async () => {\n log('platform');\n client.services.services.SystemService?.getPlatform()\n .then((platform) => {\n log('platform', { platform });\n if (platform.memory) {\n this.gauge('dxos.client.runtime.rss', platform.memory.rss);\n this.gauge('dxos.client.runtime.heapTotal', platform.memory.heapTotal);\n this.gauge('dxos.client.runtime.heapUsed', platform.memory.heapUsed);\n }\n })\n .catch((error) => log('platform error', { error }));\n },\n frequency,\n );\n }\n\n //\n // Telemetry\n //\n\n private async _initTelemetry() {\n if (this._secrets.TELEMETRY_API_KEY && this._mode !== 'disabled') {\n const { SegmentTelemetry } = await import('./segment');\n this._telemetry = new SegmentTelemetry({\n apiKey: this._secrets.TELEMETRY_API_KEY,\n batchSize: this._telemetryBatchSize,\n getTags: () =>\n Object.fromEntries(\n Array.from(this._tags)\n .filter(([key, value]) => {\n return value.scope === 'all' || value.scope === 'telemetry';\n })\n .map(([key, value]) => [key, value.value]),\n ),\n });\n } else {\n log('segment disabled');\n }\n }\n\n /**\n * A telemetry event.\n *\n * The default implementation uses Segment.\n */\n event(options: EventOptions) {\n this._telemetry?.event(options);\n }\n\n /**\n * A telemetry page view.\n *\n * The default implementation uses Segment.\n */\n page(options: PageOptions) {\n this._telemetry?.page(options);\n }\n\n //\n // Error Logs\n //\n\n private async _initErrorLogs() {\n if (this._secrets.SENTRY_DESTINATION && this._mode !== 'disabled') {\n const { captureException, enableSentryLogProcessor, configureTracing, init, setTag } = await import('./sentry');\n this._captureException = captureException;\n this._setTag = setTag;\n\n // TODO(nf): refactor package into this one?\n log.info('Initializing Sentry', {\n dest: this._secrets.SENTRY_DESTINATION,\n options: this._errorReportingOptions,\n });\n init({\n ...this._errorReportingOptions,\n destination: this._secrets.SENTRY_DESTINATION,\n scrubFilenames: this._mode !== 'full',\n });\n if (this._errorReportingOptions?.tracing) {\n configureTracing();\n }\n // TODO(nf): set platform at instantiation? needed for node.\n if (this._errorLogProcessor) {\n enableSentryLogProcessor();\n }\n // TODO(nf): is this different than passing as properties in options?\n this._tags.forEach((v, k) => {\n if (v.scope === 'all' || v.scope === 'errors') {\n setTag(k, v.value);\n }\n });\n } else {\n log('sentry disabled');\n }\n }\n\n /**\n * Manually capture an exception.\n *\n * The default implementation uses Sentry.\n */\n captureException(err: any) {\n if (this.enabled) {\n this._captureException?.(err);\n }\n }\n}\n", "{\n \"SENTRY_DESTINATION\": \"https://2647916221e643869965e78469479aa4@o4504012000067584.ingest.sentry.io/4504012027265029\",\n \"TELEMETRY_API_KEY\": \"B00QG6PtJJrJ0VVFe0H5a6bcUUShKyZM\",\n \"IPDATA_API_KEY\": \"73dfdecdf979c18f07d50cf841bbdd9e589f237256326ac8cca23786\",\n \"DATADOG_API_KEY\": null,\n \"DATADOG_APP_KEY\": null\n}", "//\n// Copyright 2022 DXOS.org\n//\n\n// NOTE: localStorage is not available in web workers.\nimport * as localForage from 'localforage';\n\n// import { type Platform } from '@dxos/client-services';\n// import { type InitOptions as TelemetryInitOptions } from '@dxos/telemetry';\n\nimport type { Config } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport type { IPData } from './common';\nimport type { Mode, Observability } from '../observability';\n\nexport const OBSERVABILITY_DISABLED_KEY = 'observability-disabled';\nexport const OBSERVABILITY_GROUP_KEY = 'observability-group';\n\nexport const isObservabilityDisabled = async (namespace: string): Promise<boolean> => {\n try {\n return (await localForage.getItem(`${namespace}:${OBSERVABILITY_DISABLED_KEY}`)) === 'true';\n } catch (err) {\n log.catch('Failed to check if observability is disabled, assuming it is', err);\n return true;\n }\n};\n\nexport const storeObservabilityDisabled = async (namespace: string, value: boolean) => {\n try {\n await localForage.setItem(`${namespace}:${OBSERVABILITY_DISABLED_KEY}`, String(value));\n } catch (err) {\n log.catch('Failed to store observability disabled', err);\n }\n};\n\nexport const getObservabilityGroup = async (namespace: string): Promise<string | undefined> => {\n try {\n return (await localForage.getItem(`${namespace}:${OBSERVABILITY_GROUP_KEY}`)) ?? undefined;\n } catch (err) {\n log.catch('Failed to get observability group', err);\n }\n};\n\nexport const storeObservabilityGroup = async (namespace: string, value: string) => {\n try {\n await localForage.setItem(`${namespace}:${OBSERVABILITY_GROUP_KEY}`, value);\n } catch (err) {\n log.catch('Failed to store observability group', err);\n }\n};\n\nexport type AppObservabilityOptions = {\n namespace: string;\n config: Config;\n mode?: Mode;\n tracingEnable?: boolean;\n replayEnable?: boolean;\n // TODO(nf): options for providers?\n};\n\n// TODO(wittjosiah): Store preference for disabling observability.\n// At minimum should be stored locally (i.e., localstorage), possibly in halo preference.\n// Needs to be hooked up to settings page for user visibility.\nexport const initializeAppObservability = async ({\n namespace,\n config,\n mode = 'basic',\n tracingEnable = true,\n replayEnable = true,\n}: AppObservabilityOptions): Promise<Observability> => {\n log('initializeAppObservability', { config });\n\n /*\n const platform = (await client.services.services.SystemService?.getPlatform()) as Platform;\n if (!platform) {\n log.error('failed to get platform, could not initialize observability');\n return undefined;\n }\n */\n\n const group = (await getObservabilityGroup(namespace)) ?? undefined;\n const release = `${namespace}@${config.get('runtime.app.build.version')}`;\n const environment = config.get('runtime.app.env.DX_ENVIRONMENT');\n\n const observabilityDisabled = await isObservabilityDisabled(namespace);\n\n const { Observability } = await import('../observability');\n\n // TODO(nf): configure mode\n const observability = new Observability({\n namespace,\n release,\n environment,\n group,\n mode,\n config,\n errorLog: {\n sentryInitOptions: {\n environment,\n release,\n tracing: tracingEnable,\n replay: replayEnable,\n // TODO(wittjosiah): Configure these.\n sampleRate: 1.0,\n replaySampleRate: 0.1,\n replaySampleRateOnError: 1.0,\n },\n },\n });\n\n // global kill switch\n if (observabilityDisabled) {\n observability.setMode('disabled');\n log.info('observability disabled');\n return observability;\n }\n\n try {\n const getIPData = async (config: Config): Promise<IPData | void> => {\n const IP_DATA_CACHE_TIMEOUT = 6 * 60 * 60 * 1000; // 6 hours\n type CachedIPData = {\n data: IPData;\n timestamp: number;\n };\n\n // Check cache first.\n const cachedData: null | CachedIPData = await localForage.getItem('dxos:observability:ipdata');\n if (cachedData && cachedData.timestamp > Date.now() - IP_DATA_CACHE_TIMEOUT) {\n return cachedData.data;\n }\n\n // Fetch data if not cached.\n const IPDATA_API_KEY = config.get('runtime.app.env.DX_IPDATA_API_KEY');\n if (IPDATA_API_KEY) {\n return fetch(`https://api.ipdata.co?api-key=${IPDATA_API_KEY}`)\n .then((res) => res.json())\n .then((data) => {\n // Cache data.\n localForage\n .setItem('dxos:observability:ipdata', {\n data,\n timestamp: Date.now(),\n })\n .catch((err) => observability.captureException(err));\n\n return data;\n })\n .catch((err) => observability.captureException(err));\n }\n };\n\n // TODO(nf): plugin state?\n\n // TODO(nf): should provide capability to init Sentry earlier in booting process to capture errors during initialization.\n\n await observability.initialize();\n\n const ipData = await getIPData(config);\n\n ipData && observability.addIPDataTelemetryTags(ipData);\n\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n setInterval(async () => {\n try {\n const storageEstimate = await navigator.storage.estimate();\n storageEstimate.usage && observability.setTag('storageUsage', storageEstimate.usage.toString(), 'telemetry');\n storageEstimate.quota && observability.setTag('storageQuota', storageEstimate.quota.toString(), 'telemetry');\n } catch (error) {\n log.warn('Failed to run estimate()', error);\n }\n }, 10e3);\n }\n } catch (err: any) {\n log.error('Failed to initialize app observability', err);\n }\n\n return observability;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport type { Client } from '@dxos/client';\n\n// TODO(wittjosiah): Improve privacy of telemetry identifiers.\n// - Identifier should be generated client-side with no attachment to identity.\n// - Identifier can then be reset by user.\n// - Identifier can be synced via HALO to allow for correlation of events bewteen devices.\n// - Identifier should also be stored outside of HALO such that it is available immediately on startup.\nexport const getTelemetryIdentifier = (client: Client) => {\n if (!client?.initialized) {\n return undefined;\n }\n\n const identity = client.halo.identity.get();\n if (identity) {\n return identity.identityKey.truncate();\n }\n\n return undefined;\n};\n\nexport type IPData = { city: string; region: string; country: string; latitude: number; longitude: number };\n", "//\n// Copyright 2022 DXOS.org\n//\nimport yaml from 'js-yaml';\nimport { existsSync, statSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { v4 as uuid, validate as validateUuid } from 'uuid';\n\nimport type { Config } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { Observability, type Mode } from '../observability';\n\n/**\n * Print observability banner once per installation.\n */\nexport const showObservabilityBanner = async (configDir: string, bannercb: (input: string) => void) => {\n const path = join(configDir, '.observability-banner-printed');\n if (existsSync(path)) {\n return;\n }\n bannercb(\n // eslint-disable-next-line no-multi-str\n 'Basic observability data will be sent to the DXOS team in order to improve the product. This includes \\\n performance metrics, error logs, and usage data. No personally identifiable information, other than your \\\n public key, is included with this data and no private data ever leaves your devices. To disable sending \\\n observability data, set the environment variable DX_DISABLE_OBSERVABILITY=true.',\n );\n\n await writeFile(path, '', 'utf-8');\n};\n\nexport const getObservabilityState = async (configDir: string): Promise<PersistentObservabilityState> => {\n // check whether configDir exists and if it's a directory\n\n if (existsSync(configDir)) {\n if (!statSync(configDir).isDirectory()) {\n throw new Error(`Config directory ${configDir} exists but is not a directory`);\n }\n } else {\n await mkdir(configDir, { recursive: true });\n }\n\n const idPath = join(configDir, 'observability.yml');\n if (existsSync(idPath)) {\n const context = await readFile(idPath, 'utf-8');\n return validate(context) ?? initializeState(idPath);\n }\n\n return initializeState(idPath);\n};\n\nexport type PersistentObservabilityState = {\n installationId: string;\n group?: string;\n mode: Mode;\n};\n\n// create initial state and write to file, using environment variables to override defaults.\nconst initializeState = async (idPath: string): Promise<PersistentObservabilityState> => {\n // TODO(nf): read initial values from config or seed file\n const observabilityState = {\n installationId: uuid(),\n group: process.env.DX_OBSERVABILITY_GROUP ?? undefined,\n mode: (process.env.DX_DISABLE_OBSERVABILITY ? 'disabled' : process.env.DX_OBSERVABILITY_MODE ?? 'basic') as Mode,\n };\n\n await writeFile(\n idPath,\n '# This file is automatically generated by the @dxos/cli.\\n' + yaml.dump(observabilityState),\n 'utf-8',\n );\n\n return observabilityState;\n};\n\nconst validate = (contextString: string) => {\n const context = yaml.load(contextString) as PersistentObservabilityState;\n if (Boolean(context.installationId) && validateUuid(context.installationId!)) {\n return {\n ...context,\n mode: process.env.DX_DISABLE_OBSERVABILITY ? 'disabled' : context.mode ?? 'basic',\n };\n }\n};\n\nexport type NodeObservabilityOptions = {\n installationId: string;\n group?: string;\n namespace: string;\n version: string;\n config: Config;\n mode?: Mode;\n tracingEnable?: boolean;\n replayEnable?: boolean;\n // TODO(nf): options for providers?\n};\n\nexport const initializeNodeObservability = async ({\n namespace,\n version,\n config,\n installationId,\n group,\n mode = 'basic',\n tracingEnable = true,\n replayEnable = true,\n}: NodeObservabilityOptions): Promise<Observability> => {\n log('initializeCliObservability', { config });\n\n // TODO(nf): make CLI build populate runtime.app.build config?\n const release = `${namespace}@${version}`;\n const environment = process.env.DX_ENVIRONMENT ?? 'unknown';\n\n const observability = new Observability({\n namespace,\n release,\n environment,\n group,\n mode,\n errorLog: {\n sentryInitOptions: {\n environment,\n release,\n // TODO(wittjosiah): Configure this.\n sampleRate: 1.0,\n },\n logProcessor: true,\n },\n });\n\n observability.setTag('installationId', installationId);\n\n // TODO(nf): cache ipdata to avoid repeated requests\n const IPDATA_API_KEY = config.get('runtime.app.env.DX_IPDATA_API_KEY');\n try {\n const res = await fetch(`https://api.ipdata.co/?api-key=${IPDATA_API_KEY}`);\n const ipData = await res.json();\n ipData && observability.addIPDataTelemetryTags(ipData);\n } catch (err) {\n observability?.captureException(err);\n }\n return observability;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type { Space } from '@dxos/client-protocol';\n\nexport type MapSpacesOptions = {\n verbose?: boolean;\n truncateKeys?: boolean;\n};\n\nexport const mapSpaces = (spaces: Space[], options: MapSpacesOptions = { verbose: false, truncateKeys: false }) => {\n return spaces.map((space) => {\n // TODO(burdon): Factor out.\n // TODO(burdon): Agent needs to restart before `ready` is available.\n const { open, ready } = space.internal.data.metrics ?? {};\n const startup = open && ready && ready.getTime() - open.getTime();\n\n // TODO(burdon): Get feeds from client-services if verbose (factor out from devtools/diagnostics).\n // const host = client.services.services.DevtoolsHost!;\n const pipeline = space.internal.data.pipeline;\n const startDataMutations = pipeline?.currentEpoch?.subject.assertion.timeframe.totalMessages() ?? 0;\n const epoch = pipeline?.currentEpoch?.subject.assertion.number;\n // const appliedEpoch = pipeline?.appliedEpoch?.subject.assertion.number;\n const currentDataMutations = pipeline?.currentDataTimeframe?.totalMessages() ?? 0;\n const totalDataMutations = pipeline?.targetDataTimeframe?.totalMessages() ?? 0;\n\n return {\n // TODO(nf): truncate keys for DD?\n key: space.key.truncate(),\n open: space.isOpen,\n members: space.members.get().length,\n objects: space.db.query().objects.length,\n startup,\n epoch,\n // appliedEpoch,\n startDataMutations,\n currentDataMutations,\n totalDataMutations,\n\n // TODO(burdon): Negative?\n progress: (\n Math.min(Math.abs((currentDataMutations - startDataMutations) / (totalDataMutations - startDataMutations)), 1) *\n 100\n ).toFixed(0),\n };\n });\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport type { Client } from '@dxos/client';\n\nimport { getTelemetryIdentifier } from './common';\nimport type { Observability } from '../observability';\n\nlet lastFocusEvent = new Date();\nlet totalTime = 0;\n\nexport const setupTelemetryListeners = (namespace: string, client: Client, observability: Observability) => {\n const clickCallback = (event: any) => {\n setTimeout(() =>\n observability.event({\n identityId: getTelemetryIdentifier(client),\n name: `${namespace}.window.click`,\n properties: {\n href: window.location.href,\n id: (event.target as HTMLElement)?.id,\n path: (event.path as HTMLElement[])\n ?.filter((el) => Boolean(el.tagName))\n .map((el) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ''}`)\n .reverse()\n .join('>'),\n },\n }),\n );\n };\n\n const focusCallback = () => {\n const now = new Date();\n setTimeout(() =>\n observability.event({\n identityId: getTelemetryIdentifier(client),\n name: `${namespace}.window.focus`,\n properties: {\n href: window.location.href,\n timeAway: now.getTime() - lastFocusEvent.getTime(),\n },\n }),\n );\n lastFocusEvent = now;\n };\n\n const blurCallback = () => {\n const now = new Date();\n const timeSpent = now.getTime() - lastFocusEvent.getTime();\n setTimeout(() =>\n observability.event({\n identityId: getTelemetryIdentifier(client),\n name: `${namespace}.window.blur`,\n properties: {\n href: window.location.href,\n timeSpent,\n },\n }),\n );\n lastFocusEvent = now;\n totalTime = totalTime + timeSpent;\n };\n\n const unloadCallback = () => {\n setTimeout(() =>\n observability.event({\n identityId: getTelemetryIdentifier(client),\n name: `${namespace}.page.unload`,\n properties: {\n href: window.location.href,\n timeSpent: totalTime,\n },\n }),\n );\n };\n\n const errorCallback = (event: ErrorEvent) => {\n setTimeout(() =>\n observability.event({\n identityId: getTelemetryIdentifier(client),\n name: `${namespace}.window.error`,\n properties: {\n href: window.location.href,\n message: event.message,\n filename: event.filename,\n stack: (event.error as Error).stack,\n },\n }),\n );\n };\n\n window.addEventListener('click', clickCallback, true);\n window.addEventListener('focus', focusCallback);\n window.addEventListener('blur', blurCallback);\n window.addEventListener('beforeunload', unloadCallback);\n window.addEventListener('error', errorCallback);\n\n return () => {\n window.removeEventListener('click', clickCallback, true);\n window.removeEventListener('focus', focusCallback);\n window.removeEventListener('blur', blurCallback);\n window.removeEventListener('beforeunload', unloadCallback);\n window.removeEventListener('error', errorCallback);\n };\n};\n"],
5
- "mappings": ";AAIA,SAASA,OAAOC,4BAA4B;AAG5C,SAASC,eAAe;AACxB,SAASC,iBAAiB;AAC1B,SAASC,OAAAA,YAAW;AACpB,SAASC,uBAAuB;AAChC,SAASC,YAAgCC,gBAAgB;AACzD,SAASC,cAAc;;;ACZvB;AAAA,EACE,oBAAsB;AAAA,EACtB,mBAAqB;AAAA,EACrB,gBAAkB;AAAA,EAClB,iBAAmB;AAAA,EACnB,iBAAmB;AACrB;;;ACDA,YAAYC,iBAAiB;AAM7B,SAASC,WAAW;;AAKb,IAAMC,6BAA6B;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UAAI,KAAKO,wBAAwB0J,SAAS;AACxCP,yBAAAA;MACF;AAEA,UAAI,KAAKjJ,oBAAoB;AAC3BgJ,iCAAAA;MACF;AAEA,WAAKrK,MAAMiG,QAAQ,CAAC6E,GAAGC,MAAAA;AACrB,YAAID,EAAE9H,UAAU,SAAS8H,EAAE9H,UAAU,UAAU;AAC7C5C,iBAAO2K,GAAGD,EAAE/H,KAAK;QACnB;MACF,CAAA;IACF,OAAO;AACLZ,MAAAA,KAAI,mBAAA,QAAA;;;;;;IACN;EACF;;;;;;EAOAiI,iBAAiBY,KAAU;AACzB,QAAI,KAAKnI,SAAS;AAChB,WAAK2H,oBAAoBQ,GAAAA;IAC3B;EACF;AACF;",
6
- "names": ["Event", "scheduleTaskInterval", "Context", "invariant", "log", "ConnectionState", "DeviceKind", "Platform", "isNode", "localForage", "log", "OBSERVABILITY_DISABLED_KEY", "OBSERVABILITY_GROUP_KEY", "isObservabilityDisabled", "namespace", "getItem", "err", "catch", "storeObservabilityDisabled", "value", "setItem", "String", "getObservabilityGroup", "undefined", "storeObservabilityGroup", "initializeAppObservability", "config", "mode", "tracingEnable", "replayEnable", "group", "release", "get", "environment", "observabilityDisabled", "Observability", "observability", "errorLog", "sentryInitOptions", "tracing", "replay", "sampleRate", "replaySampleRate", "replaySampleRateOnError", "setMode", "info", "getIPData", "IP_DATA_CACHE_TIMEOUT", "cachedData", "timestamp", "Date", "now", "data", "IPDATA_API_KEY", "fetch", "then", "res", "json", "captureException", "initialize", "ipData", "addIPDataTelemetryTags", "navigator", "storage", "estimate", "setInterval", "storageEstimate", "usage", "setTag", "toString", "quota", "error", "warn", "getTelemetryIdentifier", "client", "initialized", "undefined", "identity", "halo", "get", "identityKey", "truncate", "yaml", "existsSync", "statSync", "mkdir", "readFile", "writeFile", "join", "v4", "uuid", "validate", "validateUuid", "log", "showObservabilityBanner", "configDir", "bannercb", "path", "join", "existsSync", "writeFile", "getObservabilityState", "statSync", "isDirectory", "Error", "mkdir", "recursive", "idPath", "context", "readFile", "validate", "initializeState", "observabilityState", "installationId", "uuid", "group", "process", "env", "DX_OBSERVABILITY_GROUP", "undefined", "mode", "DX_DISABLE_OBSERVABILITY", "DX_OBSERVABILITY_MODE", "yaml", "dump", "contextString", "load", "Boolean", "validateUuid", "initializeNodeObservability", "namespace", "version", "config", "tracingEnable", "replayEnable", "log", "release", "environment", "DX_ENVIRONMENT", "observability", "Observability", "errorLog", "sentryInitOptions", "sampleRate", "logProcessor", "setTag", "IPDATA_API_KEY", "get", "res", "fetch", "ipData", "json", "addIPDataTelemetryTags", "err", "captureException", "mapSpaces", "spaces", "options", "verbose", "truncateKeys", "map", "space", "open", "ready", "internal", "data", "metrics", "startup", "getTime", "pipeline", "startDataMutations", "currentEpoch", "subject", "assertion", "timeframe", "totalMessages", "epoch", "number", "currentDataMutations", "currentDataTimeframe", "totalDataMutations", "targetDataTimeframe", "key", "truncate", "isOpen", "members", "get", "length", "objects", "db", "query", "progress", "Math", "min", "abs", "toFixed", "lastFocusEvent", "Date", "totalTime", "setupTelemetryListeners", "namespace", "client", "observability", "clickCallback", "event", "setTimeout", "identityId", "getTelemetryIdentifier", "name", "properties", "href", "window", "location", "id", "target", "path", "filter", "el", "Boolean", "tagName", "map", "toLowerCase", "reverse", "join", "focusCallback", "now", "timeAway", "getTime", "blurCallback", "timeSpent", "unloadCallback", "errorCallback", "message", "filename", "stack", "error", "addEventListener", "removeEventListener", "SPACE_METRICS_MIN_INTERVAL", "DATADOG_IDLE_INTERVAL", "Observability", "constructor", "namespace", "environment", "release", "config", "secrets", "group", "mode", "telemetry", "errorLog", "_ctx", "Context", "_tags", "Map", "addIPDataTelemetryTags", "ipData", "setTag", "city", "region", "country", "latitude", "toString", "longitude", "_namespace", "_mode", "_config", "_group", "_secrets", "_loadSecrets", "_telemetryBatchSize", "batchSize", "_errorReportingOptions", "sentryInitOptions", "_errorLogProcessor", "logProcessor", "isNode", "mergedSecrets", "buildSecrets", "process", "env", "DX_ENVIRONMENT", "DX_RELEASE", "SENTRY_DESTINATION", "TELEMETRY_API_KEY", "IPDATA_API_KEY", "DATADOG_API_KEY", "DATADOG_APP_KEY", "log", "rtc", "get", "initialize", "_initMetrics", "_initTelemetry", "_initErrorLogs", "close", "dispose", "setMode", "enabled", "key", "value", "scope", "undefined", "_setTag", "set", "getTag", "setIdentityTags", "client", "services", "IdentityService", "queryIdentity", "subscribe", "idqr", "identity", "identityKey", "truncate", "DevicesService", "queryDevices", "dqr", "devices", "length", "device", "invariant", "thisDevice", "find", "kind", "DeviceKind", "CURRENT", "deviceKey", "profile", "label", "DatadogMetrics", "_metrics", "apiKey", "getTags", "Object", "fromEntries", "Array", "from", "filter", "map", "gauge", "name", "extraTags", "startNetworkMetrics", "updateSignalMetrics", "Event", "on", "networkStatus", "signaling", "forEach", "server", "state", "swarmCount", "connectionStates", "ConnectionState", "totalReadBufferSize", "totalWriteBufferSize", "totalChannelBufferSize", "connectionInfo", "conn", "connections", "readBufferSize", "writeBufferSize", "stream", "streams", "NetworkService", "queryStatus", "emit", "startSpacesMetrics", "spaces", "subscriptions", "onDispose", "subscription", "unsubscribe", "updateSpaceMetrics", "debounce", "data", "mapSpaces", "truncateKeys", "members", "objects", "epoch", "currentDataMutations", "event", "identityId", "getTelemetryIdentifier", "properties", "subscribeToSpaceUpdate", "space", "pipeline", "next", "toHex", "has", "scheduleTaskInterval", "startRuntimeMetrics", "frequency", "platform", "SystemService", "getPlatform", "Platform", "PLATFORM_TYPE", "type", "toLowerCase", "arch", "runtime", "then", "memory", "rss", "heapTotal", "heapUsed", "catch", "error", "SegmentTelemetry", "_telemetry", "options", "page", "captureException", "enableSentryLogProcessor", "configureTracing", "init", "_captureException", "info", "dest", "destination", "scrubFilenames", "tracing", "v", "k", "err"]
7
- }
@@ -1,7 +0,0 @@
1
- import {
2
- Observability
3
- } from "./chunk-XF67HMEA.mjs";
4
- export {
5
- Observability
6
- };
7
- //# sourceMappingURL=observability-MK4LFDOW.mjs.map