@dxos/observability 0.6.12 → 0.6.13-main.548ca8d

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 (36) hide show
  1. package/dist/lib/node-esm/chunk-BHETLWXO.mjs +939 -0
  2. package/dist/lib/node-esm/chunk-BHETLWXO.mjs.map +7 -0
  3. package/dist/lib/node-esm/chunk-CMDADTM3.mjs +133 -0
  4. package/dist/lib/node-esm/chunk-CMDADTM3.mjs.map +7 -0
  5. package/dist/lib/node-esm/chunk-YJ4KVBWC.mjs +2 -0
  6. package/dist/lib/node-esm/chunk-YJ4KVBWC.mjs.map +7 -0
  7. package/dist/lib/node-esm/index.mjs +34 -0
  8. package/dist/lib/node-esm/index.mjs.map +7 -0
  9. package/dist/lib/node-esm/meta.json +1 -0
  10. package/dist/lib/node-esm/observability-QJFZLUL4.mjs +8 -0
  11. package/dist/lib/node-esm/observability-QJFZLUL4.mjs.map +7 -0
  12. package/dist/lib/node-esm/otel-YI7HAFOG.mjs +258 -0
  13. package/dist/lib/node-esm/otel-YI7HAFOG.mjs.map +7 -0
  14. package/dist/lib/node-esm/segment/index.mjs +144 -0
  15. package/dist/lib/node-esm/segment/index.mjs.map +7 -0
  16. package/dist/lib/node-esm/sentry/index.mjs +25 -0
  17. package/dist/lib/node-esm/sentry/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/sentry-log-processor-JYJH3AMG.mjs +133 -0
  19. package/dist/lib/node-esm/sentry-log-processor-JYJH3AMG.mjs.map +7 -0
  20. package/dist/types/src/sentry/node.node.test.d.ts +2 -0
  21. package/dist/types/src/sentry/node.node.test.d.ts.map +1 -0
  22. package/dist/types/src/sentry/{node.test.js → node.node.test.js} +8 -15
  23. package/dist/types/src/sentry/node.node.test.js.map +1 -0
  24. package/dist/types/src/sentry/sentry.node.test.d.ts +2 -0
  25. package/dist/types/src/sentry/sentry.node.test.d.ts.map +1 -0
  26. package/dist/types/src/sentry/{sentry.test.js → sentry.node.test.js} +8 -15
  27. package/dist/types/src/sentry/sentry.node.test.js.map +1 -0
  28. package/package.json +21 -18
  29. package/src/sentry/{node.test.ts → node.node.test.ts} +2 -9
  30. package/src/sentry/{sentry.test.ts → sentry.node.test.ts} +2 -7
  31. package/dist/types/src/sentry/node.test.d.ts +0 -2
  32. package/dist/types/src/sentry/node.test.d.ts.map +0 -1
  33. package/dist/types/src/sentry/node.test.js.map +0 -1
  34. package/dist/types/src/sentry/sentry.test.d.ts +0 -2
  35. package/dist/types/src/sentry/sentry.test.d.ts.map +0 -1
  36. package/dist/types/src/sentry/sentry.test.js.map +0 -1
@@ -0,0 +1,939 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+
3
+ // packages/sdk/observability/src/observability.ts
4
+ import { Event, scheduleTaskInterval } from "@dxos/async";
5
+ import { Context } from "@dxos/context";
6
+ import { invariant } from "@dxos/invariant";
7
+ import { log as log3 } from "@dxos/log";
8
+ import { ConnectionState } from "@dxos/network-manager";
9
+ import { DeviceKind, Platform } from "@dxos/protocols/proto/dxos/client/services";
10
+ import { isNode } from "@dxos/util";
11
+
12
+ // packages/sdk/observability/src/cli-observability-secrets.json
13
+ var cli_observability_secrets_default = {
14
+ SENTRY_DESTINATION: "https://2647916221e643869965e78469479aa4@o4504012000067584.ingest.sentry.io/4504012027265029",
15
+ TELEMETRY_API_KEY: "B00QG6PtJJrJ0VVFe0H5a6bcUUShKyZM",
16
+ IPDATA_API_KEY: "73dfdecdf979c18f07d50cf841bbdd9e589f237256326ac8cca23786",
17
+ OTEL_ENDPOINT: null,
18
+ OTEL_AUTHORIZATION: null
19
+ };
20
+
21
+ // packages/sdk/observability/src/helpers/browser-observability.ts
22
+ import * as localForage from "localforage";
23
+ import { log } from "@dxos/log";
24
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/observability/src/helpers/browser-observability.ts";
25
+ var OBSERVABILITY_DISABLED_KEY = "observability-disabled";
26
+ var OBSERVABILITY_GROUP_KEY = "observability-group";
27
+ var isObservabilityDisabled = async (namespace) => {
28
+ try {
29
+ return await localForage.getItem(`${namespace}:${OBSERVABILITY_DISABLED_KEY}`) === "true";
30
+ } catch (err) {
31
+ log.catch("Failed to check if observability is disabled, assuming it is", err, {
32
+ F: __dxlog_file,
33
+ L: 24,
34
+ S: void 0,
35
+ C: (f, a) => f(...a)
36
+ });
37
+ return true;
38
+ }
39
+ };
40
+ var storeObservabilityDisabled = async (namespace, value) => {
41
+ try {
42
+ await localForage.setItem(`${namespace}:${OBSERVABILITY_DISABLED_KEY}`, String(value));
43
+ } catch (err) {
44
+ log.catch("Failed to store observability disabled", err, {
45
+ F: __dxlog_file,
46
+ L: 33,
47
+ S: void 0,
48
+ C: (f, a) => f(...a)
49
+ });
50
+ }
51
+ };
52
+ var getObservabilityGroup = async (namespace) => {
53
+ try {
54
+ return await localForage.getItem(`${namespace}:${OBSERVABILITY_GROUP_KEY}`) ?? void 0;
55
+ } catch (err) {
56
+ log.catch("Failed to get observability group", err, {
57
+ F: __dxlog_file,
58
+ L: 41,
59
+ S: void 0,
60
+ C: (f, a) => f(...a)
61
+ });
62
+ }
63
+ };
64
+ var storeObservabilityGroup = async (namespace, value) => {
65
+ try {
66
+ await localForage.setItem(`${namespace}:${OBSERVABILITY_GROUP_KEY}`, value);
67
+ } catch (err) {
68
+ log.catch("Failed to store observability group", err, {
69
+ F: __dxlog_file,
70
+ L: 49,
71
+ S: void 0,
72
+ C: (f, a) => f(...a)
73
+ });
74
+ }
75
+ };
76
+ var initializeAppObservability = async ({ namespace, config, mode = "basic", tracingEnable = true, replayEnable = true }) => {
77
+ log("initializeAppObservability", {
78
+ config
79
+ }, {
80
+ F: __dxlog_file,
81
+ L: 72,
82
+ S: void 0,
83
+ C: (f, a) => f(...a)
84
+ });
85
+ const group = await getObservabilityGroup(namespace) ?? void 0;
86
+ const release = `${namespace}@${config.get("runtime.app.build.version")}`;
87
+ const environment = config.get("runtime.app.env.DX_ENVIRONMENT");
88
+ const observabilityDisabled = await isObservabilityDisabled(namespace);
89
+ const { Observability: Observability2 } = await import("./observability-QJFZLUL4.mjs");
90
+ const observability = new Observability2({
91
+ namespace,
92
+ release,
93
+ environment,
94
+ group,
95
+ mode,
96
+ config,
97
+ errorLog: {
98
+ sentryInitOptions: {
99
+ environment,
100
+ release,
101
+ tracing: tracingEnable,
102
+ replay: replayEnable,
103
+ // TODO(wittjosiah): Configure these.
104
+ sampleRate: 1,
105
+ replaySampleRate: 0.1,
106
+ replaySampleRateOnError: 1
107
+ }
108
+ }
109
+ });
110
+ if (observabilityDisabled) {
111
+ observability.setMode("disabled");
112
+ log.info("observability disabled", void 0, {
113
+ F: __dxlog_file,
114
+ L: 115,
115
+ S: void 0,
116
+ C: (f, a) => f(...a)
117
+ });
118
+ return observability;
119
+ }
120
+ try {
121
+ const getIPData = async (config2) => {
122
+ const IP_DATA_CACHE_TIMEOUT = 6 * 60 * 60 * 1e3;
123
+ const cachedData = await localForage.getItem("dxos:observability:ipdata");
124
+ if (cachedData && cachedData.timestamp > Date.now() - IP_DATA_CACHE_TIMEOUT) {
125
+ return cachedData.data;
126
+ }
127
+ const IPDATA_API_KEY = config2.get("runtime.app.env.DX_IPDATA_API_KEY");
128
+ if (IPDATA_API_KEY) {
129
+ return fetch(`https://api.ipdata.co?api-key=${IPDATA_API_KEY}`).then((res) => res.json()).then((data) => {
130
+ localForage.setItem("dxos:observability:ipdata", {
131
+ data,
132
+ timestamp: Date.now()
133
+ }).catch((err) => observability.captureException(err));
134
+ return data;
135
+ }).catch((err) => observability.captureException(err));
136
+ }
137
+ };
138
+ await observability.initialize();
139
+ observability.startErrorLogs();
140
+ const ipData = await getIPData(config);
141
+ ipData && observability.addIPDataTelemetryTags(ipData);
142
+ if (typeof navigator !== "undefined" && navigator.storage?.estimate) {
143
+ setInterval(async () => {
144
+ try {
145
+ const storageEstimate = await navigator.storage.estimate();
146
+ storageEstimate.usage && observability.setTag("storageUsage", storageEstimate.usage.toString(), "telemetry");
147
+ storageEstimate.quota && observability.setTag("storageQuota", storageEstimate.quota.toString(), "telemetry");
148
+ } catch (error) {
149
+ log.warn("Failed to run estimate()", error, {
150
+ F: __dxlog_file,
151
+ L: 171,
152
+ S: void 0,
153
+ C: (f, a) => f(...a)
154
+ });
155
+ }
156
+ }, 1e4);
157
+ }
158
+ } catch (err) {
159
+ log.error("Failed to initialize app observability", err, {
160
+ F: __dxlog_file,
161
+ L: 176,
162
+ S: void 0,
163
+ C: (f, a) => f(...a)
164
+ });
165
+ }
166
+ return observability;
167
+ };
168
+
169
+ // packages/sdk/observability/src/helpers/common.ts
170
+ var getTelemetryIdentifier = (client) => {
171
+ if (!client?.initialized) {
172
+ return void 0;
173
+ }
174
+ const identity = client.halo.identity.get();
175
+ if (identity) {
176
+ return identity.identityKey.truncate();
177
+ }
178
+ return void 0;
179
+ };
180
+
181
+ // packages/sdk/observability/src/helpers/node-observability.ts
182
+ import yaml from "js-yaml";
183
+ import { existsSync, statSync } from "node:fs";
184
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
185
+ import { join } from "node:path";
186
+ import { v4 as uuid, validate as validateUuid } from "uuid";
187
+ import { log as log2 } from "@dxos/log";
188
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/sdk/observability/src/helpers/node-observability.ts";
189
+ var showObservabilityBanner = async (configDir, bannercb) => {
190
+ const path = join(configDir, ".observability-banner-printed");
191
+ if (existsSync(path)) {
192
+ return;
193
+ }
194
+ bannercb(
195
+ // eslint-disable-next-line no-multi-str
196
+ "Basic observability data will be sent to the DXOS team in order to improve the product. This includes performance metrics, error logs, and usage data. No personally identifiable information, other than your public key, is included with this data and no private data ever leaves your devices. To disable sending observability data, set the environment variable DX_DISABLE_OBSERVABILITY=true."
197
+ );
198
+ await writeFile(path, "", "utf-8");
199
+ };
200
+ var getObservabilityState = async (configDir) => {
201
+ if (existsSync(configDir)) {
202
+ if (!statSync(configDir).isDirectory()) {
203
+ throw new Error(`Config directory ${configDir} exists but is not a directory`);
204
+ }
205
+ } else {
206
+ await mkdir(configDir, {
207
+ recursive: true
208
+ });
209
+ }
210
+ const idPath = join(configDir, "observability.yml");
211
+ if (existsSync(idPath)) {
212
+ const context = await readFile(idPath, "utf-8");
213
+ return validate(context) ?? initializeState(idPath);
214
+ }
215
+ return initializeState(idPath);
216
+ };
217
+ var initializeState = async (idPath) => {
218
+ const observabilityState = {
219
+ installationId: uuid(),
220
+ group: process.env.DX_OBSERVABILITY_GROUP ?? void 0,
221
+ mode: process.env.DX_DISABLE_OBSERVABILITY ? "disabled" : process.env.DX_OBSERVABILITY_MODE ?? "basic"
222
+ };
223
+ await writeFile(idPath, "# This file is automatically generated by the @dxos/cli.\n" + yaml.dump(observabilityState), "utf-8");
224
+ return observabilityState;
225
+ };
226
+ var validate = (contextString) => {
227
+ const context = yaml.load(contextString);
228
+ if (Boolean(context.installationId) && validateUuid(context.installationId)) {
229
+ return {
230
+ ...context,
231
+ mode: process.env.DX_DISABLE_OBSERVABILITY ? "disabled" : context.mode ?? "basic"
232
+ };
233
+ }
234
+ };
235
+ var initializeNodeObservability = async ({ namespace, version, config, installationId, group, mode = "basic", tracingEnable = true, replayEnable = true }) => {
236
+ log2("initializeCliObservability", {
237
+ config
238
+ }, {
239
+ F: __dxlog_file2,
240
+ L: 110,
241
+ S: void 0,
242
+ C: (f, a) => f(...a)
243
+ });
244
+ const release = `${namespace}@${version}`;
245
+ const environment = process.env.DX_ENVIRONMENT ?? "unknown";
246
+ const observability = new Observability({
247
+ namespace,
248
+ release,
249
+ environment,
250
+ group,
251
+ mode,
252
+ errorLog: {
253
+ sentryInitOptions: {
254
+ environment,
255
+ release,
256
+ // TODO(wittjosiah): Configure this.
257
+ sampleRate: 1
258
+ }
259
+ }
260
+ });
261
+ observability.setTag("installationId", installationId);
262
+ const IPDATA_API_KEY = config.get("runtime.app.env.DX_IPDATA_API_KEY");
263
+ try {
264
+ const res = await fetch(`https://api.ipdata.co/?api-key=${IPDATA_API_KEY}`);
265
+ const ipData = await res.json();
266
+ ipData && observability.addIPDataTelemetryTags(ipData);
267
+ } catch (err) {
268
+ observability?.captureException(err);
269
+ }
270
+ return observability;
271
+ };
272
+
273
+ // packages/sdk/observability/src/helpers/map-spaces.ts
274
+ var mapSpaces = (spaces, options = {
275
+ verbose: false,
276
+ truncateKeys: false
277
+ }) => {
278
+ return spaces.map((space) => {
279
+ const { open, ready } = space.internal.data.metrics ?? {};
280
+ const startup = open && ready && ready.getTime() - open.getTime();
281
+ const pipeline = space.internal.data.pipeline;
282
+ const startDataMutations = pipeline?.currentEpoch?.subject.assertion.timeframe.totalMessages() ?? 0;
283
+ const epoch = pipeline?.currentEpoch?.subject.assertion.number;
284
+ const currentDataMutations = pipeline?.currentDataTimeframe?.totalMessages() ?? 0;
285
+ const totalDataMutations = pipeline?.targetDataTimeframe?.totalMessages() ?? 0;
286
+ return {
287
+ // TODO(nf): truncate keys for DD?
288
+ key: space.key.truncate(),
289
+ open: space.isOpen,
290
+ members: space.members.get().length,
291
+ objects: space.db.coreDatabase.getAllObjectIds().length,
292
+ startup,
293
+ epoch,
294
+ // appliedEpoch,
295
+ startDataMutations,
296
+ currentDataMutations,
297
+ totalDataMutations,
298
+ // TODO(burdon): Negative?
299
+ progress: (Math.min(Math.abs((currentDataMutations - startDataMutations) / (totalDataMutations - startDataMutations)), 1) * 100).toFixed(0)
300
+ };
301
+ });
302
+ };
303
+
304
+ // packages/sdk/observability/src/helpers/setup-telemetry-listeners.ts
305
+ var lastFocusEvent = /* @__PURE__ */ new Date();
306
+ var totalTime = 0;
307
+ var setupTelemetryListeners = (namespace, client, observability) => {
308
+ const clickCallback = (event) => {
309
+ const id = event.target?.id;
310
+ if (!id) {
311
+ return;
312
+ }
313
+ setTimeout(() => observability.event({
314
+ identityId: getTelemetryIdentifier(client),
315
+ name: `${namespace}.window.click`,
316
+ properties: {
317
+ href: window.location.href,
318
+ id: event.target?.id,
319
+ path: event.composedPath().filter((el) => Boolean(el.tagName)).map((el) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}`).reverse().join(">")
320
+ }
321
+ }));
322
+ };
323
+ const focusCallback = () => {
324
+ const now = /* @__PURE__ */ new Date();
325
+ setTimeout(() => observability.event({
326
+ identityId: getTelemetryIdentifier(client),
327
+ name: `${namespace}.window.focus`,
328
+ properties: {
329
+ href: window.location.href,
330
+ timeAway: now.getTime() - lastFocusEvent.getTime()
331
+ }
332
+ }));
333
+ lastFocusEvent = now;
334
+ };
335
+ const blurCallback = () => {
336
+ const now = /* @__PURE__ */ new Date();
337
+ const timeSpent = now.getTime() - lastFocusEvent.getTime();
338
+ setTimeout(() => observability.event({
339
+ identityId: getTelemetryIdentifier(client),
340
+ name: `${namespace}.window.blur`,
341
+ properties: {
342
+ href: window.location.href,
343
+ timeSpent
344
+ }
345
+ }));
346
+ lastFocusEvent = now;
347
+ totalTime = totalTime + timeSpent;
348
+ };
349
+ const unloadCallback = () => {
350
+ setTimeout(() => observability.event({
351
+ identityId: getTelemetryIdentifier(client),
352
+ name: `${namespace}.page.unload`,
353
+ properties: {
354
+ href: window.location.href,
355
+ timeSpent: totalTime
356
+ }
357
+ }));
358
+ };
359
+ const errorCallback = (event) => {
360
+ setTimeout(() => observability.event({
361
+ identityId: getTelemetryIdentifier(client),
362
+ name: `${namespace}.window.error`,
363
+ properties: {
364
+ href: window.location.href,
365
+ message: event.message,
366
+ filename: event.filename,
367
+ stack: event.error.stack
368
+ }
369
+ }));
370
+ };
371
+ window.addEventListener("click", clickCallback, true);
372
+ window.addEventListener("focus", focusCallback);
373
+ window.addEventListener("blur", blurCallback);
374
+ window.addEventListener("beforeunload", unloadCallback);
375
+ window.addEventListener("error", errorCallback);
376
+ return () => {
377
+ window.removeEventListener("click", clickCallback, true);
378
+ window.removeEventListener("focus", focusCallback);
379
+ window.removeEventListener("blur", blurCallback);
380
+ window.removeEventListener("beforeunload", unloadCallback);
381
+ window.removeEventListener("error", errorCallback);
382
+ };
383
+ };
384
+
385
+ // packages/sdk/observability/src/observability.ts
386
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/sdk/observability/src/observability.ts";
387
+ var SPACE_METRICS_MIN_INTERVAL = 1e3 * 60;
388
+ var SPACE_TELEMETRY_MIN_INTERVAL = 1e3 * 60 * 60;
389
+ var NETWORK_METRICS_MIN_INTERVAL = 1e3 * 60 * 5;
390
+ var Observability = class {
391
+ // TODO(nf): make platform a required extension?
392
+ constructor({ namespace, environment, release, config, secrets, group, mode, telemetry, errorLog }) {
393
+ // TODO(nf): accept upstream context?
394
+ this._ctx = new Context(void 0, {
395
+ F: __dxlog_file3,
396
+ L: 87
397
+ });
398
+ this._tags = /* @__PURE__ */ new Map();
399
+ this.addIPDataTelemetryTags = (ipData) => {
400
+ this.setTag("city", ipData.city, "telemetry");
401
+ this.setTag("region", ipData.region, "telemetry");
402
+ this.setTag("country", ipData.country, "telemetry");
403
+ ipData.latitude && this.setTag("latitude", ipData.latitude.toString(), "telemetry");
404
+ ipData.longitude && this.setTag("longitude", ipData.longitude.toString(), "telemetry");
405
+ };
406
+ this._namespace = namespace;
407
+ this._mode = mode;
408
+ this._config = config;
409
+ this._group = group;
410
+ this._secrets = this._loadSecrets(config, secrets);
411
+ this._telemetryBatchSize = telemetry?.batchSize ?? 30;
412
+ this._errorReportingOptions = errorLog?.sentryInitOptions;
413
+ if (this._group) {
414
+ this.setTag("group", this._group);
415
+ }
416
+ this.setTag("namespace", this._namespace);
417
+ environment && this.setTag("environment", environment);
418
+ release && this.setTag("release", release);
419
+ this.setTag("mode", this._mode);
420
+ }
421
+ get mode() {
422
+ return this._mode;
423
+ }
424
+ get group() {
425
+ return this._group;
426
+ }
427
+ get enabled() {
428
+ return this._mode !== "disabled";
429
+ }
430
+ _loadSecrets(config, secrets) {
431
+ if (isNode()) {
432
+ const mergedSecrets = {
433
+ ...cli_observability_secrets_default,
434
+ ...secrets
435
+ };
436
+ process.env.DX_ENVIRONMENT && (mergedSecrets.DX_ENVIRONMENT = process.env.DX_ENVIRONMENT);
437
+ process.env.DX_RELEASE && (mergedSecrets.DX_RELEASE = process.env.DX_RELEASE);
438
+ process.env.SENTRY_DESTINATION && (mergedSecrets.SENTRY_DESTINATION = process.env.SENTRY_DESTINATION);
439
+ process.env.TELEMETRY_API_KEY && (mergedSecrets.TELEMETRY_API_KEY = process.env.TELEMETRY_API_KEY);
440
+ process.env.IPDATA_API_KEY && (mergedSecrets.IPDATA_API_KEY = process.env.IPDATA_API_KEY);
441
+ process.env.DX_OTEL_ENDPOINT && (mergedSecrets.OTEL_ENDPOINT = process.env.DX_OTEL_ENDPOINT);
442
+ process.env.DX_OTEL_AUTHORIZATION && (mergedSecrets.OTEL_AUTHORIZATION = process.env.DX_OTEL_AUTHORIZATION);
443
+ return mergedSecrets;
444
+ } else {
445
+ log3("config", {
446
+ rtc: this._secrets,
447
+ config
448
+ }, {
449
+ F: __dxlog_file3,
450
+ L: 150,
451
+ S: this,
452
+ C: (f, a) => f(...a)
453
+ });
454
+ return {
455
+ DX_ENVIRONMENT: config?.get("runtime.app.env.DX_ENVIRONMENT"),
456
+ DX_RELEASE: config?.get("runtime.app.env.DX_RELEASE"),
457
+ SENTRY_DESTINATION: config?.get("runtime.app.env.DX_SENTRY_DESTINATION"),
458
+ TELEMETRY_API_KEY: config?.get("runtime.app.env.DX_TELEMETRY_API_KEY"),
459
+ IPDATA_API_KEY: config?.get("runtime.app.env.DX_IPDATA_API_KEY"),
460
+ OTEL_ENDPOINT: config?.get("runtime.app.env.DX_OTEL_ENDPOINT"),
461
+ OTEL_AUTHORIZATION: config?.get("runtime.app.env.DX_OTEL_AUTHORIZATION"),
462
+ ...secrets
463
+ };
464
+ }
465
+ }
466
+ async initialize() {
467
+ await this._initMetrics();
468
+ await this._initTelemetry();
469
+ await this._initErrorLogs();
470
+ await this._initTraces();
471
+ }
472
+ async close() {
473
+ const closes = [];
474
+ this._telemetry && closes.push(this._telemetry.close());
475
+ this._otelMetrics && closes.push(this._otelMetrics.close());
476
+ this._otelLogs && closes.push(this._otelLogs.close());
477
+ await Promise.all(closes);
478
+ await this._ctx.dispose();
479
+ }
480
+ setMode(mode) {
481
+ this._mode = mode;
482
+ }
483
+ //
484
+ // Tags
485
+ //
486
+ setTag(key, value, scope) {
487
+ if (this.enabled && (scope === void 0 || scope === "all" || scope === "errors")) {
488
+ this._setTag?.(key, value);
489
+ }
490
+ if (!scope) {
491
+ scope = "all";
492
+ }
493
+ this._tags.set(key, {
494
+ value,
495
+ scope
496
+ });
497
+ }
498
+ getTag(key) {
499
+ return this._tags.get(key);
500
+ }
501
+ // TODO(wittjosiah): Improve privacy of telemetry identifiers. See `getTelemetryIdentifier`.
502
+ async setIdentityTags(clientServices) {
503
+ if (clientServices.IdentityService) {
504
+ clientServices.IdentityService.queryIdentity().subscribe((idqr) => {
505
+ if (!idqr?.identity?.identityKey) {
506
+ log3("empty response from identity service", {
507
+ idqr
508
+ }, {
509
+ F: __dxlog_file3,
510
+ L: 218,
511
+ S: this,
512
+ C: (f, a) => f(...a)
513
+ });
514
+ return;
515
+ }
516
+ this.setTag("identityKey", idqr.identity.identityKey.truncate());
517
+ });
518
+ }
519
+ if (clientServices.DevicesService) {
520
+ clientServices.DevicesService.queryDevices().subscribe((dqr) => {
521
+ if (!dqr || !dqr.devices || dqr.devices.length === 0) {
522
+ log3("empty response from device service", {
523
+ device: dqr
524
+ }, {
525
+ F: __dxlog_file3,
526
+ L: 228,
527
+ S: this,
528
+ C: (f, a) => f(...a)
529
+ });
530
+ return;
531
+ }
532
+ invariant(dqr, "empty response from device service", {
533
+ F: __dxlog_file3,
534
+ L: 231,
535
+ S: this,
536
+ A: [
537
+ "dqr",
538
+ "'empty response from device service'"
539
+ ]
540
+ });
541
+ const thisDevice = dqr.devices.find((device) => device.kind === DeviceKind.CURRENT);
542
+ if (!thisDevice) {
543
+ log3("no current device", {
544
+ device: dqr
545
+ }, {
546
+ F: __dxlog_file3,
547
+ L: 235,
548
+ S: this,
549
+ C: (f, a) => f(...a)
550
+ });
551
+ return;
552
+ }
553
+ this.setTag("deviceKey", thisDevice.deviceKey.truncate());
554
+ if (thisDevice.profile?.label) {
555
+ this.setTag("deviceProfile", thisDevice.profile.label);
556
+ }
557
+ });
558
+ }
559
+ }
560
+ //
561
+ // Metrics
562
+ //
563
+ async _initMetrics() {
564
+ if (this.enabled && this._secrets.OTEL_ENDPOINT && this._secrets.OTEL_AUTHORIZATION) {
565
+ const { OtelMetrics } = await import("./otel-YI7HAFOG.mjs");
566
+ this._otelMetrics = new OtelMetrics({
567
+ endpoint: this._secrets.OTEL_ENDPOINT,
568
+ authorizationHeader: this._secrets.OTEL_AUTHORIZATION,
569
+ serviceName: this._namespace,
570
+ serviceVersion: this.getTag("release")?.value ?? "0.0.0",
571
+ getTags: () => Object.fromEntries(Array.from(this._tags).filter(([key, value]) => {
572
+ return value.scope === "all" || value.scope === "metrics";
573
+ }).map(([key, value]) => [
574
+ key,
575
+ value.value
576
+ ]))
577
+ });
578
+ log3("otel metrics enabled", void 0, {
579
+ F: __dxlog_file3,
580
+ L: 267,
581
+ S: this,
582
+ C: (f, a) => f(...a)
583
+ });
584
+ } else {
585
+ log3("otel metrics disabled", void 0, {
586
+ F: __dxlog_file3,
587
+ L: 269,
588
+ S: this,
589
+ C: (f, a) => f(...a)
590
+ });
591
+ }
592
+ }
593
+ /**
594
+ * Gauge metric.
595
+ *
596
+ * The default implementation uses OpenTelemetry
597
+ */
598
+ gauge(name, value, extraTags) {
599
+ this._otelMetrics?.gauge(name, value, extraTags);
600
+ }
601
+ // TODO(nf): Refactor into ObservabilityExtensions.
602
+ startNetworkMetrics(clientServices) {
603
+ if (!clientServices.NetworkService) {
604
+ return;
605
+ }
606
+ const updateSignalMetrics = new Event().debounce(NETWORK_METRICS_MIN_INTERVAL);
607
+ updateSignalMetrics.on(this._ctx, async () => {
608
+ log3("send signal metrics", void 0, {
609
+ F: __dxlog_file3,
610
+ L: 291,
611
+ S: this,
612
+ C: (f, a) => f(...a)
613
+ });
614
+ (this._lastNetworkStatus?.signaling).forEach(({ server, state }) => {
615
+ this.gauge("dxos.client.network.signal.connectionState", state, {
616
+ server
617
+ });
618
+ });
619
+ let swarmCount = 0;
620
+ const connectionStates = /* @__PURE__ */ new Map();
621
+ for (const state in ConnectionState) {
622
+ connectionStates.set(state, 0);
623
+ }
624
+ let totalReadBufferSize = 0;
625
+ let totalWriteBufferSize = 0;
626
+ let totalChannelBufferSize = 0;
627
+ this._lastNetworkStatus?.connectionInfo?.forEach((connectionInfo) => {
628
+ swarmCount++;
629
+ for (const conn of connectionInfo.connections ?? []) {
630
+ connectionStates.set(conn.state, (connectionStates.get(conn.state) ?? 0) + 1);
631
+ totalReadBufferSize += conn.readBufferSize ?? 0;
632
+ totalWriteBufferSize += conn.writeBufferSize ?? 0;
633
+ for (const stream of conn.streams ?? []) {
634
+ totalChannelBufferSize += stream.writeBufferSize ?? 0;
635
+ }
636
+ }
637
+ this.gauge("dxos.client.network.swarm.count", swarmCount);
638
+ for (const state in ConnectionState) {
639
+ this.gauge("dxos.client.network.connection.count", connectionStates.get(state) ?? 0, {
640
+ state
641
+ });
642
+ }
643
+ this.gauge("dxos.client.network.totalReadBufferSize", totalReadBufferSize);
644
+ this.gauge("dxos.client.network.totalWriteBufferSize", totalWriteBufferSize);
645
+ this.gauge("dxos.client.network.totalChannelBufferSize", totalChannelBufferSize);
646
+ });
647
+ });
648
+ clientServices.NetworkService.queryStatus().subscribe((networkStatus) => {
649
+ this._lastNetworkStatus = networkStatus;
650
+ updateSignalMetrics.emit();
651
+ });
652
+ scheduleTaskInterval(this._ctx, async () => updateSignalMetrics.emit(), NETWORK_METRICS_MIN_INTERVAL);
653
+ }
654
+ startSpacesMetrics(client, namespace) {
655
+ const spaces = client.spaces.get();
656
+ const subscriptions = /* @__PURE__ */ new Map();
657
+ this._ctx.onDispose(() => subscriptions.forEach((subscription) => subscription.unsubscribe()));
658
+ const updateSpaceMetrics = new Event().debounce(SPACE_METRICS_MIN_INTERVAL);
659
+ updateSpaceMetrics.on(this._ctx, async () => {
660
+ log3("send space metrics", void 0, {
661
+ F: __dxlog_file3,
662
+ L: 345,
663
+ S: this,
664
+ C: (f, a) => f(...a)
665
+ });
666
+ for (const data of mapSpaces(spaces, {
667
+ truncateKeys: true
668
+ })) {
669
+ this.gauge("dxos.client.space.members", data.members, {
670
+ key: data.key
671
+ });
672
+ this.gauge("dxos.client.space.objects", data.objects, {
673
+ key: data.key
674
+ });
675
+ this.gauge("dxos.client.space.epoch", data.epoch, {
676
+ key: data.key
677
+ });
678
+ this.gauge("dxos.client.space.currentDataMutations", data.currentDataMutations, {
679
+ key: data.key
680
+ });
681
+ }
682
+ });
683
+ const updateSpaceTelemetry = new Event().debounce(SPACE_TELEMETRY_MIN_INTERVAL);
684
+ updateSpaceTelemetry.on(this._ctx, async () => {
685
+ log3("send space telemetry", void 0, {
686
+ F: __dxlog_file3,
687
+ L: 356,
688
+ S: this,
689
+ C: (f, a) => f(...a)
690
+ });
691
+ for (const data of mapSpaces(spaces, {
692
+ truncateKeys: true
693
+ })) {
694
+ this.event({
695
+ identityId: getTelemetryIdentifier(client),
696
+ name: `${namespace}.space.update`,
697
+ properties: data
698
+ });
699
+ }
700
+ });
701
+ const subscribeToSpaceUpdate = (space) => space.pipeline.subscribe({
702
+ next: () => {
703
+ updateSpaceMetrics.emit();
704
+ updateSpaceTelemetry.emit();
705
+ }
706
+ });
707
+ spaces.forEach((space) => {
708
+ subscriptions.set(space.key.toHex(), subscribeToSpaceUpdate(space));
709
+ });
710
+ client.spaces.subscribe({
711
+ next: async (spaces2) => {
712
+ spaces2.filter((space) => !subscriptions.has(space.key.toHex())).forEach((space) => {
713
+ subscriptions.set(space.key.toHex(), subscribeToSpaceUpdate(space));
714
+ });
715
+ }
716
+ });
717
+ scheduleTaskInterval(this._ctx, async () => updateSpaceMetrics.emit(), NETWORK_METRICS_MIN_INTERVAL);
718
+ }
719
+ async startRuntimeMetrics(client, frequency = NETWORK_METRICS_MIN_INTERVAL) {
720
+ const platform = await client.services.services.SystemService?.getPlatform();
721
+ invariant(platform, "platform is required", {
722
+ F: __dxlog_file3,
723
+ L: 393,
724
+ S: this,
725
+ A: [
726
+ "platform",
727
+ "'platform is required'"
728
+ ]
729
+ });
730
+ this.setTag("platform_type", Platform.PLATFORM_TYPE[platform.type].toLowerCase());
731
+ if (this._mode === "full") {
732
+ if (platform.platform) {
733
+ this.setTag("platform", platform.platform);
734
+ }
735
+ if (platform.arch) {
736
+ this.setTag("arch", platform.arch);
737
+ }
738
+ if (platform.runtime) {
739
+ this.setTag("runtime", platform.runtime);
740
+ }
741
+ }
742
+ scheduleTaskInterval(this._ctx, async () => {
743
+ if (client.services.constructor.name === "WorkerClientServices") {
744
+ const memory = window.performance.memory;
745
+ if (memory) {
746
+ this.gauge("dxos.client.runtime.heapTotal", memory.totalJSHeapSize);
747
+ this.gauge("dxos.client.runtime.heapUsed", memory.usedJSHeapSize);
748
+ this.gauge("dxos.client.runtime.heapSizeLimit", memory.jsHeapSizeLimit);
749
+ }
750
+ }
751
+ client.services.services.SystemService?.getPlatform().then((platform2) => {
752
+ if (platform2.memory) {
753
+ this.gauge("dxos.client.services.runtime.rss", platform2.memory.rss);
754
+ this.gauge("dxos.client.services.runtime.heapTotal", platform2.memory.heapTotal);
755
+ this.gauge("dxos.client.services.runtime.heapUsed", platform2.memory.heapUsed);
756
+ }
757
+ }).catch((error) => log3("platform error", {
758
+ error
759
+ }, {
760
+ F: __dxlog_file3,
761
+ L: 428,
762
+ S: this,
763
+ C: (f, a) => f(...a)
764
+ }));
765
+ }, frequency);
766
+ }
767
+ //
768
+ // Telemetry
769
+ //
770
+ async _initTelemetry() {
771
+ if (this._secrets.TELEMETRY_API_KEY && this._mode !== "disabled") {
772
+ const { SegmentTelemetry } = await import("./segment/index.mjs");
773
+ this._telemetry = new SegmentTelemetry({
774
+ apiKey: this._secrets.TELEMETRY_API_KEY,
775
+ batchSize: this._telemetryBatchSize,
776
+ getTags: () => Object.fromEntries(Array.from(this._tags).filter(([key, value]) => {
777
+ return value.scope === "all" || value.scope === "telemetry";
778
+ }).map(([key, value]) => [
779
+ key,
780
+ value.value
781
+ ]))
782
+ });
783
+ } else {
784
+ log3("segment disabled", void 0, {
785
+ F: __dxlog_file3,
786
+ L: 454,
787
+ S: this,
788
+ C: (f, a) => f(...a)
789
+ });
790
+ }
791
+ }
792
+ /**
793
+ * A telemetry event.
794
+ *
795
+ * The default implementation uses Segment.
796
+ */
797
+ event(options) {
798
+ this._telemetry?.event(options);
799
+ }
800
+ /**
801
+ * A telemetry page view.
802
+ *
803
+ * The default implementation uses Segment.
804
+ */
805
+ page(options) {
806
+ this._telemetry?.page(options);
807
+ }
808
+ //
809
+ // Error Logs
810
+ //
811
+ async _initErrorLogs() {
812
+ if (this._secrets.SENTRY_DESTINATION && this._mode !== "disabled") {
813
+ const { captureException, captureUserFeedback, init, setTag } = await import("./sentry/index.mjs");
814
+ const { SentryLogProcessor } = await import("./sentry-log-processor-JYJH3AMG.mjs");
815
+ this._captureException = captureException;
816
+ this._captureUserFeedback = captureUserFeedback;
817
+ this._setTag = setTag;
818
+ log3.info("Initializing Sentry", {
819
+ dest: this._secrets.SENTRY_DESTINATION,
820
+ options: this._errorReportingOptions
821
+ }, {
822
+ F: __dxlog_file3,
823
+ L: 490,
824
+ S: this,
825
+ C: (f, a) => f(...a)
826
+ });
827
+ this._sentryLogProcessor = new SentryLogProcessor();
828
+ init({
829
+ ...this._errorReportingOptions,
830
+ destination: this._secrets.SENTRY_DESTINATION,
831
+ scrubFilenames: this._mode !== "full",
832
+ onError: (event) => this._sentryLogProcessor.addLogBreadcrumbsTo(event)
833
+ });
834
+ this._tags.forEach((v, k) => {
835
+ if (v.scope === "all" || v.scope === "errors") {
836
+ setTag(k, v.value);
837
+ }
838
+ });
839
+ } else {
840
+ log3("sentry disabled", void 0, {
841
+ F: __dxlog_file3,
842
+ L: 510,
843
+ S: this,
844
+ C: (f, a) => f(...a)
845
+ });
846
+ }
847
+ if (this._secrets.OTEL_ENDPOINT && this._secrets.OTEL_AUTHORIZATION && this._mode !== "disabled") {
848
+ const { OtelLogs } = await import("./otel-YI7HAFOG.mjs");
849
+ this._otelLogs = new OtelLogs({
850
+ endpoint: this._secrets.OTEL_ENDPOINT,
851
+ authorizationHeader: this._secrets.OTEL_AUTHORIZATION,
852
+ serviceName: this._namespace,
853
+ serviceVersion: this.getTag("release")?.value ?? "0.0.0",
854
+ getTags: () => Object.fromEntries(Array.from(this._tags).filter(([key, value]) => {
855
+ return value.scope === "all" || value.scope === "errors";
856
+ }).map(([key, value]) => [
857
+ key,
858
+ value.value
859
+ ]))
860
+ });
861
+ log3("otel logs enabled", {
862
+ namespace: this._namespace
863
+ }, {
864
+ F: __dxlog_file3,
865
+ L: 529,
866
+ S: this,
867
+ C: (f, a) => f(...a)
868
+ });
869
+ } else {
870
+ log3("otel logs disabled", void 0, {
871
+ F: __dxlog_file3,
872
+ L: 531,
873
+ S: this,
874
+ C: (f, a) => f(...a)
875
+ });
876
+ }
877
+ }
878
+ startErrorLogs() {
879
+ this._sentryLogProcessor && log3.runtimeConfig.processors.push(this._sentryLogProcessor.logProcessor);
880
+ this._otelLogs && log3.runtimeConfig.processors.push(this._otelLogs.logProcessor);
881
+ }
882
+ startTraces() {
883
+ this._otelTraces && this._otelTraces.start();
884
+ }
885
+ // TODO(nf): refactor init based on providers and their capabilities
886
+ async _initTraces() {
887
+ if (this._secrets.OTEL_ENDPOINT && this._secrets.OTEL_AUTHORIZATION && this._mode !== "disabled") {
888
+ const { OtelTraces } = await import("./otel-YI7HAFOG.mjs");
889
+ this._otelTraces = new OtelTraces({
890
+ endpoint: this._secrets.OTEL_ENDPOINT,
891
+ authorizationHeader: this._secrets.OTEL_AUTHORIZATION,
892
+ serviceName: this._namespace,
893
+ serviceVersion: this.getTag("release")?.value ?? "0.0.0",
894
+ getTags: () => Object.fromEntries(Array.from(this._tags).filter(([key, value]) => {
895
+ return value.scope === "all" || value.scope === "metrics";
896
+ }).map(([key, value]) => [
897
+ key,
898
+ value.value
899
+ ]))
900
+ });
901
+ }
902
+ }
903
+ /**
904
+ * Manually capture an exception.
905
+ *
906
+ * The default implementation uses Sentry.
907
+ */
908
+ captureException(err) {
909
+ if (this.enabled) {
910
+ this._captureException?.(err);
911
+ }
912
+ }
913
+ /**
914
+ * Manually capture user feedback.
915
+ *
916
+ * The default implementation uses Sentry.
917
+ */
918
+ captureUserFeedback(name, email, message) {
919
+ void this._captureUserFeedback?.(name, email, message);
920
+ }
921
+ };
922
+
923
+ export {
924
+ Observability,
925
+ OBSERVABILITY_DISABLED_KEY,
926
+ OBSERVABILITY_GROUP_KEY,
927
+ isObservabilityDisabled,
928
+ storeObservabilityDisabled,
929
+ getObservabilityGroup,
930
+ storeObservabilityGroup,
931
+ initializeAppObservability,
932
+ getTelemetryIdentifier,
933
+ showObservabilityBanner,
934
+ getObservabilityState,
935
+ initializeNodeObservability,
936
+ mapSpaces,
937
+ setupTelemetryListeners
938
+ };
939
+ //# sourceMappingURL=chunk-BHETLWXO.mjs.map