@dxos/observability 0.6.13 → 0.6.14-main.7bd9c89

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