@dxos/observability 0.6.13 → 0.6.14-main.69511f5

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