@dxos/observability 0.3.11-main.e19f39d → 0.3.11-main.e28df4f

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 (55) hide show
  1. package/dist/lib/browser/chunk-ROSK6U3K.mjs +83 -0
  2. package/dist/lib/browser/chunk-ROSK6U3K.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-STWCJK52.mjs +748 -0
  4. package/dist/lib/browser/chunk-STWCJK52.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +28 -553
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/observability-XIDFB6PJ.mjs +10 -0
  9. package/dist/lib/browser/observability-XIDFB6PJ.mjs.map +7 -0
  10. package/dist/lib/browser/segment/index.mjs +8 -0
  11. package/dist/lib/browser/segment/index.mjs.map +7 -0
  12. package/dist/lib/node/chunk-ARUBPK2W.cjs +170 -0
  13. package/dist/lib/node/chunk-ARUBPK2W.cjs.map +7 -0
  14. package/dist/lib/node/chunk-DE7OVD7T.cjs +769 -0
  15. package/dist/lib/node/chunk-DE7OVD7T.cjs.map +7 -0
  16. package/dist/lib/node/index.cjs +26 -602
  17. package/dist/lib/node/index.cjs.map +4 -4
  18. package/dist/lib/node/meta.json +1 -1
  19. package/dist/lib/node/observability-YMIQHLME.cjs +32 -0
  20. package/dist/lib/node/observability-YMIQHLME.cjs.map +7 -0
  21. package/dist/lib/node/segment/index.cjs +30 -0
  22. package/dist/lib/node/segment/index.cjs.map +7 -0
  23. package/dist/types/src/helpers/app-observability.d.ts +19 -0
  24. package/dist/types/src/helpers/app-observability.d.ts.map +1 -0
  25. package/dist/types/src/helpers/app-observability.js +195 -0
  26. package/dist/types/src/helpers/app-observability.js.map +1 -0
  27. package/dist/types/src/helpers/index.d.ts +4 -0
  28. package/dist/types/src/helpers/index.d.ts.map +1 -0
  29. package/dist/types/src/helpers/index.js +23 -0
  30. package/dist/types/src/helpers/index.js.map +1 -0
  31. package/dist/types/src/{util.d.ts → helpers/map-spaces.d.ts} +2 -3
  32. package/dist/types/src/helpers/map-spaces.d.ts.map +1 -0
  33. package/dist/types/src/{util.js → helpers/map-spaces.js} +1 -2
  34. package/dist/types/src/helpers/map-spaces.js.map +1 -0
  35. package/dist/types/src/helpers/setup-telemetry-listeners.d.ts +4 -0
  36. package/dist/types/src/helpers/setup-telemetry-listeners.d.ts.map +1 -0
  37. package/dist/types/src/helpers/setup-telemetry-listeners.js +96 -0
  38. package/dist/types/src/helpers/setup-telemetry-listeners.js.map +1 -0
  39. package/dist/types/src/index.d.ts +1 -0
  40. package/dist/types/src/index.d.ts.map +1 -1
  41. package/dist/types/src/index.js +1 -0
  42. package/dist/types/src/index.js.map +1 -1
  43. package/dist/types/src/observability.d.ts +3 -4
  44. package/dist/types/src/observability.d.ts.map +1 -1
  45. package/dist/types/src/observability.js +26 -25
  46. package/dist/types/src/observability.js.map +1 -1
  47. package/package.json +15 -14
  48. package/src/helpers/app-observability.ts +205 -0
  49. package/src/helpers/index.ts +7 -0
  50. package/src/{util.ts → helpers/map-spaces.ts} +1 -2
  51. package/src/helpers/setup-telemetry-listeners.ts +115 -0
  52. package/src/index.ts +1 -0
  53. package/src/observability.ts +26 -24
  54. package/dist/types/src/util.d.ts.map +0 -1
  55. package/dist/types/src/util.js.map +0 -1
@@ -0,0 +1,769 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var chunk_DE7OVD7T_exports = {};
30
+ __export(chunk_DE7OVD7T_exports, {
31
+ BASE_TELEMETRY_PROPERTIES: () => BASE_TELEMETRY_PROPERTIES,
32
+ OBSERVABILITY_DISABLED_KEY: () => OBSERVABILITY_DISABLED_KEY,
33
+ OBSERVABILITY_GROUP_KEY: () => OBSERVABILITY_GROUP_KEY,
34
+ Observability: () => Observability,
35
+ getObservabilityGroup: () => getObservabilityGroup,
36
+ getTelemetryIdentifier: () => getTelemetryIdentifier,
37
+ initializeAppObservability: () => initializeAppObservability,
38
+ isObservabilityDisabled: () => isObservabilityDisabled,
39
+ mapSpaces: () => mapSpaces,
40
+ setupTelemetryListeners: () => setupTelemetryListeners,
41
+ storeObservabilityDisabled: () => storeObservabilityDisabled,
42
+ storeObservabilityGroup: () => storeObservabilityGroup
43
+ });
44
+ module.exports = __toCommonJS(chunk_DE7OVD7T_exports);
45
+ var import_chunk_VDBBIYH6 = require("./chunk-VDBBIYH6.cjs");
46
+ var import_chunk_ARUBPK2W = require("./chunk-ARUBPK2W.cjs");
47
+ var import_chunk_FSAOBKO2 = require("./chunk-FSAOBKO2.cjs");
48
+ var import_async = require("@dxos/async");
49
+ var import_context = require("@dxos/context");
50
+ var import_invariant = require("@dxos/invariant");
51
+ var import_log = require("@dxos/log");
52
+ var import_network_manager = require("@dxos/network-manager");
53
+ var import_services = require("@dxos/protocols/proto/dxos/client/services");
54
+ var import_util = require("@dxos/util");
55
+ var localForage = __toESM(require("localforage"));
56
+ var import_log2 = require("@dxos/log");
57
+ var cli_observability_secrets_default = {
58
+ SENTRY_DESTINATION: "https://2647916221e643869965e78469479aa4@o4504012000067584.ingest.sentry.io/4504012027265029",
59
+ TELEMETRY_API_KEY: "B00QG6PtJJrJ0VVFe0H5a6bcUUShKyZM",
60
+ IPDATA_API_KEY: "73dfdecdf979c18f07d50cf841bbdd9e589f237256326ac8cca23786",
61
+ DATADOG_API_KEY: null,
62
+ DATADOG_APP_KEY: null
63
+ };
64
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/observability/src/helpers/app-observability.ts";
65
+ var BASE_TELEMETRY_PROPERTIES = {};
66
+ var OBSERVABILITY_DISABLED_KEY = "telemetry-disabled";
67
+ var OBSERVABILITY_GROUP_KEY = "telemetry-group";
68
+ if (typeof navigator !== "undefined" && navigator.storage?.estimate) {
69
+ setInterval(async () => {
70
+ try {
71
+ const storageEstimate = await navigator.storage.estimate();
72
+ BASE_TELEMETRY_PROPERTIES.storageUsage = storageEstimate.usage;
73
+ BASE_TELEMETRY_PROPERTIES.storageQuota = storageEstimate.quota;
74
+ } catch (error) {
75
+ import_log2.log.warn("Failed to run estimate()", error, {
76
+ F: __dxlog_file,
77
+ L: 27,
78
+ S: void 0,
79
+ C: (f, a) => f(...a)
80
+ });
81
+ }
82
+ }, 1e4);
83
+ }
84
+ var getTelemetryIdentifier = (client) => {
85
+ if (!client?.initialized) {
86
+ return void 0;
87
+ }
88
+ const identity = client.halo.identity.get();
89
+ if (identity) {
90
+ return identity.identityKey.truncate();
91
+ }
92
+ return void 0;
93
+ };
94
+ var isObservabilityDisabled = async (namespace) => {
95
+ try {
96
+ return await localForage.getItem(`${namespace}:${OBSERVABILITY_DISABLED_KEY}`) === "true";
97
+ } catch (err) {
98
+ import_log2.log.catch("Failed to check if observability is disabled, assuming it is", err, {
99
+ F: __dxlog_file,
100
+ L: 54,
101
+ S: void 0,
102
+ C: (f, a) => f(...a)
103
+ });
104
+ return true;
105
+ }
106
+ };
107
+ var storeObservabilityDisabled = async (namespace, value) => {
108
+ try {
109
+ await localForage.setItem(`${namespace}:${OBSERVABILITY_DISABLED_KEY}`, String(value));
110
+ } catch (err) {
111
+ import_log2.log.catch("Failed to store observability disabled", err, {
112
+ F: __dxlog_file,
113
+ L: 63,
114
+ S: void 0,
115
+ C: (f, a) => f(...a)
116
+ });
117
+ }
118
+ };
119
+ var getObservabilityGroup = async (namespace) => {
120
+ try {
121
+ return await localForage.getItem(`${namespace}:${OBSERVABILITY_GROUP_KEY}`) ?? void 0;
122
+ } catch (err) {
123
+ import_log2.log.catch("Failed to get observability group", err, {
124
+ F: __dxlog_file,
125
+ L: 71,
126
+ S: void 0,
127
+ C: (f, a) => f(...a)
128
+ });
129
+ }
130
+ };
131
+ var storeObservabilityGroup = async (namespace, value) => {
132
+ try {
133
+ await localForage.setItem(`${namespace}:${OBSERVABILITY_GROUP_KEY}`, value);
134
+ } catch (err) {
135
+ import_log2.log.catch("Failed to store observability group", err, {
136
+ F: __dxlog_file,
137
+ L: 79,
138
+ S: void 0,
139
+ C: (f, a) => f(...a)
140
+ });
141
+ }
142
+ };
143
+ var initializeAppObservability = async ({ namespace, config, mode = "basic", tracingEnable = true, replayEnable = true }) => {
144
+ (0, import_log2.log)("initializeAppObservability", {
145
+ config
146
+ }, {
147
+ F: __dxlog_file,
148
+ L: 104,
149
+ S: void 0,
150
+ C: (f, a) => f(...a)
151
+ });
152
+ const group = await getObservabilityGroup(namespace) ?? void 0;
153
+ const release = `${namespace}@${config.get("runtime.app.build.version")}`;
154
+ const environment = config.get("runtime.app.env.DX_ENVIRONMENT");
155
+ BASE_TELEMETRY_PROPERTIES.group = group;
156
+ BASE_TELEMETRY_PROPERTIES.release = release;
157
+ BASE_TELEMETRY_PROPERTIES.environment = environment;
158
+ const observabilityDisabled = await isObservabilityDisabled(namespace);
159
+ const { Observability: Observability2 } = await import("./observability-YMIQHLME.cjs");
160
+ const observability = new Observability2({
161
+ namespace,
162
+ group,
163
+ mode,
164
+ config,
165
+ errorLog: {
166
+ sentryInitOptions: {
167
+ environment,
168
+ release,
169
+ tracing: tracingEnable,
170
+ replay: replayEnable,
171
+ // TODO(wittjosiah): Configure these.
172
+ sampleRate: 1,
173
+ replaySampleRate: 0.1,
174
+ replaySampleRateOnError: 1
175
+ }
176
+ }
177
+ });
178
+ if (observabilityDisabled) {
179
+ observability.setMode("disabled");
180
+ import_log2.log.info("observability disabled", void 0, {
181
+ F: __dxlog_file,
182
+ L: 147,
183
+ S: void 0,
184
+ C: (f, a) => f(...a)
185
+ });
186
+ return observability;
187
+ }
188
+ try {
189
+ const getIPData = async (config2) => {
190
+ const IP_DATA_CACHE_TIMEOUT = 6 * 60 * 60 * 1e3;
191
+ const cachedData = await localForage.getItem("dxos:telemetry:ipdata");
192
+ if (cachedData && cachedData.timestamp > Date.now() - IP_DATA_CACHE_TIMEOUT) {
193
+ return cachedData.data;
194
+ }
195
+ const IPDATA_API_KEY = config2.get("runtime.app.env.DX_IPDATA_API_KEY");
196
+ if (IPDATA_API_KEY) {
197
+ return fetch(`https://api.ipdata.co?api-key=${IPDATA_API_KEY}`).then((res) => res.json()).then((data) => {
198
+ localForage.setItem("dxos:telemetry:ipdata", {
199
+ data,
200
+ timestamp: Date.now()
201
+ }).catch((err) => observability.captureException(err));
202
+ return data;
203
+ }).catch((err) => observability.captureException(err));
204
+ }
205
+ };
206
+ const ipData = await getIPData(config);
207
+ if (ipData && ipData.city) {
208
+ BASE_TELEMETRY_PROPERTIES.city = ipData.city;
209
+ BASE_TELEMETRY_PROPERTIES.region = ipData.region;
210
+ BASE_TELEMETRY_PROPERTIES.country = ipData.country;
211
+ BASE_TELEMETRY_PROPERTIES.latitude = ipData.latitude;
212
+ BASE_TELEMETRY_PROPERTIES.longitude = ipData.longitude;
213
+ }
214
+ observability.initialize();
215
+ } catch (err) {
216
+ import_log2.log.error("Failed to initialize app observability", err, {
217
+ F: __dxlog_file,
218
+ L: 201,
219
+ S: void 0,
220
+ C: (f, a) => f(...a)
221
+ });
222
+ }
223
+ return observability;
224
+ };
225
+ var mapSpaces = (spaces, options = {
226
+ verbose: false,
227
+ truncateKeys: false
228
+ }) => {
229
+ return spaces.map((space) => {
230
+ const { open, ready } = space.internal.data.metrics ?? {};
231
+ const startup = open && ready && ready.getTime() - open.getTime();
232
+ const pipeline = space.internal.data.pipeline;
233
+ const startDataMutations = pipeline?.currentEpoch?.subject.assertion.timeframe.totalMessages() ?? 0;
234
+ const epoch = pipeline?.currentEpoch?.subject.assertion.number;
235
+ const currentDataMutations = pipeline?.currentDataTimeframe?.totalMessages() ?? 0;
236
+ const totalDataMutations = pipeline?.targetDataTimeframe?.totalMessages() ?? 0;
237
+ return {
238
+ // TODO(nf): truncate keys for DD?
239
+ key: space.key.truncate(),
240
+ open: space.isOpen,
241
+ members: space.members.get().length,
242
+ objects: space.db.query().objects.length,
243
+ startup,
244
+ epoch,
245
+ // appliedEpoch,
246
+ startDataMutations,
247
+ currentDataMutations,
248
+ totalDataMutations,
249
+ // TODO(burdon): Negative?
250
+ progress: (Math.min(Math.abs((currentDataMutations - startDataMutations) / (totalDataMutations - startDataMutations)), 1) * 100).toFixed(0)
251
+ };
252
+ });
253
+ };
254
+ var lastFocusEvent = /* @__PURE__ */ new Date();
255
+ var totalTime = 0;
256
+ var setupTelemetryListeners = (namespace, client, observability) => {
257
+ const clickCallback = (event) => {
258
+ if (BASE_TELEMETRY_PROPERTIES.group === "dxos" && event.target && !event.target.id) {
259
+ console.warn("Click event on element without id:", event.target);
260
+ }
261
+ setTimeout(() => observability.event({
262
+ identityId: getTelemetryIdentifier(client),
263
+ name: `${namespace}.window.click`,
264
+ properties: {
265
+ ...BASE_TELEMETRY_PROPERTIES,
266
+ href: window.location.href,
267
+ id: event.target?.id,
268
+ path: event.path?.filter((el) => Boolean(el.tagName)).map((el) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}`).reverse().join(">")
269
+ }
270
+ }));
271
+ };
272
+ const focusCallback = () => {
273
+ const now = /* @__PURE__ */ new Date();
274
+ setTimeout(() => observability.event({
275
+ identityId: getTelemetryIdentifier(client),
276
+ name: `${namespace}.window.focus`,
277
+ properties: {
278
+ ...BASE_TELEMETRY_PROPERTIES,
279
+ href: window.location.href,
280
+ timeAway: now.getTime() - lastFocusEvent.getTime()
281
+ }
282
+ }));
283
+ lastFocusEvent = now;
284
+ };
285
+ const blurCallback = () => {
286
+ const now = /* @__PURE__ */ new Date();
287
+ const timeSpent = now.getTime() - lastFocusEvent.getTime();
288
+ setTimeout(() => observability.event({
289
+ identityId: getTelemetryIdentifier(client),
290
+ name: `${namespace}.window.blur`,
291
+ properties: {
292
+ ...BASE_TELEMETRY_PROPERTIES,
293
+ href: window.location.href,
294
+ timeSpent
295
+ }
296
+ }));
297
+ lastFocusEvent = now;
298
+ totalTime = totalTime + timeSpent;
299
+ };
300
+ const unloadCallback = () => {
301
+ setTimeout(() => observability.event({
302
+ identityId: getTelemetryIdentifier(client),
303
+ name: `${namespace}.page.unload`,
304
+ properties: {
305
+ ...BASE_TELEMETRY_PROPERTIES,
306
+ href: window.location.href,
307
+ timeSpent: totalTime
308
+ }
309
+ }));
310
+ };
311
+ const errorCallback = (event) => {
312
+ setTimeout(() => observability.event({
313
+ identityId: getTelemetryIdentifier(client),
314
+ name: `${namespace}.window.error`,
315
+ properties: {
316
+ ...BASE_TELEMETRY_PROPERTIES,
317
+ href: window.location.href,
318
+ message: event.message,
319
+ filename: event.filename,
320
+ stack: event.error.stack
321
+ }
322
+ }));
323
+ };
324
+ window.addEventListener("click", clickCallback, true);
325
+ window.addEventListener("focus", focusCallback);
326
+ window.addEventListener("blur", blurCallback);
327
+ window.addEventListener("beforeunload", unloadCallback);
328
+ window.addEventListener("error", errorCallback);
329
+ return () => {
330
+ window.removeEventListener("click", clickCallback, true);
331
+ window.removeEventListener("focus", focusCallback);
332
+ window.removeEventListener("blur", blurCallback);
333
+ window.removeEventListener("beforeunload", unloadCallback);
334
+ window.removeEventListener("error", errorCallback);
335
+ };
336
+ };
337
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/sdk/observability/src/observability.ts";
338
+ var SPACE_METRICS_MIN_INTERVAL = 1e3 * 60;
339
+ var DATADOG_IDLE_INTERVAL = 1e3 * 60 * 1;
340
+ var ERROR_TAGS = [
341
+ "identityKey",
342
+ "username",
343
+ "deviceKey",
344
+ "group"
345
+ ];
346
+ var Observability = class {
347
+ // TODO(nf): make platform a required extension?
348
+ constructor({ namespace, config, secrets, group, mode, telemetry, errorLog }) {
349
+ this._mode = "disabled";
350
+ this._ctx = new import_context.Context();
351
+ this._tags = /* @__PURE__ */ new Map();
352
+ this._namespace = namespace;
353
+ this._config = config;
354
+ this._mode = mode ?? "disabled";
355
+ this._group = group;
356
+ this._secrets = this._loadSecrets(config, secrets);
357
+ this._telemetryBatchSize = telemetry?.batchSize ?? 30;
358
+ this._errorReportingOptions = errorLog?.sentryInitOptions;
359
+ this._errorLogProcessor = errorLog?.logProcessor ?? false;
360
+ if (this._group) {
361
+ this.setTag("group", this._group);
362
+ }
363
+ this.setTag("namespace", this._namespace);
364
+ if (this._mode === "full") {
365
+ }
366
+ }
367
+ _loadSecrets(config, secrets) {
368
+ if ((0, import_util.isNode)()) {
369
+ return cli_observability_secrets_default;
370
+ } else {
371
+ (0, import_invariant.invariant)(config, "runtime config is required", {
372
+ F: __dxlog_file2,
373
+ L: 117,
374
+ S: this,
375
+ A: [
376
+ "config",
377
+ "'runtime config is required'"
378
+ ]
379
+ });
380
+ (0, import_log.log)("config", {
381
+ rtc: this._secrets,
382
+ config
383
+ }, {
384
+ F: __dxlog_file2,
385
+ L: 118,
386
+ S: this,
387
+ C: (f, a) => f(...a)
388
+ });
389
+ return {
390
+ DX_ENVIRONMENT: config.get("runtime.app.env.DX_ENVIRONMENT"),
391
+ DX_RELEASE: config.get("runtime.app.env.DX_RELEASE"),
392
+ SENTRY_DESTINATION: config.get("runtime.app.env.DX_SENTRY_DESTINATION"),
393
+ TELEMETRY_API_KEY: config.get("runtime.app.env.DX_TELEMETRY_API_KEY"),
394
+ IPDATA_API_KEY: config.get("runtime.app.env.DX_IPDATA_API_KEY"),
395
+ DATADOG_API_KEY: config.get("runtime.app.env.DX_DATADOG_API_KEY"),
396
+ DATADOG_APP_KEY: config.get("runtime.app.env.DX_DATADOG_APP_KEY"),
397
+ ...secrets
398
+ };
399
+ }
400
+ }
401
+ initialize() {
402
+ this._initMetrics();
403
+ this._initTelemetry();
404
+ this._initErrorLogs();
405
+ }
406
+ async close() {
407
+ await this._ctx.dispose();
408
+ }
409
+ setMode(mode) {
410
+ this._mode = mode;
411
+ }
412
+ get mode() {
413
+ return this._mode;
414
+ }
415
+ get enabled() {
416
+ return this._mode !== "disabled";
417
+ }
418
+ //
419
+ // Tags
420
+ //
421
+ /**
422
+ * Set a tag for all observability services.
423
+ */
424
+ setTag(key, value) {
425
+ if (this.enabled && ERROR_TAGS.includes(key)) {
426
+ (0, import_chunk_FSAOBKO2.setTag)(key, value);
427
+ }
428
+ this._tags.set(key, value);
429
+ }
430
+ // TODO(wittjosiah): Improve privacy of telemetry identifiers. See `getTelemetryIdentifier`.
431
+ async setIdentityTags(client) {
432
+ client.services.services.IdentityService.queryIdentity().subscribe((idqr) => {
433
+ if (!idqr?.identity?.identityKey) {
434
+ (0, import_log.log)("empty response from identity service", {
435
+ idqr
436
+ }, {
437
+ F: __dxlog_file2,
438
+ L: 175,
439
+ S: this,
440
+ C: (f, a) => f(...a)
441
+ });
442
+ return;
443
+ }
444
+ this.setTag("identityKey", idqr.identity.identityKey.truncate());
445
+ });
446
+ client.services.services.DevicesService.queryDevices().subscribe((dqr) => {
447
+ if (!dqr || !dqr.devices || dqr.devices.length === 0) {
448
+ (0, import_log.log)("empty response from device service", {
449
+ device: dqr
450
+ }, {
451
+ F: __dxlog_file2,
452
+ L: 184,
453
+ S: this,
454
+ C: (f, a) => f(...a)
455
+ });
456
+ return;
457
+ }
458
+ (0, import_invariant.invariant)(dqr, "empty response from device service", {
459
+ F: __dxlog_file2,
460
+ L: 187,
461
+ S: this,
462
+ A: [
463
+ "dqr",
464
+ "'empty response from device service'"
465
+ ]
466
+ });
467
+ const thisDevice = dqr.devices.find((device) => device.kind === import_services.DeviceKind.CURRENT);
468
+ if (!thisDevice) {
469
+ (0, import_log.log)("no current device", {
470
+ device: dqr
471
+ }, {
472
+ F: __dxlog_file2,
473
+ L: 191,
474
+ S: this,
475
+ C: (f, a) => f(...a)
476
+ });
477
+ return;
478
+ }
479
+ this.setTag("deviceKey", thisDevice.deviceKey.truncate());
480
+ if (thisDevice.profile?.label) {
481
+ this.setTag("deviceProfile", thisDevice.profile.label);
482
+ }
483
+ });
484
+ }
485
+ //
486
+ // Metrics
487
+ //
488
+ _initMetrics() {
489
+ if (this.enabled && this._secrets.DATADOG_API_KEY) {
490
+ this._metrics = new import_chunk_VDBBIYH6.DatadogMetrics({
491
+ apiKey: this._secrets.DATADOG_API_KEY,
492
+ getTags: () => this._tags,
493
+ // TODO(nf): move/refactor from telementryContext, needed to read CORS proxy
494
+ config: this._config
495
+ });
496
+ } else {
497
+ (0, import_log.log)("datadog disabled", void 0, {
498
+ F: __dxlog_file2,
499
+ L: 214,
500
+ S: this,
501
+ C: (f, a) => f(...a)
502
+ });
503
+ }
504
+ }
505
+ /**
506
+ * Gauge metric.
507
+ *
508
+ * The default implementation uses Datadog.
509
+ */
510
+ gauge(name, value, extraTags) {
511
+ this._metrics?.gauge(name, value, extraTags);
512
+ }
513
+ // TODO(nf): Refactor into ObservabilityExtensions.
514
+ startNetworkMetrics(client) {
515
+ const updateSignalMetrics = new import_async.Event();
516
+ updateSignalMetrics.on(this._ctx, async (networkStatus) => {
517
+ (0, import_log.log)("send signal metrics", void 0, {
518
+ F: __dxlog_file2,
519
+ L: 234,
520
+ S: this,
521
+ C: (f, a) => f(...a)
522
+ });
523
+ networkStatus.signaling.forEach(({ server, state }) => {
524
+ this.gauge("dxos.client.network.signal.connectionState", state, {
525
+ server
526
+ });
527
+ });
528
+ let swarmCount = 0;
529
+ const connectionStates = /* @__PURE__ */ new Map();
530
+ for (const state in import_network_manager.ConnectionState) {
531
+ connectionStates.set(state, 0);
532
+ }
533
+ let totalReadBufferSize = 0;
534
+ let totalWriteBufferSize = 0;
535
+ let totalChannelBufferSize = 0;
536
+ networkStatus.connectionInfo?.forEach((connectionInfo) => {
537
+ swarmCount++;
538
+ for (const conn of connectionInfo.connections ?? []) {
539
+ connectionStates.set(conn.state, (connectionStates.get(conn.state) ?? 0) + 1);
540
+ totalReadBufferSize += conn.readBufferSize ?? 0;
541
+ totalWriteBufferSize += conn.writeBufferSize ?? 0;
542
+ for (const stream of conn.streams ?? []) {
543
+ totalChannelBufferSize += stream.writeBufferSize ?? 0;
544
+ }
545
+ }
546
+ this.gauge("dxos.client.network.swarm.count", swarmCount);
547
+ for (const state in import_network_manager.ConnectionState) {
548
+ this.gauge("dxos.client.network.connection.count", connectionStates.get(state) ?? 0, {
549
+ state
550
+ });
551
+ }
552
+ this.gauge("dxox.client.network.totalReadBufferSize", totalReadBufferSize);
553
+ this.gauge("dxos.client.network.totalWriteBufferSize", totalWriteBufferSize);
554
+ this.gauge("dxos.client.network.totalChannelBufferSize", totalChannelBufferSize);
555
+ });
556
+ });
557
+ client.services.services.NetworkService?.queryStatus().subscribe((networkStatus) => {
558
+ updateSignalMetrics.emit(networkStatus);
559
+ });
560
+ }
561
+ startSpacesMetrics(client, namespace) {
562
+ const spaces = client.spaces.get();
563
+ const subscriptions = /* @__PURE__ */ new Map();
564
+ this._ctx.onDispose(() => subscriptions.forEach((subscription) => subscription.unsubscribe()));
565
+ const updateSpaceMetrics = new import_async.Event().debounce(SPACE_METRICS_MIN_INTERVAL);
566
+ updateSpaceMetrics.on(this._ctx, async () => {
567
+ (0, import_log.log)("send space update", void 0, {
568
+ F: __dxlog_file2,
569
+ L: 286,
570
+ S: this,
571
+ C: (f, a) => f(...a)
572
+ });
573
+ for (const data of mapSpaces(spaces, {
574
+ truncateKeys: true
575
+ })) {
576
+ this.gauge("dxos.client.space.members", data.members, {
577
+ key: data.key
578
+ });
579
+ this.gauge("dxos.client.space.objects", data.objects, {
580
+ key: data.key
581
+ });
582
+ this.gauge("dxos.client.space.epoch", data.epoch, {
583
+ key: data.key
584
+ });
585
+ this.gauge("dxos.client.space.currentDataMutations", data.currentDataMutations, {
586
+ key: data.key
587
+ });
588
+ this.event({
589
+ identityId: getTelemetryIdentifier(client),
590
+ name: `${namespace}.space.update`,
591
+ properties: {
592
+ ...BASE_TELEMETRY_PROPERTIES,
593
+ ...data
594
+ }
595
+ });
596
+ }
597
+ });
598
+ const subscribeToSpaceUpdate = (space) => space.pipeline.subscribe({
599
+ next: () => {
600
+ updateSpaceMetrics.emit();
601
+ }
602
+ });
603
+ spaces.forEach((space) => {
604
+ subscriptions.set(space.key.toHex(), subscribeToSpaceUpdate(space));
605
+ });
606
+ client.spaces.subscribe({
607
+ next: async (spaces2) => {
608
+ spaces2.filter((space) => !subscriptions.has(space.key.toHex())).forEach((space) => {
609
+ subscriptions.set(space.key.toHex(), subscribeToSpaceUpdate(space));
610
+ });
611
+ }
612
+ });
613
+ (0, import_async.scheduleTaskInterval)(this._ctx, async () => updateSpaceMetrics.emit(), DATADOG_IDLE_INTERVAL);
614
+ }
615
+ async startRuntimeMetrics(client, frequency = DATADOG_IDLE_INTERVAL) {
616
+ const platform = await client.services.services.SystemService?.getPlatform();
617
+ (0, import_invariant.invariant)(platform, "platform is required", {
618
+ F: __dxlog_file2,
619
+ L: 332,
620
+ S: this,
621
+ A: [
622
+ "platform",
623
+ "'platform is required'"
624
+ ]
625
+ });
626
+ this.setTag("platform_type", import_services.Platform.PLATFORM_TYPE[platform.type].toLowerCase());
627
+ if (this._mode === "full") {
628
+ if (platform.platform) {
629
+ this.setTag("platform", platform.platform);
630
+ }
631
+ if (platform.arch) {
632
+ this.setTag("arch", platform.arch);
633
+ }
634
+ if (platform.runtime) {
635
+ this.setTag("runtime", platform.runtime);
636
+ }
637
+ }
638
+ (0, import_async.scheduleTaskInterval)(this._ctx, async () => {
639
+ (0, import_log.log)("platform", void 0, {
640
+ F: __dxlog_file2,
641
+ L: 350,
642
+ S: this,
643
+ C: (f, a) => f(...a)
644
+ });
645
+ client.services.services.SystemService?.getPlatform().then((platform2) => {
646
+ (0, import_log.log)("platform", {
647
+ platform: platform2
648
+ }, {
649
+ F: __dxlog_file2,
650
+ L: 353,
651
+ S: this,
652
+ C: (f, a) => f(...a)
653
+ });
654
+ if (platform2.memory) {
655
+ this.gauge("dxos.client.runtime.rss", platform2.memory.rss);
656
+ this.gauge("dxos.client.runtime.heapTotal", platform2.memory.heapTotal);
657
+ this.gauge("dxos.client.runtime.heapUsed", platform2.memory.heapUsed);
658
+ }
659
+ }).catch((error) => (0, import_log.log)("platform error", {
660
+ error
661
+ }, {
662
+ F: __dxlog_file2,
663
+ L: 360,
664
+ S: this,
665
+ C: (f, a) => f(...a)
666
+ }));
667
+ }, frequency);
668
+ }
669
+ //
670
+ // Telemetry
671
+ //
672
+ _initTelemetry() {
673
+ if (this._secrets.TELEMETRY_API_KEY && this._mode !== "disabled") {
674
+ this._telemetry = new import_chunk_ARUBPK2W.SegmentTelemetry({
675
+ apiKey: this._secrets.TELEMETRY_API_KEY,
676
+ batchSize: this._telemetryBatchSize,
677
+ getTags: () => this._tags
678
+ });
679
+ } else {
680
+ (0, import_log.log)("segment disabled", void 0, {
681
+ F: __dxlog_file2,
682
+ L: 378,
683
+ S: this,
684
+ C: (f, a) => f(...a)
685
+ });
686
+ }
687
+ }
688
+ /**
689
+ * A telemetry event.
690
+ *
691
+ * The default implementation uses Segment.
692
+ */
693
+ event(options) {
694
+ this._telemetry?.event(options);
695
+ }
696
+ /**
697
+ * A telemetry page view.
698
+ *
699
+ * The default implementation uses Segment.
700
+ */
701
+ page(options) {
702
+ this._telemetry?.page(options);
703
+ }
704
+ //
705
+ // Error Logs
706
+ //
707
+ _initErrorLogs() {
708
+ if (this._secrets.SENTRY_DESTINATION && this._mode !== "disabled") {
709
+ import_log.log.info("Initializing Sentry", {
710
+ dest: this._secrets.SENTRY_DESTINATION,
711
+ options: this._errorReportingOptions
712
+ }, {
713
+ F: __dxlog_file2,
714
+ L: 407,
715
+ S: this,
716
+ C: (f, a) => f(...a)
717
+ });
718
+ (0, import_chunk_FSAOBKO2.init)({
719
+ ...this._errorReportingOptions,
720
+ destination: this._secrets.SENTRY_DESTINATION,
721
+ scrubFilenames: this._mode !== "full"
722
+ });
723
+ if (this._errorReportingOptions?.tracing) {
724
+ (0, import_chunk_FSAOBKO2.configureTracing)();
725
+ }
726
+ if (this._errorLogProcessor) {
727
+ (0, import_chunk_FSAOBKO2.enableSentryLogProcessor)();
728
+ }
729
+ this._tags.forEach((v, k) => {
730
+ if (ERROR_TAGS.includes(k)) {
731
+ (0, import_chunk_FSAOBKO2.setTag)(k, v);
732
+ }
733
+ });
734
+ } else {
735
+ (0, import_log.log)("sentry disabled", void 0, {
736
+ F: __dxlog_file2,
737
+ L: 430,
738
+ S: this,
739
+ C: (f, a) => f(...a)
740
+ });
741
+ }
742
+ }
743
+ /**
744
+ * Manually capture an exception.
745
+ *
746
+ * The default implementation uses Sentry.
747
+ */
748
+ captureException(err) {
749
+ if (this.enabled) {
750
+ (0, import_chunk_FSAOBKO2.captureException)(err);
751
+ }
752
+ }
753
+ };
754
+ // Annotate the CommonJS export names for ESM import in node:
755
+ 0 && (module.exports = {
756
+ BASE_TELEMETRY_PROPERTIES,
757
+ OBSERVABILITY_DISABLED_KEY,
758
+ OBSERVABILITY_GROUP_KEY,
759
+ Observability,
760
+ getObservabilityGroup,
761
+ getTelemetryIdentifier,
762
+ initializeAppObservability,
763
+ isObservabilityDisabled,
764
+ mapSpaces,
765
+ setupTelemetryListeners,
766
+ storeObservabilityDisabled,
767
+ storeObservabilityGroup
768
+ });
769
+ //# sourceMappingURL=chunk-DE7OVD7T.cjs.map