From 032c331e1bd5f6ac1ebd4acf082a029eba6de4ac Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 20 Oct 2026 12:44:53 +0500 Subject: [PATCH 1/3] feat(trackers): domain ConnectivityTracker supersedes per-signal ConnectionTracker (TR3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per-window singleton owning online/offline + navigator.connection listeners; stages online/networkInfo/state; rebind merge semantics; connection trace unchanged plus link_downstream_max_kbps. ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/browser-connectivity-tracker.md | 6 + docs/PROGRESS.md | 3 +- packages/browser/src/launch.test.ts | 45 +- .../src/trace-producers.sensors.test.ts | 37 +- packages/browser/src/trace-producers.ts | 38 +- .../src/trackers/connection-tracker.test.ts | 210 --------- .../src/trackers/connection-tracker.ts | 127 ----- packages/trackers/README.md | 2 +- .../src/browser/connectivity-tracker.test.ts | 441 ++++++++++++++++++ .../src/browser/connectivity-tracker.ts | 257 ++++++++++ packages/trackers/src/browser/index.ts | 10 + packages/trackers/src/index.test.ts | 3 + packages/webview/src/launch.test.ts | 5 +- 13 files changed, 810 insertions(+), 374 deletions(-) create mode 100644 .changeset/browser-connectivity-tracker.md delete mode 100644 packages/browser/src/trackers/connection-tracker.test.ts delete mode 100644 packages/browser/src/trackers/connection-tracker.ts create mode 100644 packages/trackers/src/browser/connectivity-tracker.test.ts create mode 100644 packages/trackers/src/browser/connectivity-tracker.ts diff --git a/.changeset/browser-connectivity-tracker.md b/.changeset/browser-connectivity-tracker.md new file mode 100644 index 00000000..937d58d7 --- /dev/null +++ b/.changeset/browser-connectivity-tracker.md @@ -0,0 +1,6 @@ +--- +'@bugsee/browser': minor +'@bugsee/trackers': minor +--- + +Browser system traces: the `connection` trace gains `link_downstream_max_kbps` (from `NetworkInformation.downlinkMax`; omitted when the browser reports no usable value). Zero/non-finite `downlink` and `rtt` readings are now omitted instead of sent as 0. Connectivity is now served by a per-window singleton `ConnectivityTracker` (in the `@bugsee/trackers/browser` entry) that owns the `online`/`offline` and `navigator.connection` listeners and exposes `online`, `networkInfo` and `state` notifications. The trace name and the existing fields are unchanged. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 78eaf496..8512e150 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -18,7 +18,7 @@ Read this first; then `docs/design/sdk-design.md` (Draft v3) for the full archit | `@bugsee/logger` | Debug logger (`debug.warn` etc.); platforms route `onError` here. | | `@bugsee/protocol` | Wire types (`RequestJson`, `EnvironmentEnvelope`, `NetworkEvent` superset incl. `'http'` mechanism, `NetworkStage`, `FileType`, `Mechanism`), `Severity` enum + level conversions, header/JSON/params sanitizers, shape redaction, **`BugseeOption` canonical identifiers + `optionsToWire` (dots โ†’ colons)**. | | `@bugsee/service` | The DI/IoC container: `createServiceContainer`/`defineService`/`Provider` (Firebase-component model, LAZY/EXPLICIT, lazy resolution, deps-via-container, `onInit`, late registration). The backbone of the **internal aggregated object** (see DI note below). | -| `@bugsee/trackers` | Tracker foundation below core (core imports + re-exports): `MultiKeyEmitterBase`/`createMultiKeyEmitter`, `Interceptor`/`EventSubscribable`, `InterceptorBase`, `createTrackerRegistry` (per-window singletons, `rebind`). Portable root; platform subpaths `./browser` (`PowerTracker`, `powerTrackerFor`, `resetPowerTracker`, `hostRead`), plus reserved empty `./node` and `./electron`. | +| `@bugsee/trackers` | Tracker foundation below core (core imports + re-exports): `MultiKeyEmitterBase`/`createMultiKeyEmitter`, `Interceptor`/`EventSubscribable`, `InterceptorBase`, `createTrackerRegistry` (per-window singletons, `rebind`). Portable root; platform subpaths `./browser` (`PowerTracker`, `powerTrackerFor`, `resetPowerTracker`, `ConnectivityTracker`, `connectivityTrackerFor`, `resetConnectivityTracker`, `hostRead`), plus reserved empty `./node` and `./electron`. | ### Kernel โ€” `@bugsee/core` (the thin kernel; runtime-portable) - **`Client`** (`createClient`) โ€” composition root: identity/attributes via the single global `Environment`, manual capture (`addBreadcrumb`/`log`/`event`/`trace`/`logException`), provider/extension registration, lifecycle (`launch`/`isLaunched`/`stop`/`flush`). `flush()`/`stop()` await both `uploadPipeline.flush` AND in-flight **report promises** (the path that lets crash flush-then-exit deliver), bounded by an unref'd deadline. **Identity reaches the wire (audit fix A):** `setUserIdentifier` โ†’ `request.json.email` at assemble time (Android maps the user identifier to the `email` field โ€” "email from global scope"; no separate `user` field, no `setEmail`). **Internal object / DI (Phase 1, `docs/design/internal-object-di.md`):** the Client now owns a per-process `ServiceContainer` (the "BugseeInternal" โ€” the internal aggregated object); `addService`/`getService`/`getServiceProvider` (a typed `ServiceToken` facade over the generic `@bugsee/service` container โ€” see ยง7 "DI token migration") + `getInternal(carrier)` reach it process-wide via the singleton client. **Phase 2 (delivers E) โ€” redaction filters as the first real service:** a `filters` service (`FilterStore`) registered in the container; the facade `setNetworkEventFilter`/`setLogEventFilter`/`setBreadcrumbFilter`/`setReportHandler` mutate it; the capture pipeline (network/log providers, `addBreadcrumb`, the report path) reads it LIVE via `getFilters()` (the singleton client on the carrier). Filter = mutate or return null to DROP; a throwing filter drops (privacy-safe) + one `onError`. The user network filter REPLACES the built-in sanitizer (Android XOR); the default sanitizer is now gated on `CaptureNetworkDefaultSanitizer`. Report `before` mutates/vetoes before assembly. **Phase 3 (COMPLETE) โ€” every platform seam is a container service, resolved by a typed `ServiceToken`:** Node `launch` creates the `ServiceContainer`, registers the HTTP `transport` (and the rest of the seams), resolves it to build the pipeline, and hands the SAME container to `createClient`; the client exposes `getService(TransportToken)`. Behavior-preserving (the `internalTagged`/override path is unchanged). The full token set, the `ServiceToken` migration (replacing the old `NameServiceMapping` declaration-merge), and the carrier-hosted service-manifest auto-registration path are in ยง7 "DI Phase 3 / token migration". **Lifecycle (audit fix B):** `logException` after `stop()` is a silent no-op (ยง1501) until re-launch (a `stopped` flag distinct from `!launched`, so pre-launch capture is unaffected). **Kill-state (audit fix D, ยง1435/ยง1504; REVISED โ€” see the note below):** the collector's `KILL_SDK` code (`99099`) โ€” and ONLY that โ€” sets `BugseeError.fatal`, which `track()` observes on any report result and which flips the client PERMANENTLY dead: one-time `onError`, capture+detection halt, all capture/`logException` no-op, and `launch()` won't re-arm a killed client. **An HTTP 401/403 no longer kills the client.** It used to, on the theory that a 401/403 on session create meant an invalid app token โ€” but the collector never answers that way: the appserver returns HTTP **200** with an envelope error code (`error.router.js:50` calls `res.code(200)` unconditionally), so an invalid token arrives as code `14019`, which classifies as `permanent` (drop this bundle) and not as `kill_sdk`. A raw 401/403 is therefore an infrastructure answer โ€” a proxy, a WAF, an expiring session mid-upload โ€” and killing the SDK on one silently ended capture for the rest of the process. It is now RETRYABLE. The collector-code namespace (`classifyServerErrorCode`, `transport.ts`) is disjoint from HTTP statuses and is the only thing that carries a control verdict; `BugseeError.code` is the HTTP status (`0` when no response was reached) and `BugseeError.serverCode` is the collector code. @@ -405,6 +405,7 @@ solid), in slices: its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the connection/orientation trackers subscribe to it. - **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible โ€” loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first) and optional `screen_size`. - **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism. +- **TR3 (DONE, `feat/connectivity-tracker`):** the per-signal `ConnectionTracker` (and its test) is deleted; the domain **`ConnectivityTracker`** (`packages/trackers/src/browser/connectivity-tracker.ts`, `connectivityTrackerFor(env, onError)`, `resetConnectivityTracker`) is a per-window singleton via the registry (keyed on `env.window`, else `env.navigator`, else the env object) with `rebind` (latest `onError` wins; a defined `window`/`navigator` replaces ours, a partial env never drops them; a RUNNING tracker moves its listeners to a changed window/navigator and re-reads). It owns ALL connectivity listeners (window `online`/`offline` + `navigator.connection` `change`) and does NOT depend on the page-lifecycle tracker. Stages: `online` `{online}`, `networkInfo` `{type?, effectiveType?, downlink?, downlinkMax?, rtt?, saveData?}` and the aggregate `state` `{online, networkInfo?}`; activation emits a baseline of every stage. Fields are omitted when absent/invalid; zero/non-finite `downlink`/`downlinkMax`/`rtt` count as "no estimate" (Chromium reports 0 offline) and are omitted, `saveData` only when boolean. Every host read goes through `hostRead` (a hostile getter costs only its field; reported; a throwing `onError` never escapes). **Retention:** there is no cached snapshot to lose: state lives in `navigator`, which the tracker keeps and READS LIVE (`current()` and a fresh baseline on each activation); only the listeners are released on the last unsubscribe. `ConnectionProducer` is rewired onto it with UNCHANGED trace name/wire (`connection`: `type`, `effective_type`, `link_downstream_kbps`, `rtt`, `save_data`); `downlinkMax` is added to the open trace data as `link_downstream_max_kbps` (the connection trace is a free-form object with no schema, so this is additive). Consequence: `online`/`offline` are now bound twice on a window while capturing (the lifecycle tracker still serves the events source; the connectivity tracker owns its own), until the Application tracker absorbs the events source. - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index 8668860b..e2fa286c 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -42,6 +42,7 @@ import { type RequestJson, Severity, } from '@bugsee/protocol'; +import { connectivityTrackerFor } from '@bugsee/trackers/browser'; import { strFromU8, unzipSync } from '@bugsee/util'; import { IDBFactory } from 'fake-indexeddb'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -479,8 +480,10 @@ describe('launch', () => { systemMetricsSampler: undefined, }), ); - // traces (connection/orientation) AND the events source are both live, yet each type is bound once - expect(w.count('online')).toBe(1); + // traces (orientation) AND the events source share ONE lifecycle tracker (a single orientationchange listener); + // online/offline are bound twice: once by that lifecycle tracker (events) and once by the domain + // ConnectivityTracker, which owns its own connectivity listeners and does not depend on the lifecycle tracker. + expect(w.count('online')).toBe(2); expect(w.count('orientationchange')).toBe(1); doc.emit('visibilitychange', {}); const names = ((await drain(store, 'events.system')) ?? []).map( @@ -1326,8 +1329,9 @@ describe('launch', () => { // the system-events source listens on the same window, so isolate the trace trackers noSampler({ window: w.win, captureStore: memStore(), captureSystemEvents: false }), ); - expect(w.count('online')).toBe(1); - expect(w.count('offline')).toBe(1); + // online/offline: the shared lifecycle tracker (orientation) + the ConnectivityTracker's own listeners + expect(w.count('online')).toBe(2); + expect(w.count('offline')).toBe(2); expect(w.count('orientationchange')).toBe(1); await client.stop(); expect(w.count('online')).toBe(0); @@ -1335,6 +1339,39 @@ describe('launch', () => { expect(w.count('orientationchange')).toBe(0); }); + it('launch goes through the per-window ConnectivityTracker singleton: a second consumer shares its listeners, and downlinkMax reaches the trace', async () => { + vi.stubGlobal('navigator', { + onLine: true, + connection: { type: 'wifi', downlink: 10, downlinkMax: 100 }, + }); + const w = fakeWindow(); + const store = memStore(); + const client = await launchTracked( + 'tok', + noSampler({ window: w.win, captureStore: store, captureSystemEvents: false }), + ); + const before = w.count('online'); // lifecycle tracker + the connectivity tracker + // The singleton for this window is the one launch subscribed through: a new `ConnectivityTracker` would add + // another pair of window listeners here instead of sharing the first. + const off = connectivityTrackerFor({ window: w.win }).on('online', () => {}); + expect(w.count('online')).toBe(before); + off(); + expect(w.count('online')).toBe(before); // launch's own subscription still holds it + const rows = new Map( + ((await drain(store, 'traces.system')) ?? []).map((e) => { + const d = e.data as { name: string; value: unknown }; + return [d.name, d.value]; + }), + ); + expect(rows.get('connection')).toMatchObject({ + type: 'wifi', + link_downstream_kbps: 10_000, + link_downstream_max_kbps: 100_000, + }); + await client.stop(); + expect(w.count('online')).toBe(0); + }); + it('with captureSystemTraces:false no sensor listener is attached and no timer is started', async () => { stubSensors(); const w = fakeWindow(); diff --git a/packages/browser/src/trace-producers.sensors.test.ts b/packages/browser/src/trace-producers.sensors.test.ts index 4a286876..b32a602f 100644 --- a/packages/browser/src/trace-producers.sensors.test.ts +++ b/packages/browser/src/trace-producers.sensors.test.ts @@ -1,4 +1,5 @@ import type { TraceProducer } from '@bugsee/capture'; +import { ConnectivityTracker } from '@bugsee/trackers/browser'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { AdvertisedMemoryProducer, @@ -7,7 +8,6 @@ import { MemoryProducer, OrientationProducer, } from './trace-producers'; -import { ConnectionTracker } from './trackers/connection-tracker'; import { MemoryTracker } from './trackers/memory-tracker'; import { OrientationTracker } from './trackers/orientation-tracker'; @@ -133,10 +133,17 @@ describe('AdvertisedMemoryProducer', () => { describe('ConnectionProducer', () => { it('emits a TRANSPORT type the viewer can render, with effectiveType kept as detail', () => { // `type` must be a CONNECTION_STATES key; it used to carry effectiveType ('4g'), in no table. - const t = new ConnectionTracker({ + const t = new ConnectivityTracker({ navigator: { onLine: true, - connection: { type: 'wifi', effectiveType: '4g', downlink: 10, rtt: 50, saveData: false }, + connection: { + type: 'wifi', + effectiveType: '4g', + downlink: 10, + downlinkMax: 100, + rtt: 50, + saveData: false, + }, }, }); expect(startAll([new ConnectionProducer(t)]).out).toEqual([ @@ -146,6 +153,7 @@ describe('ConnectionProducer', () => { type: 'wifi', effective_type: '4g', link_downstream_kbps: 10_000, // downlink is Mbps; Android reports kbps + link_downstream_max_kbps: 100_000, rtt: 50, save_data: false, }, @@ -157,7 +165,7 @@ describe('ConnectionProducer', () => { const win = mkTarget(); const nav = { onLine: true, connection: { type: 'wifi' } }; const { out } = startAll([ - new ConnectionProducer(new ConnectionTracker({ window: win, navigator: nav })), + new ConnectionProducer(new ConnectivityTracker({ window: win, navigator: nav })), ]); nav.onLine = false; win.fire('offline'); @@ -166,7 +174,7 @@ describe('ConnectionProducer', () => { it('still emits (type unknown) with NO NetworkInformation, because onLine alone is worth a row', () => { expect( - startAll([new ConnectionProducer(new ConnectionTracker({ navigator: { onLine: true } }))]) + startAll([new ConnectionProducer(new ConnectivityTracker({ navigator: { onLine: true } }))]) .out, ).toEqual([{ name: 'connection', value: { type: 'unknown' } }]); }); @@ -175,7 +183,7 @@ describe('ConnectionProducer', () => { const win = mkTarget(); const nav = { onLine: true }; const { out } = startAll([ - new ConnectionProducer(new ConnectionTracker({ window: win, navigator: nav })), + new ConnectionProducer(new ConnectivityTracker({ window: win, navigator: nav })), ]); win.fire('online'); expect(out).toHaveLength(1); @@ -184,15 +192,28 @@ describe('ConnectionProducer', () => { expect(out).toHaveLength(2); }); + it('producers built twice from one window share ONE connectivity tracker (one listener pair)', () => { + const win = mkTarget(); + const nav = { onLine: true }; + const pick = () => + named(createBrowserSystemTraceProducers({ window: win, navigator: nav }), ['connection']); + const a = startAll(pick()); + const b = startAll(pick()); + expect(win.count()).toBe(2); // ONE online + offline pair, shared; a per-producer tracker would make it 4 + a.stop(); + b.stop(); + expect(win.count()).toBe(0); + }); + it('emits nothing with no navigator at all', () => { - expect(startAll([new ConnectionProducer(new ConnectionTracker({}))]).out).toEqual([]); + expect(startAll([new ConnectionProducer(new ConnectivityTracker({}))]).out).toEqual([]); }); it('stop() releases the tracker listeners and late events write nothing', () => { const win = mkTarget(); const nav = { onLine: true }; const { out, stop } = startAll([ - new ConnectionProducer(new ConnectionTracker({ window: win, navigator: nav })), + new ConnectionProducer(new ConnectivityTracker({ window: win, navigator: nav })), ]); stop(); expect(win.count()).toBe(0); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 44482f61..8355069f 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -4,15 +4,13 @@ import { type BatteryEnv, type BatteryManagerLike, type BatteryState, + type ConnectivityState, + type ConnectivityTracker, + connectivityTrackerFor, type PowerTracker, powerTrackerFor, } from '@bugsee/trackers/browser'; import { chargingToWire, connectionTypeToWire, orientationToWire } from './system-trace-values'; -import { - type ConnectionEnv, - type ConnectionState, - ConnectionTracker, -} from './trackers/connection-tracker'; import { type FpsEnv, FpsTracker } from './trackers/fps-tracker'; import { type MemoryReading, type MemoryState, MemoryTracker } from './trackers/memory-tracker'; import { @@ -136,10 +134,10 @@ export class AdvertisedMemoryProducer extends TraceProducerBase { export class ConnectionProducer extends TraceProducerBase { readonly name = 'connection'; - readonly #tracker: ConnectionTracker; + readonly #tracker: ConnectivityTracker; #off: (() => void) | undefined; - constructor(tracker: ConnectionTracker) { + constructor(tracker: ConnectivityTracker) { super(); this.#tracker = tracker; } @@ -155,9 +153,9 @@ export class ConnectionProducer extends TraceProducerBase { this.#off = undefined; } - #publish({ onLine, connection }: ConnectionState): void { + #publish({ online, networkInfo: connection }: ConnectivityState): void { this.emitIfChanged('connection', { - type: connectionTypeToWire(connection, onLine), + type: connectionTypeToWire(connection, online), // Everything below is DETAIL (the viewer renders `item.data`), so it is omitted rather than sent // as undefined โ€” an explicitly absent key is what the other tiers send. ...(connection?.effectiveType !== undefined @@ -167,6 +165,10 @@ export class ConnectionProducer extends TraceProducerBase { ...(connection?.downlink !== undefined ? { link_downstream_kbps: Math.round(connection.downlink * 1000) } : {}), + // `downlinkMax` (the link's ceiling, Mbps) rides the same unit; the key is additive detail on the open object. + ...(connection?.downlinkMax !== undefined + ? { link_downstream_max_kbps: Math.round(connection.downlinkMax * 1000) } + : {}), ...(connection?.rtt !== undefined ? { rtt: connection.rtt } : {}), ...(connection?.saveData !== undefined ? { save_data: connection.saveData } : {}), }); @@ -267,13 +269,16 @@ export class FpsProducer extends TraceProducerBase { */ export interface BrowserTraceEnv extends BatteryEnv { performance?: { readonly memory?: MemoryReading; now?(): number }; - navigator?: ConnectionEnv['navigator'] & { + navigator?: { /** `navigator.deviceMemory` in GiB โ€” a coarse bucket, not a measurement. */ readonly deviceMemory?: number; + readonly onLine?: boolean; + /** NetworkInformation (read by the ConnectivityTracker). */ + readonly connection?: object; }; screen?: OrientationEnv['screen']; /** Source of `online` / `offline` / `orientationchange`. */ - window?: ConnectionEnv['window']; + window?: OrientationEnv['window']; /** The document the SDK is bound to: visibility for `app_state` and `fps`. */ document?: FpsEnv['document']; /** `window.requestAnimationFrame` / `cancelAnimationFrame` (bound to that window): drive `fps`. */ @@ -415,16 +420,7 @@ export function createBrowserSystemTraceProducers( }), ), new AdvertisedMemoryProducer(() => nav?.deviceMemory), - new ConnectionProducer( - new ConnectionTracker( - { - ...(env.lifecycle !== undefined ? { lifecycle: env.lifecycle } : {}), - ...(env.window !== undefined ? { window: env.window } : {}), - ...(nav !== undefined ? { navigator: nav } : {}), - }, - onError, - ), - ), + new ConnectionProducer(connectivityTrackerFor(env, onError)), new OrientationProducer( new OrientationTracker( { diff --git a/packages/browser/src/trackers/connection-tracker.test.ts b/packages/browser/src/trackers/connection-tracker.test.ts deleted file mode 100644 index 06fcc5da..00000000 --- a/packages/browser/src/trackers/connection-tracker.test.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { ConnectionTracker } from './connection-tracker'; -import { PageLifecycleTracker } from './page-lifecycle-tracker'; - -function mkTarget() { - const l = new Map void>>(); - return { - addEventListener: (t: string, f: () => void) => { - const s = l.get(t) ?? new Set<() => void>(); - s.add(f); - l.set(t, s); - }, - removeEventListener: (t: string, f: () => void) => void l.get(t)?.delete(f), - fire: (t: string) => - l.get(t)?.forEach((f) => { - f(); - }), - count: () => [...l.values()].reduce((n, s) => n + s.size, 0), - }; -} - -describe('ConnectionTracker', () => { - it('attaches nothing until the first subscriber', () => { - const win = mkTarget(); - const connection = mkTarget(); - new ConnectionTracker({ window: win, navigator: { onLine: true, connection } }); - expect(win.count() + connection.count()).toBe(0); - }); - - it('listens to online/offline on the window and change on navigator.connection; releases all on the last unsubscribe', () => { - const win = mkTarget(); - const connection = mkTarget(); - const t = new ConnectionTracker({ window: win, navigator: { onLine: true, connection } }); - const offA = t.on('state', () => {}); - const offB = t.on('state', () => {}); - expect(win.count()).toBe(2); - expect(connection.count()).toBe(1); - offA(); - expect(win.count() + connection.count()).toBe(3); - offB(); - expect(win.count() + connection.count()).toBe(0); - }); - - it('emits a fresh snapshot of onLine + NetworkInformation on each event', () => { - const win = mkTarget(); - const nav = { - onLine: true, - connection: { - ...mkTarget(), - type: 'wifi', - effectiveType: '4g', - downlink: 10, - rtt: 50, - saveData: false, - }, - }; - const t = new ConnectionTracker({ window: win, navigator: nav }); - const seen: unknown[] = []; - t.on('state', (s) => seen.push(s)); - nav.onLine = false; - win.fire('offline'); - nav.onLine = true; - nav.connection.rtt = 120; - nav.connection.fire('change'); - expect(seen).toEqual([ - { - onLine: false, - connection: { type: 'wifi', effectiveType: '4g', downlink: 10, rtt: 50, saveData: false }, - }, - { - onLine: true, - connection: { type: 'wifi', effectiveType: '4g', downlink: 10, rtt: 120, saveData: false }, - }, - ]); - }); - - it('online fires the same snapshot path as offline', () => { - const win = mkTarget(); - const nav = { onLine: false }; - const t = new ConnectionTracker({ window: win, navigator: nav }); - const seen: unknown[] = []; - t.on('state', (s) => seen.push(s)); - nav.onLine = true; - win.fire('online'); - expect(seen).toEqual([{ onLine: true }]); - }); - - it('current() is the live snapshot; onLine defaults to true when the browser does not say; undefined with no navigator', () => { - expect( - new ConnectionTracker({ navigator: { connection: { type: 'cellular' } } }).current(), - ).toEqual({ onLine: true, connection: { type: 'cellular' } }); - expect(new ConnectionTracker({ navigator: { onLine: false } }).current()).toEqual({ - onLine: false, - }); - expect(new ConnectionTracker({}).current()).toBeUndefined(); - }); - - it('omits absent NetworkInformation fields instead of carrying undefined', () => { - const c = new ConnectionTracker({ - navigator: { onLine: true, connection: { effectiveType: '3g' } }, - }).current(); - expect(c?.connection).toEqual({ effectiveType: '3g' }); - expect(Object.keys(c?.connection ?? {})).toEqual(['effectiveType']); - }); - - it('works with no window and a connection that cannot take listeners (Safari/Firefox)', () => { - const onError = vi.fn(); - const t = new ConnectionTracker( - { navigator: { onLine: true, connection: { type: 'wifi' } } }, - onError, - ); - const off = t.on('state', () => {}); - expect(() => off()).not.toThrow(); - expect(onError).not.toHaveBeenCalled(); // skipped quietly, not a swallowed TypeError - }); - - it('a throwing getter in the event path is reported, never thrown into the browser', () => { - const win = mkTarget(); - const onError = vi.fn(); - const nav = { - get onLine(): boolean { - throw new Error('getter'); - }, - }; - const t = new ConnectionTracker({ window: win, navigator: nav }, onError); - t.on('state', () => {}); - expect(() => win.fire('offline')).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); - expect(t.current()).toBeUndefined(); - expect(onError).toHaveBeenCalledTimes(2); - }); - - it('a throwing removeEventListener does not leak the other listeners', () => { - const win = mkTarget(); - const connection = mkTarget(); - const realRemove = win.removeEventListener; - win.removeEventListener = (t, f) => { - if (t === 'online') throw new Error('detached'); - realRemove(t, f); - }; - const t = new ConnectionTracker({ window: win, navigator: { onLine: true, connection } }); - const off = t.on('state', () => {}); - expect(() => off()).not.toThrow(); - expect(connection.count()).toBe(0); - expect(win.count()).toBe(1); // only the one whose removal threw is left - }); - - it('a throwing navigator.connection getter at activation is reported, not thrown out of on(); what attached is released', () => { - const win = mkTarget(); - const onError = vi.fn(); - const nav = { - onLine: true, - get connection(): never { - throw new Error('getter'); - }, - }; - const t = new ConnectionTracker({ window: win, navigator: nav }, onError); - let off: (() => void) | undefined; - expect(() => { - off = t.on('state', () => {}); - }).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); - expect(win.count()).toBe(2); // online/offline attached before the throw - off?.(); - expect(win.count()).toBe(0); - }); - - it('removes each listener exactly once per activation cycle (no stale entries replayed on a later stop)', () => { - const win = mkTarget(); - const removes = vi.fn(); - const realRemove = win.removeEventListener; - win.removeEventListener = (t, f) => { - removes(t); - realRemove(t, f); - }; - const t = new ConnectionTracker({ window: win, navigator: { onLine: true } }); - t.on('state', () => {})(); - t.on('state', () => {})(); - expect(removes).toHaveBeenCalledTimes(4); // online + offline, twice - }); - - it('an online/offline event with no navigator to read emits nothing', () => { - const win = mkTarget(); - const t = new ConnectionTracker({ window: win }); - const seen = vi.fn(); - t.on('state', seen); - win.fire('online'); - expect(seen).not.toHaveBeenCalled(); - }); - - it('with a shared lifecycle it takes online/offline from it and attaches NO window listener of its own', () => { - const win = mkTarget(); - const connection = mkTarget(); - const lifecycle = new PageLifecycleTracker({ window: win as never }); - const t = new ConnectionTracker({ - lifecycle, - window: win, - navigator: { onLine: true, connection }, - }); - const seen: unknown[] = []; - const off = t.on('state', (s) => seen.push(s)); - expect(win.count()).toBe(4); // the lifecycle's own four window listeners; the tracker added none - expect(connection.count()).toBe(1); - win.fire('online'); - win.fire('offline'); - expect(seen).toHaveLength(2); - off(); - expect(win.count() + connection.count()).toBe(0); - }); -}); diff --git a/packages/browser/src/trackers/connection-tracker.ts b/packages/browser/src/trackers/connection-tracker.ts deleted file mode 100644 index 60a781bc..00000000 --- a/packages/browser/src/trackers/connection-tracker.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { InterceptorBase } from '@bugsee/core'; -import type { PageLifecycleTracker } from './page-lifecycle-tracker'; - -// Browser connectivity TRACKER (mirrors the mobile tracker/producer split): snapshots `navigator.onLine` -// plus NetworkInformation whenever the browser says either changed โ€” `online`/`offline` on the window and -// `change` on `navigator.connection`. Safari and Firefox have no NetworkInformation, so `onLine` alone is -// still worth a row. Listeners are attached on the first subscriber and removed on the last. - -/** The NetworkInformation fields the trace reads (all optional; Chromium-on-Android has the most). */ -export interface ConnectionInfo { - type?: string; - effectiveType?: string; - downlink?: number; - rtt?: number; - saveData?: boolean; -} -export interface ConnectionState { - onLine: boolean; - /** Absent where the browser has no NetworkInformation. */ - connection?: ConnectionInfo; -} -interface TargetLike { - addEventListener(type: string, listener: () => void): void; - removeEventListener(type: string, listener: () => void): void; -} -export interface ConnectionEnv { - /** Shared lifecycle tracker for `online`/`offline`; when absent they are listened for on `window`. */ - lifecycle?: Pick; - window?: TargetLike; - navigator?: { - /** NetworkInformation; it is an EventTarget where it exists, but the fields are what matter. */ - connection?: ConnectionInfo & Partial; - onLine?: boolean; - }; -} - -export class ConnectionTracker extends InterceptorBase<{ state: ConnectionState }> { - readonly name = 'browser-connection'; - readonly #env: ConnectionEnv; - readonly #onError: ((error: unknown) => void) | undefined; - #attached: Array<{ target: Partial; type: string }> = []; - #subscriptions: Array<() => void> = []; - - readonly #onChange = (): void => { - try { - const state = this.#snapshot(); - if (state !== undefined) this.emit('state', state); - } catch (error) { - this.#onError?.(error); // never throw into the browser's event dispatch - } - }; - - constructor(env: ConnectionEnv, onError?: (error: unknown) => void) { - super(onError); - this.#env = env; - this.#onError = onError; - } - - /** The live state, or undefined with no `navigator` (or a throwing getter). */ - current(): ConnectionState | undefined { - try { - return this.#snapshot(); - } catch (error) { - this.#onError?.(error); - return undefined; - } - } - - // Guarded: the tracker is already marked active (and the subscriber registered) before this runs, so a - // throwing `navigator.connection` getter must be reported here, not leak out of `on()`. Whatever attached - // before the throw is still removed on deactivation. - protected onActivate(): void { - try { - const lifecycle = this.#env.lifecycle; - if (lifecycle !== undefined) { - this.#subscriptions.push( - lifecycle.on('online', this.#onChange), - lifecycle.on('offline', this.#onChange), - ); - } else { - this.#listen(this.#env.window, 'online'); - this.#listen(this.#env.window, 'offline'); - } - this.#listen(this.#env.navigator?.connection, 'change'); - } catch (error) { - this.#onError?.(error); - } - } - - protected override onDeactivate(): void { - const subscriptions = this.#subscriptions; - this.#subscriptions = []; - for (const off of subscriptions) off(); - const attached = this.#attached; - this.#attached = []; - for (const { target, type } of attached) { - try { - target.removeEventListener?.(type, this.#onChange); - } catch { - /* best-effort: one detached target must not leak the others */ - } - } - } - - #listen(target: Partial | undefined, type: string): void { - if (typeof target?.addEventListener !== 'function') return; - target.addEventListener(type, this.#onChange); - this.#attached.push({ target, type }); - } - - #snapshot(): ConnectionState | undefined { - const nav = this.#env.navigator; - if (nav === undefined) return undefined; - const c = nav.connection; - const onLine = nav.onLine !== false; - if (c === undefined) return { onLine }; - // Only the fields that exist: a key holding undefined would not survive JSON anyway. - const connection: ConnectionInfo = { - ...(c.type !== undefined ? { type: c.type } : {}), - ...(c.effectiveType !== undefined ? { effectiveType: c.effectiveType } : {}), - ...(c.downlink !== undefined ? { downlink: c.downlink } : {}), - ...(c.rtt !== undefined ? { rtt: c.rtt } : {}), - ...(c.saveData !== undefined ? { saveData: c.saveData } : {}), - }; - return { onLine, connection }; - } -} diff --git a/packages/trackers/README.md b/packages/trackers/README.md index d0494914..53541461 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -22,7 +22,7 @@ Trackers are the abstraction over system and runtime APIs. The package root is r - `@bugsee/trackers/node` (`src/node/`) - `@bugsee/trackers/electron` (`src/electron/`) -The `./browser` entry exports the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`) and `hostRead`; `./node` and `./electron` are reserved in `exports` and currently export nothing. Its API is internal and may change between releases. +The `./browser` entry exports the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`) and `hostRead`; `./node` and `./electron` are reserved in `exports` and currently export nothing. Its API is internal and may change between releases. ## Links diff --git a/packages/trackers/src/browser/connectivity-tracker.test.ts b/packages/trackers/src/browser/connectivity-tracker.test.ts new file mode 100644 index 00000000..924d01b4 --- /dev/null +++ b/packages/trackers/src/browser/connectivity-tracker.test.ts @@ -0,0 +1,441 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + type ConnectivityState, + ConnectivityTracker, + connectivityTrackerFor, + type NetworkInfo, + resetConnectivityTracker, +} from './connectivity-tracker'; + +function mkTarget() { + const l = new Map void>>(); + return { + addEventListener: (t: string, f: () => void) => { + const s = l.get(t) ?? new Set<() => void>(); + s.add(f); + l.set(t, s); + }, + removeEventListener: (t: string, f: () => void) => void l.get(t)?.delete(f), + fire: (t: string) => + l.get(t)?.forEach((f) => { + f(); + }), + count: () => [...l.values()].reduce((n, s) => n + s.size, 0), + }; +} +function mkNav(info?: Record, onLine = true) { + const connection = info === undefined ? undefined : Object.assign(mkTarget(), info); + return { onLine, connection }; +} + +const wins: object[] = []; +function mkWin() { + const w = mkTarget(); + wins.push(w); + return w; +} +afterEach(() => { + for (const w of wins.splice(0)) resetConnectivityTracker({ window: w }); +}); + +describe('ConnectivityTracker', () => { + it('reads online + every NetworkInformation field; omits absent ones', () => { + const nav = mkNav({ + type: 'wifi', + effectiveType: '4g', + downlink: 10, + downlinkMax: 100, + rtt: 50, + saveData: false, + }); + expect(new ConnectivityTracker({ navigator: nav }).current()).toEqual({ + online: true, + networkInfo: { + type: 'wifi', + effectiveType: '4g', + downlink: 10, + downlinkMax: 100, + rtt: 50, + saveData: false, + }, + }); + expect(new ConnectivityTracker({ navigator: mkNav({ rtt: 5 }) }).current()).toEqual({ + online: true, + networkInfo: { rtt: 5 }, + }); + }); + + it('no NetworkInformation -> no networkInfo key; no navigator -> undefined', () => { + expect(new ConnectivityTracker({ navigator: mkNav() }).current()).toEqual({ online: true }); + expect(new ConnectivityTracker({}).current()).toBeUndefined(); + }); + + it('onLine false -> online false; anything but false counts as online', () => { + expect(new ConnectivityTracker({ navigator: mkNav(undefined, false) }).current()?.online).toBe( + false, + ); + expect(new ConnectivityTracker({ navigator: {} }).current()?.online).toBe(true); + }); + + it('omits invalid / zero / non-finite values, never fabricates', () => { + const nav = mkNav({ + type: '', + effectiveType: 4, + downlink: 0, + downlinkMax: Infinity, + rtt: -1, + saveData: 'yes', + }); + expect(new ConnectivityTracker({ navigator: nav }).current()).toEqual({ + online: true, + networkInfo: {}, + }); + const nan = mkNav({ downlink: NaN, downlinkMax: 0, rtt: 0, saveData: true }); + expect(new ConnectivityTracker({ navigator: nan }).current()?.networkInfo).toEqual({ + saveData: true, + }); + }); + + it('a throwing getter costs only that field and is reported', () => { + const onError = vi.fn(); + const connection = Object.assign(mkTarget(), { type: 'wifi' }); + Object.defineProperty(connection, 'rtt', { + get() { + throw new Error('rtt boom'); + }, + }); + const t = new ConnectivityTracker({ navigator: { onLine: true, connection } }, onError); + expect(t.current()?.networkInfo).toEqual({ type: 'wifi' }); + expect((onError.mock.calls[0]?.[0] as Error).message).toBe('rtt boom'); + }); + + it('a throwing navigator.connection / onLine getter degrades and is reported', () => { + const onError = vi.fn(); + const nav = {}; + Object.defineProperty(nav, 'connection', { + get() { + throw new Error('conn boom'); + }, + }); + Object.defineProperty(nav, 'onLine', { + get() { + throw new Error('online boom'); + }, + }); + const win = mkTarget(); + const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); + expect(t.current()).toEqual({ online: true }); + const off = t.on('state', () => {}); + expect(win.count()).toBe(2); // window listeners still attach + off(); + expect(onError.mock.calls.length).toBeGreaterThanOrEqual(3); + }); + + it('a throwing onError never escapes', () => { + const nav = {}; + Object.defineProperty(nav, 'onLine', { + get() { + throw new Error('x'); + }, + }); + const t = new ConnectivityTracker({ navigator: nav }, () => { + throw new Error('reporter'); + }); + expect(() => t.current()).not.toThrow(); + }); + + it('emits online / state on online+offline events', () => { + const win = mkWin() as ReturnType; + const nav = mkNav({ type: 'wifi' }); + const t = new ConnectivityTracker({ window: win, navigator: nav }); + const online: boolean[] = []; + const states: ConnectivityState[] = []; + t.on('online', (e) => online.push(e.online)); + t.on('state', (s) => states.push(s)); + expect(online).toEqual([true]); // baseline + nav.onLine = false; + win.fire('offline'); + nav.onLine = true; + win.fire('online'); + expect(online).toEqual([true, false, true]); + expect(states.map((s) => s.online)).toEqual([false, true]); // subscribed after the baseline + }); + + it('emits networkInfo / state on connection change', () => { + const nav = mkNav({ effectiveType: '4g', downlink: 10 }); + const t = new ConnectivityTracker({ window: mkWin(), navigator: nav }); + const infos: NetworkInfo[] = []; + const states: ConnectivityState[] = []; + t.on('networkInfo', (i) => infos.push(i)); + t.on('state', (s) => states.push(s)); + Object.assign(nav.connection as object, { effectiveType: '3g', downlink: 1.5, downlinkMax: 7 }); + (nav.connection as ReturnType).fire('change'); + expect(infos).toEqual([ + { effectiveType: '4g', downlink: 10 }, + { effectiveType: '3g', downlink: 1.5, downlinkMax: 7 }, + ]); + expect(states.at(-1)).toEqual({ online: true, networkInfo: infos[1] }); + expect(states).toHaveLength(1); + }); + + it('a connection change event without a navigator reading emits nothing; online event with no connection emits no networkInfo', () => { + const win = mkWin() as ReturnType; + const t = new ConnectivityTracker({ window: win, navigator: mkNav() }); + const infos: NetworkInfo[] = []; + t.on('networkInfo', (i) => infos.push(i)); + win.fire('online'); + expect(infos).toEqual([]); + }); + + it('a connection change after navigator.connection vanished emits no networkInfo', () => { + const nav = mkNav({ type: 'wifi' }); + const conn = nav.connection as ReturnType; + const t = new ConnectivityTracker({ navigator: nav }); + const infos: NetworkInfo[] = []; + t.on('networkInfo', (i) => infos.push(i)); + nav.connection = undefined; + conn.fire('change'); + expect(infos).toHaveLength(1); // the baseline only + }); + + it('listeners attach only while subscribed and are fully released', () => { + const win = mkWin() as ReturnType; + const nav = mkNav({ type: 'wifi' }); + const conn = nav.connection as ReturnType; + const t = new ConnectivityTracker({ window: win, navigator: nav }); + expect(win.count() + conn.count()).toBe(0); + const off = t.on('online', () => {}); + expect(win.count()).toBe(2); + expect(conn.count()).toBe(1); + off(); + expect(win.count() + conn.count()).toBe(0); + }); + + it('retention: nothing is lost across the last unsubscribe; a later subscriber gets a fresh baseline', () => { + const win = mkWin() as ReturnType; + const nav = mkNav({ type: 'wifi' }); + const t = new ConnectivityTracker({ window: win, navigator: nav }); + const off = t.on('state', () => {}); + off(); + nav.onLine = false; // changed while nobody listened + const seen: ConnectivityState[] = []; + t.on('state', (s) => seen.push(s)); + expect(seen).toEqual([{ online: false, networkInfo: { type: 'wifi' } }]); + }); + + it('no navigator but window events: a firing event emits nothing', () => { + const win = mkTarget(); + const t = new ConnectivityTracker({ window: win }); + const seen: unknown[] = []; + t.on('state', (s) => seen.push(s)); + win.fire('online'); + expect(seen).toEqual([]); + }); + + it('a window whose addEventListener throws is reported, unwound, and never fails on()', () => { + const onError = vi.fn(); + const conn = mkTarget(); + const win = { + addEventListener: (type: string) => { + if (type === 'offline') throw new Error('add refused'); + }, + removeEventListener: vi.fn(), + }; + const nav = { onLine: true, connection: Object.assign(conn, { type: 'wifi' }) }; + const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); + const off = t.on('state', () => {}); + expect((onError.mock.calls[0]?.[0] as Error).message).toBe('add refused'); + expect(win.removeEventListener).toHaveBeenCalledTimes(2); // online + the refused offline (a no-op) unwound + expect(conn.count()).toBe(0); + off(); + }); + + it('a removeEventListener that throws does not leak the other targets', () => { + const conn = mkTarget(); + const win = { + addEventListener: () => {}, + removeEventListener: () => { + throw new Error('gone'); + }, + }; + const t = new ConnectivityTracker({ window: win, navigator: { connection: conn } }); + const off = t.on('state', () => {}); + expect(conn.count()).toBe(1); + off(); + expect(conn.count()).toBe(0); + }); + + it('a throwing subscriber inside an event never escapes into dispatch, and is reported', () => { + const onError = vi.fn(); + const win = mkWin() as ReturnType; + const nav = mkNav(); + const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); + let calls = 0; + t.on('online', () => { + if (++calls > 1) throw new Error('subscriber'); + }); + expect(() => win.fire('offline')).not.toThrow(); + }); + + it('a navigator without usable event targets still works (no connection listener)', () => { + const t = new ConnectivityTracker({ + navigator: { onLine: true, connection: { type: 'wifi' } }, + }); + const seen: ConnectivityState[] = []; + t.on('state', (s) => seen.push(s)); + expect(seen).toEqual([{ online: true, networkInfo: { type: 'wifi' } }]); + }); + + describe('rebind (latest launch wins, merge not drop)', () => { + it('a defined onError replaces the reporter; undefined keeps it', () => { + const first = vi.fn(); + const second = vi.fn(); + const nav = { onLine: true }; + Object.defineProperty(nav, 'connection', { + get() { + throw new Error('e'); + }, + }); + const t = new ConnectivityTracker({ navigator: nav }, first); + t.rebind({}, second); + t.current(); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalled(); + second.mockClear(); + t.rebind({}); + t.current(); + expect(second).toHaveBeenCalled(); + }); + + it('a partial env never clobbers window/navigator; a defined one replaces', () => { + const win = mkTarget(); + const nav = mkNav({ type: 'wifi' }); + const t = new ConnectivityTracker({ window: win, navigator: nav }); + t.rebind({}); + t.on('state', () => {}); + expect(win.count()).toBe(2); + expect(t.current()?.networkInfo).toEqual({ type: 'wifi' }); + }); + + it('a running tracker moves its listeners to a new window/navigator and re-reads', () => { + const w1 = mkTarget(); + const n1 = mkNav({ type: 'wifi' }); + const t = new ConnectivityTracker({ window: w1, navigator: n1 }); + const seen: ConnectivityState[] = []; + t.on('state', (s) => seen.push(s)); + const w2 = mkTarget(); + const n2 = mkNav({ type: 'cellular' }, false); + t.rebind({ window: w2, navigator: n2 }); + expect(w1.count()).toBe(0); + expect((n1.connection as ReturnType).count()).toBe(0); + expect(w2.count()).toBe(2); + expect((n2.connection as ReturnType).count()).toBe(1); + expect(seen.at(-1)).toEqual({ online: false, networkInfo: { type: 'cellular' } }); + }); + + it('rebinding the same objects while running does not re-attach or re-emit', () => { + const w1 = mkTarget(); + const n1 = mkNav(); + const t = new ConnectivityTracker({ window: w1, navigator: n1 }); + const seen: unknown[] = []; + t.on('state', (s) => seen.push(s)); + t.rebind({ window: w1, navigator: n1 }); + expect(seen).toHaveLength(1); + expect(w1.count()).toBe(2); + }); + + it('a partial env on a running tracker does not re-attach or re-emit', () => { + const w1 = mkTarget(); + const t = new ConnectivityTracker({ window: w1, navigator: mkNav() }); + const seen: unknown[] = []; + t.on('state', (s) => seen.push(s)); + t.rebind({}); + expect(seen).toHaveLength(1); + expect(w1.count()).toBe(2); + }); + + it('an idle tracker just adopts the new objects (no listeners)', () => { + const w2 = mkTarget(); + const t = new ConnectivityTracker({ navigator: mkNav() }); + t.rebind({ window: w2 }); + expect(w2.count()).toBe(0); + t.on('state', () => {}); + expect(w2.count()).toBe(2); + }); + }); + + it('reset() releases the listeners', () => { + const win = mkTarget(); + const t = new ConnectivityTracker({ window: win }); + t.on('state', () => {}); + t.reset(); + expect(win.count()).toBe(0); + }); +}); + +describe('connectivityTrackerFor', () => { + it('is one singleton per window; a different window gets its own', () => { + const w = mkWin(); + const a = connectivityTrackerFor({ window: w }); + expect(connectivityTrackerFor({ window: w })).toBe(a); + expect(connectivityTrackerFor({ window: mkWin() })).not.toBe(a); + }); + + it('keys on navigator without a window, else on the env object', () => { + const nav = {}; + const a = connectivityTrackerFor({ navigator: nav }); + expect(connectivityTrackerFor({ navigator: nav })).toBe(a); + const env = {}; + expect(connectivityTrackerFor(env)).toBe(connectivityTrackerFor(env)); + expect(connectivityTrackerFor({})).not.toBe(connectivityTrackerFor({})); + resetConnectivityTracker({ navigator: nav }); + }); + + it('a relaunch hands the shared tracker the latest onError and merges a partial env', () => { + const w = mkWin(); + const nav = mkNav({ type: 'wifi' }); + const first = vi.fn(); + const second = vi.fn(); + const a = connectivityTrackerFor({ window: w, navigator: nav }, first); + const b = connectivityTrackerFor({ window: w }, second); + expect(b).toBe(a); + expect(a.current()?.networkInfo).toEqual({ type: 'wifi' }); // navigator not dropped + const broken = {}; + Object.defineProperty(broken, 'connection', { + get() { + throw new Error('late'); + }, + }); + connectivityTrackerFor({ window: w, navigator: broken }, second); + a.current(); + expect(second).toHaveBeenCalled(); + expect(first).not.toHaveBeenCalled(); + }); + + it('a throwing env.window / env.navigator read is reported and never fails', () => { + const onError = vi.fn(); + const env = {}; + Object.defineProperty(env, 'window', { + get() { + throw new Error('win'); + }, + }); + Object.defineProperty(env, 'navigator', { + get() { + throw new Error('nav'); + }, + }); + expect(() => connectivityTrackerFor(env, onError)).not.toThrow(); + expect(onError).toHaveBeenCalled(); + }); + + it('resetConnectivityTracker releases the listeners and the next call builds a fresh one', () => { + const w = mkWin() as ReturnType; + const a = connectivityTrackerFor({ window: w, navigator: mkNav() }); + a.on('state', () => {}); + expect(w.count()).toBe(2); + resetConnectivityTracker({ window: w }); + expect(w.count()).toBe(0); + expect(connectivityTrackerFor({ window: w })).not.toBe(a); + }); +}); diff --git a/packages/trackers/src/browser/connectivity-tracker.ts b/packages/trackers/src/browser/connectivity-tracker.ts new file mode 100644 index 00000000..86af4c0a --- /dev/null +++ b/packages/trackers/src/browser/connectivity-tracker.ts @@ -0,0 +1,257 @@ +import { InterceptorBase } from '../interceptor-base'; +import { createTrackerRegistry } from '../tracker-registry'; +import { hostRead } from './host-read'; + +// Browser CONNECTIVITY tracker (domain tracker, design ยง15; Android reference: BugseeTrackerConnectivity). It owns +// EVERY connectivity listener itself: `online`/`offline` on the window and the Network Information API on +// `navigator.connection` (type, effectiveType, downlink, downlinkMax, rtt, saveData, and its `change` event). It does +// not depend on the page-lifecycle tracker. +// +// Stages (notification kinds): +// * `online` {online} โ€” `online`/`offline` window events. +// * `networkInfo` {type?, โ€ฆ} โ€” `navigator.connection` `change`; a field is OMITTED when absent or not a usable +// value (zero downlink/downlinkMax/rtt are "no estimate", never data). +// * `state` {online, networkInfo?} โ€” the aggregate; emitted alongside either of the above. Activation emits a +// baseline of all three. +// +// SINGLETON per window (see `connectivityTrackerFor`). RETENTION rule: stopping loses nothing a later subscriber +// needs. The state is not cached at all: it lives in `navigator`, which the tracker keeps (retains) across the last +// unsubscribe and READS LIVE (`current()`, and a fresh baseline on every activation) โ€” a cached snapshot could only +// be staler. The listeners are the only thing released. + +export interface NetworkInfo { + /** Transport (`wifi`, `cellular`, โ€ฆ). Chromium-on-Android in practice. */ + type?: string; + /** Speed bucket (`4g`, `3g`, โ€ฆ), NOT a transport. */ + effectiveType?: string; + /** Mbps. Omitted when 0/NaN/Infinity/negative. */ + downlink?: number; + /** Mbps, the upper bound of the underlying link. Omitted when 0/NaN/Infinity/negative. */ + downlinkMax?: number; + /** Round-trip time in ms. Omitted when 0/NaN/Infinity/negative. */ + rtt?: number; + saveData?: boolean; +} +export interface ConnectivityState { + online: boolean; + /** Absent where the browser has no NetworkInformation. */ + networkInfo?: NetworkInfo; +} +export interface ConnectivityEvents { + online: { online: boolean }; + networkInfo: NetworkInfo; + state: ConnectivityState; +} + +interface TargetLike { + addEventListener(type: string, listener: () => void): void; + removeEventListener(type: string, listener: () => void): void; +} +/** What the tracker needs from a launch. */ +export interface ConnectivityHost { + /** Source of `online`/`offline`. */ + window?: object; + navigator?: object; +} + +function positive(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined; +} + +export class ConnectivityTracker extends InterceptorBase { + readonly name = 'browser-connectivity'; + #window: object | undefined; + #navigator: object | undefined; + #running = false; + #attached: Array<{ target: Partial; type: string; listener: () => void }> = []; + + // Mutable indirection: the SHARED tracker outlives launches, so the reporter is always the latest launch's. + readonly #report: { fn: ((error: unknown) => void) | undefined }; + + constructor(host: ConnectivityHost, onError?: (error: unknown) => void) { + const report = { fn: onError }; + super((error) => report.fn?.(error)); + this.#report = report; + this.#window = host.window; + this.#navigator = host.navigator; + } + + /** + * Hand the latest launch's seams to this shared tracker (latest launch wins, but a PARTIAL env never drops what + * the tracker already has): a defined `onError`/`window`/`navigator` replaces ours, an undefined one keeps it. A + * running tracker whose window or navigator changed moves its listeners to the new objects and re-reads. + */ + rebind(host: ConnectivityHost, onError?: (error: unknown) => void): void { + if (onError !== undefined) this.#report.fn = onError; + const moved = + (host.window !== undefined && host.window !== this.#window) || + (host.navigator !== undefined && host.navigator !== this.#navigator); + if (host.window !== undefined) this.#window = host.window; + if (host.navigator !== undefined) this.#navigator = host.navigator; + if (moved && this.#running) { + this.#detach(); + this.#attach(); + } + } + + #onError(error: unknown): void { + try { + this.#report.fn?.(error); + } catch { + /* the reporter itself failed */ + } + } + + /** + * The LIVE state (read on every call, never stale), or undefined with no `navigator`. + */ + current(): ConnectivityState | undefined { + return this.#read(); + } + + /** Test/teardown: release the listeners. */ + reset(): void { + this.#running = false; + this.#detach(); + } + + protected onActivate(): void { + this.#running = true; + this.#attach(); + } + + protected override onDeactivate(): void { + this.#running = false; + this.#detach(); // listeners go; the host objects are retained + } + + // Guarded: the subscriber is registered before this runs, so a hostile host must be reported here, not leak + // out of `on()`. Whatever attached before a throw is removed again. + #attach(): void { + try { + const win = this.#window as Partial | undefined; + this.#listen(win, 'online', () => this.#changed('online')); + this.#listen(win, 'offline', () => this.#changed('online')); + const nav = this.#navigator; + const connection = + nav === undefined + ? undefined + : hostRead( + () => (nav as { connection?: unknown }).connection, + (e) => this.#onError(e), + ); + this.#listen( + typeof connection === 'object' && connection !== null + ? (connection as Partial) + : undefined, + 'change', + () => this.#changed('networkInfo'), + ); + const state = this.#read(); + if (state !== undefined) { + // Baseline: every stage, so a subscriber to any one of them starts from the current truth. + this.emit('online', { online: state.online }); + if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); + this.emit('state', state); + } + } catch (error) { + this.#detach(); + this.#onError(error); + } + } + + #listen(target: Partial | undefined, type: string, listener: () => void): void { + if (typeof target?.addEventListener !== 'function') return; + // `run` cannot throw into the browser's event dispatch: reads are hostRead-guarded and the emitter isolates + // (and reports) subscriber failures. + // Recorded BEFORE attaching so a failing addEventListener still unwinds exactly what was registered. + this.#attached.push({ target, type, listener }); + target.addEventListener(type, listener); + } + + #detach(): void { + const attached = this.#attached; + this.#attached = []; + for (const { target, type, listener } of attached) { + try { + target.removeEventListener?.(type, listener); + } catch { + /* best-effort: one detached target must not leak the others */ + } + } + } + + #changed(kind: 'online' | 'networkInfo'): void { + const state = this.#read(); + if (state === undefined) return; + if (kind === 'online') this.emit('online', { online: state.online }); + else if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); + this.emit('state', state); + } + + /** Reads the host; undefined when there is no navigator. */ + #read(): ConnectivityState | undefined { + const nav = this.#navigator as { onLine?: unknown; connection?: unknown } | undefined; + if (nav === undefined) return undefined; + const report = (error: unknown): void => this.#onError(error); + const online = hostRead(() => nav.onLine, report) !== false; + const connection = hostRead(() => nav.connection, report); + const state: ConnectivityState = { online }; + if (typeof connection === 'object' && connection !== null) { + const c = connection as Record; + // Each getter is its own failure domain: a hostile one costs only that field. + const type = hostRead(() => c.type, report); + const effectiveType = hostRead(() => c.effectiveType, report); + const downlink = positive(hostRead(() => c.downlink, report)); + const downlinkMax = positive(hostRead(() => c.downlinkMax, report)); + const rtt = positive(hostRead(() => c.rtt, report)); + const saveData = hostRead(() => c.saveData, report); + state.networkInfo = { + ...(typeof type === 'string' && type !== '' ? { type } : {}), + ...(typeof effectiveType === 'string' && effectiveType !== '' ? { effectiveType } : {}), + ...(downlink !== undefined ? { downlink } : {}), + ...(downlinkMax !== undefined ? { downlinkMax } : {}), + ...(rtt !== undefined ? { rtt } : {}), + ...(typeof saveData === 'boolean' ? { saveData } : {}), + }; + } + return state; + } +} + +const registry = createTrackerRegistry(); + +function keyOf(env: ConnectivityHost, onError?: (error: unknown) => void): object { + const win = hostRead(() => env.window, onError); + if (typeof win === 'object' && win !== null) return win; + const nav = hostRead(() => env.navigator, onError); + if (typeof nav === 'object' && nav !== null) return nav; + return env; +} + +/** + * The singleton ConnectivityTracker for the env's window (else its navigator, else the env object). Every call (a + * relaunch included) hands the shared tracker the latest launch's `onError`, window and navigator (see + * {@link ConnectivityTracker.rebind}). + */ +export function connectivityTrackerFor( + env: ConnectivityHost, + onError?: (error: unknown) => void, +): ConnectivityTracker { + const win = hostRead(() => env.window, onError); + const nav = hostRead(() => env.navigator, onError); + const host: ConnectivityHost = { + ...(typeof win === 'object' && win !== null ? { window: win } : {}), + ...(typeof nav === 'object' && nav !== null ? { navigator: nav } : {}), + }; + return registry.for( + keyOf(env, onError), + () => new ConnectivityTracker(host, onError), + (tracker) => tracker.rebind(host, onError), + ); +} + +/** Test/teardown: drop the env's tracker (resetting it, so its listeners are released). */ +export function resetConnectivityTracker(env: ConnectivityHost): void { + registry.reset(keyOf(env)); +} diff --git a/packages/trackers/src/browser/index.ts b/packages/trackers/src/browser/index.ts index 31f01692..a9a0914e 100644 --- a/packages/trackers/src/browser/index.ts +++ b/packages/trackers/src/browser/index.ts @@ -1,5 +1,15 @@ // `@bugsee/trackers/browser` entry. Platform tracker implementations that need DOM/Web-API APIs live under // src/browser/ and are exported from here. The portable root entry must never import from this directory. + +export { + type ConnectivityEvents, + type ConnectivityHost, + type ConnectivityState, + ConnectivityTracker, + connectivityTrackerFor, + type NetworkInfo, + resetConnectivityTracker, +} from './connectivity-tracker'; export { hostRead } from './host-read'; export { type BatteryEnv, diff --git a/packages/trackers/src/index.test.ts b/packages/trackers/src/index.test.ts index 491e237b..fd0c4862 100644 --- a/packages/trackers/src/index.test.ts +++ b/packages/trackers/src/index.test.ts @@ -19,9 +19,12 @@ describe('@bugsee/trackers public surface', () => { it('exports the browser tracker values from ./browser', async () => { expect(Object.keys(await import('./browser/index')).sort()).toEqual([ + 'ConnectivityTracker', 'PowerTracker', + 'connectivityTrackerFor', 'hostRead', 'powerTrackerFor', + 'resetConnectivityTracker', 'resetPowerTracker', ]); }); diff --git a/packages/webview/src/launch.test.ts b/packages/webview/src/launch.test.ts index e3082ce1..c1d3034d 100644 --- a/packages/webview/src/launch.test.ts +++ b/packages/webview/src/launch.test.ts @@ -1030,8 +1030,9 @@ describe('launch (webview)', () => { expect(rows.get('ram_js_heap_used')).toBe(10); expect(rows.get('connection')).toMatchObject({ type: 'cellular' }); expect(rows.get('orientation')).toBe(3); - // ONE shared lifecycle tracker: the traces and the events source add 3 listeners between them, not 6. - expect(w.count('online', 'offline', 'orientationchange')).toBe(3); + // ONE shared lifecycle tracker (traces + events source: 3 listeners, not 6) plus the domain ConnectivityTracker's + // own online/offline pair (it does not depend on the lifecycle tracker). + expect(w.count('online', 'offline', 'orientationchange')).toBe(5); await client.stop(); expect(w.count('online', 'offline', 'orientationchange')).toBe(0); } finally { From 8a350a66c2f390c993d42e790935b441c975e839 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 20 Oct 2026 12:53:50 +0500 Subject: [PATCH 2/3] fix(trackers): ConnectivityTracker review fixes (guarded reporter/listeners, no fabricated online, tests, docs) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/browser-connectivity-tracker.md | 2 +- docs/PROGRESS.md | 6 +- .../src/trace-producers.sensors.test.ts | 14 +++ packages/browser/src/trace-producers.ts | 1 + .../src/browser/connectivity-tracker.test.ts | 116 +++++++++++++++--- .../src/browser/connectivity-tracker.ts | 107 +++++++++------- 6 files changed, 181 insertions(+), 65 deletions(-) diff --git a/.changeset/browser-connectivity-tracker.md b/.changeset/browser-connectivity-tracker.md index 937d58d7..2b79c62c 100644 --- a/.changeset/browser-connectivity-tracker.md +++ b/.changeset/browser-connectivity-tracker.md @@ -3,4 +3,4 @@ '@bugsee/trackers': minor --- -Browser system traces: the `connection` trace gains `link_downstream_max_kbps` (from `NetworkInformation.downlinkMax`; omitted when the browser reports no usable value). Zero/non-finite `downlink` and `rtt` readings are now omitted instead of sent as 0. Connectivity is now served by a per-window singleton `ConnectivityTracker` (in the `@bugsee/trackers/browser` entry) that owns the `online`/`offline` and `navigator.connection` listeners and exposes `online`, `networkInfo` and `state` notifications. The trace name and the existing fields are unchanged. +Browser system traces: the `connection` trace gains `link_downstream_max_kbps` (from `NetworkInformation.downlinkMax`; omitted when the browser reports no usable value). Zero/non-finite `downlink`, `downlinkMax` and `rtt` readings are now treated as "no estimate" and omitted instead of sent as 0 (Chromium reports 0 offline and rounds `rtt` to 25 ms; the spec reports `downlinkMax` 0 for type `none`). An unreadable `navigator.onLine` produces no `connection` row instead of a fabricated online one. Connectivity is now served by a per-window singleton `ConnectivityTracker` (in the `@bugsee/trackers/browser` entry) that owns the `online`/`offline` and `navigator.connection` listeners and exposes `online`, `networkInfo` and `state` notifications. The trace name and the existing fields are unchanged. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 8512e150..9d22b9f3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -397,15 +397,15 @@ solid), in slices: are deleted** (`systemMetricsSampler` stays as a legacy override that REPLACES the heap/connection/orientation traces, as on Node; battery still runs). New `InterceptorBase` trackers in `packages/browser/src/trackers/`: `MemoryTracker` (the one `performance.memory` poll timer, started only on a subscriber and never where the engine has no `performance.memory`), `ConnectionTracker` (`online`/`offline` + `navigator.connection` - `change`), `OrientationTracker` (`screen.orientation` `change` + `orientationchange`). Producers: `MemoryProducer` + `change`; SUPERSEDED by the domain `ConnectivityTracker`, TR3: it owns its own window listeners and no longer subscribes to the lifecycle tracker), `OrientationTracker` (`screen.orientation` `change` + `orientationchange`). Producers: `MemoryProducer` (`ram_js_heap_*`, polled), `AdvertisedMemoryProducer` (`ram_system_advertised`), `ConnectionProducer`, `OrientationProducer` (event-driven, de-duplicated, held so the provider refresh keeps them in a rolling window). The producers read the LIVE `navigator`/`performance`/`screen`/`window` (`defaultBrowserTraceEnv()`); the old sampler copied `navigator` with a spread, which drops the prototype accessors (`onLine`, `connection`, `deviceMemory`) on a real browser. Launch passes - its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the connection/orientation trackers subscribe to it. + its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the orientation tracker subscribe to it (connectivity no longer does: TR3 `ConnectivityTracker` owns its own window listeners). - **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible โ€” loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first) and optional `screen_size`. - **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism. -- **TR3 (DONE, `feat/connectivity-tracker`):** the per-signal `ConnectionTracker` (and its test) is deleted; the domain **`ConnectivityTracker`** (`packages/trackers/src/browser/connectivity-tracker.ts`, `connectivityTrackerFor(env, onError)`, `resetConnectivityTracker`) is a per-window singleton via the registry (keyed on `env.window`, else `env.navigator`, else the env object) with `rebind` (latest `onError` wins; a defined `window`/`navigator` replaces ours, a partial env never drops them; a RUNNING tracker moves its listeners to a changed window/navigator and re-reads). It owns ALL connectivity listeners (window `online`/`offline` + `navigator.connection` `change`) and does NOT depend on the page-lifecycle tracker. Stages: `online` `{online}`, `networkInfo` `{type?, effectiveType?, downlink?, downlinkMax?, rtt?, saveData?}` and the aggregate `state` `{online, networkInfo?}`; activation emits a baseline of every stage. Fields are omitted when absent/invalid; zero/non-finite `downlink`/`downlinkMax`/`rtt` count as "no estimate" (Chromium reports 0 offline) and are omitted, `saveData` only when boolean. Every host read goes through `hostRead` (a hostile getter costs only its field; reported; a throwing `onError` never escapes). **Retention:** there is no cached snapshot to lose: state lives in `navigator`, which the tracker keeps and READS LIVE (`current()` and a fresh baseline on each activation); only the listeners are released on the last unsubscribe. `ConnectionProducer` is rewired onto it with UNCHANGED trace name/wire (`connection`: `type`, `effective_type`, `link_downstream_kbps`, `rtt`, `save_data`); `downlinkMax` is added to the open trace data as `link_downstream_max_kbps` (the connection trace is a free-form object with no schema, so this is additive). Consequence: `online`/`offline` are now bound twice on a window while capturing (the lifecycle tracker still serves the events source; the connectivity tracker owns its own), until the Application tracker absorbs the events source. +- **TR3 (DONE, `feat/connectivity-tracker`):** the per-signal `ConnectionTracker` (and its test) is deleted; the domain **`ConnectivityTracker`** (`packages/trackers/src/browser/connectivity-tracker.ts`, `connectivityTrackerFor(env, onError)`, `resetConnectivityTracker`) is a per-window singleton via the registry (keyed on `env.window`, else `env.navigator`, else the env object) with `rebind` (latest `onError` wins; a defined `window`/`navigator` replaces ours, a partial env never drops them; a RUNNING tracker moves its listeners to a changed window/navigator and re-reads). It owns ALL connectivity listeners (window `online`/`offline` + `navigator.connection` `change`) and does NOT depend on the page-lifecycle tracker. Stages: `online` `{online}`, `networkInfo` `{type?, effectiveType?, downlink?, downlinkMax?, rtt?, saveData?}` and the aggregate `state` `{online, networkInfo?}`; activation emits a baseline of every stage. Fields are omitted when absent/invalid; zero/non-finite `downlink`/`downlinkMax`/`rtt` count as "no estimate" (Chromium reports 0 offline and rounds `rtt` to 25 ms, so a 0 rtt is an unmeasured one; the spec reports `downlinkMax` 0 for type `none`) and are omitted, `saveData` only when boolean. Every host read goes through `hostRead` (a hostile getter costs only its field; reported). The emitter's reporter and every DOM listener are guarded, so a throwing subscriber plus a throwing `onError` never escapes a dispatch or `on()`. A refused `addEventListener` is reported once and the listeners that did attach stay attached (no silent death; released on deactivation). A THROWING `navigator.onLine` getter is NOT online: `online` is omitted from the state (no `online` emission, no fabricated true; `ConnectionProducer` writes no row), whereas an absent `onLine` property still counts as online. `state.online` is therefore optional. **Retention:** there is no cached snapshot to lose: state lives in `navigator`, which the tracker keeps and READS LIVE (`current()` and a fresh baseline on each activation); only the listeners are released on the last unsubscribe. `ConnectionProducer` is rewired onto it with UNCHANGED trace name/wire (`connection`: `type`, `effective_type`, `link_downstream_kbps`, `rtt`, `save_data`); `downlinkMax` is added to the open trace data as `link_downstream_max_kbps` (the connection trace is a free-form object with no schema, so this is additive). Consequence: `online`/`offline` are now bound twice on a window while capturing (the lifecycle tracker still serves the events source; the connectivity tracker owns its own), until the Application tracker absorbs the events source. - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/trace-producers.sensors.test.ts b/packages/browser/src/trace-producers.sensors.test.ts index b32a602f..b7a1a3da 100644 --- a/packages/browser/src/trace-producers.sensors.test.ts +++ b/packages/browser/src/trace-producers.sensors.test.ts @@ -205,6 +205,20 @@ describe('ConnectionProducer', () => { expect(win.count()).toBe(0); }); + it('emits no row when navigator.onLine cannot be read (never a fabricated online/unknown)', () => { + const nav = { connection: { type: 'wifi' } }; + Object.defineProperty(nav, 'onLine', { + get() { + throw new Error('onLine blocked'); + }, + }); + const onError = vi.fn(); + expect( + startAll([new ConnectionProducer(new ConnectivityTracker({ navigator: nav }, onError))]).out, + ).toEqual([]); + expect(onError).toHaveBeenCalled(); + }); + it('emits nothing with no navigator at all', () => { expect(startAll([new ConnectionProducer(new ConnectivityTracker({}))]).out).toEqual([]); }); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 8355069f..e8984019 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -154,6 +154,7 @@ export class ConnectionProducer extends TraceProducerBase { } #publish({ online, networkInfo: connection }: ConnectivityState): void { + if (online === undefined) return; // an unreadable onLine is not evidence of anything: no row this.emitIfChanged('connection', { type: connectionTypeToWire(connection, online), // Everything below is DETAIL (the viewer renders `item.data`), so it is omitted rather than sent diff --git a/packages/trackers/src/browser/connectivity-tracker.test.ts b/packages/trackers/src/browser/connectivity-tracker.test.ts index 924d01b4..bc1349b3 100644 --- a/packages/trackers/src/browser/connectivity-tracker.test.ts +++ b/packages/trackers/src/browser/connectivity-tracker.test.ts @@ -109,26 +109,48 @@ describe('ConnectivityTracker', () => { expect((onError.mock.calls[0]?.[0] as Error).message).toBe('rtt boom'); }); - it('a throwing navigator.connection / onLine getter degrades and is reported', () => { + it('a throwing onLine getter is NOT online: the value is omitted, nothing fabricated, and it is reported', () => { const onError = vi.fn(); const nav = {}; - Object.defineProperty(nav, 'connection', { + Object.defineProperty(nav, 'onLine', { get() { - throw new Error('conn boom'); + throw new Error('online boom'); }, }); - Object.defineProperty(nav, 'onLine', { + const win = mkTarget(); + const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); + expect(t.current()).toEqual({}); + expect(onError).toHaveBeenCalledTimes(1); + const online: unknown[] = []; + const states: unknown[] = []; + t.on('online', (e) => online.push(e)); + t.on('state', (s) => states.push(s)); + win.fire('offline'); + expect(online).toEqual([]); // never a fabricated true + expect(states).toEqual([{}]); // the event (state subscribed after the baseline); online absent + }); + + it('a throwing navigator.connection getter degrades to online-only and is reported once per read', () => { + const onError = vi.fn(); + const nav = { onLine: true }; + Object.defineProperty(nav, 'connection', { get() { - throw new Error('online boom'); + throw new Error('conn boom'); }, }); const win = mkTarget(); const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); expect(t.current()).toEqual({ online: true }); + expect(onError).toHaveBeenCalledTimes(1); + onError.mockClear(); const off = t.on('state', () => {}); expect(win.count()).toBe(2); // window listeners still attach + expect(onError).toHaveBeenCalledTimes(2); // activation: listener lookup + baseline read off(); - expect(onError.mock.calls.length).toBeGreaterThanOrEqual(3); + }); + + it('an absent onLine property is treated as online (old behavior)', () => { + expect(new ConnectivityTracker({ navigator: {} }).current()).toEqual({ online: true }); }); it('a throwing onError never escapes', () => { @@ -178,12 +200,16 @@ describe('ConnectivityTracker', () => { expect(states).toHaveLength(1); }); - it('a connection change event without a navigator reading emits nothing; online event with no connection emits no networkInfo', () => { + it('online/offline events with a connection present emit online + state but NOT networkInfo', () => { const win = mkWin() as ReturnType; - const t = new ConnectivityTracker({ window: win, navigator: mkNav() }); + const t = new ConnectivityTracker({ window: win, navigator: mkNav({ type: 'wifi' }) }); const infos: NetworkInfo[] = []; + const online: boolean[] = []; + t.on('online', (e) => online.push(e.online)); // activates; the baseline is already gone t.on('networkInfo', (i) => infos.push(i)); + win.fire('offline'); win.fire('online'); + expect(online).toEqual([true, true, true]); // baseline + 2 events expect(infos).toEqual([]); }); @@ -232,22 +258,40 @@ describe('ConnectivityTracker', () => { expect(seen).toEqual([]); }); - it('a window whose addEventListener throws is reported, unwound, and never fails on()', () => { + it('a refused addEventListener is reported once; the listeners that did attach stay attached and are released on stop', () => { const onError = vi.fn(); const conn = mkTarget(); + const online = new Set<() => void>(); const win = { - addEventListener: (type: string) => { + addEventListener: (type: string, f: () => void) => { if (type === 'offline') throw new Error('add refused'); + online.add(f); }, - removeEventListener: vi.fn(), + removeEventListener: (_type: string, f: () => void) => void online.delete(f), }; const nav = { onLine: true, connection: Object.assign(conn, { type: 'wifi' }) }; const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); const off = t.on('state', () => {}); + expect(onError).toHaveBeenCalledTimes(1); expect((onError.mock.calls[0]?.[0] as Error).message).toBe('add refused'); - expect(win.removeEventListener).toHaveBeenCalledTimes(2); // online + the refused offline (a no-op) unwound - expect(conn.count()).toBe(0); + expect(online.size).toBe(1); // not dead: online stays attached + expect(conn.count()).toBe(1); // and the connection listener after the refusal still attached off(); + expect(online.size).toBe(0); + expect(conn.count()).toBe(0); + }); + + it('a throwing reporter on a refused addEventListener never escapes on()', () => { + const win = { + addEventListener: () => { + throw new Error('add refused'); + }, + removeEventListener: () => {}, + }; + const t = new ConnectivityTracker({ window: win, navigator: mkNav() }, () => { + throw new Error('reporter'); + }); + expect(() => t.on('state', () => {})).not.toThrow(); }); it('a removeEventListener that throws does not leak the other targets', () => { @@ -265,16 +309,36 @@ describe('ConnectivityTracker', () => { expect(conn.count()).toBe(0); }); - it('a throwing subscriber inside an event never escapes into dispatch, and is reported', () => { - const onError = vi.fn(); + it('a throwing subscriber AND a throwing onError never escape a DOM dispatch or the activation baseline', () => { + const onError = vi.fn(() => { + throw new Error('reporter'); + }); const win = mkWin() as ReturnType; - const nav = mkNav(); - const t = new ConnectivityTracker({ window: win, navigator: nav }, onError); + const t = new ConnectivityTracker({ window: win, navigator: mkNav() }, onError); let calls = 0; + // The first call is the activation baseline. + expect(() => + t.on('online', () => { + calls += 1; + throw new Error('subscriber'); + }), + ).not.toThrow(); + expect(() => win.fire('offline')).not.toThrow(); + expect(calls).toBe(2); + expect(onError).toHaveBeenCalledTimes(2); // both subscriber failures reached the (throwing) reporter + }); + + it('a throwing subscriber is reported through onError during dispatch', () => { + const onError = vi.fn(); + const win = mkWin() as ReturnType; + const t = new ConnectivityTracker({ window: win, navigator: mkNav() }, onError); t.on('online', () => { - if (++calls > 1) throw new Error('subscriber'); + throw new Error('subscriber'); }); - expect(() => win.fire('offline')).not.toThrow(); + onError.mockClear(); + win.fire('offline'); + expect(onError).toHaveBeenCalledTimes(1); + expect((onError.mock.calls[0] as unknown as [Error])[0].message).toBe('subscriber'); }); it('a navigator without usable event targets still works (no connection listener)', () => { @@ -333,6 +397,20 @@ describe('ConnectivityTracker', () => { expect(seen.at(-1)).toEqual({ online: false, networkInfo: { type: 'cellular' } }); }); + it('a navigator-only rebind moves the connection listener and re-reads', () => { + const win = mkTarget(); + const n1 = mkNav({ type: 'wifi' }); + const t = new ConnectivityTracker({ window: win, navigator: n1 }); + const seen: ConnectivityState[] = []; + t.on('state', (s) => seen.push(s)); + const n2 = mkNav({ type: 'cellular' }); + t.rebind({ navigator: n2 }); + expect((n1.connection as ReturnType).count()).toBe(0); + expect((n2.connection as ReturnType).count()).toBe(1); + expect(win.count()).toBe(2); + expect(seen.at(-1)?.networkInfo).toEqual({ type: 'cellular' }); + }); + it('rebinding the same objects while running does not re-attach or re-emit', () => { const w1 = mkTarget(); const n1 = mkNav(); diff --git a/packages/trackers/src/browser/connectivity-tracker.ts b/packages/trackers/src/browser/connectivity-tracker.ts index 86af4c0a..52692cb8 100644 --- a/packages/trackers/src/browser/connectivity-tracker.ts +++ b/packages/trackers/src/browser/connectivity-tracker.ts @@ -33,7 +33,8 @@ export interface NetworkInfo { saveData?: boolean; } export interface ConnectivityState { - online: boolean; + /** Omitted when `navigator.onLine` could not be read (never fabricated as true). */ + online?: boolean; /** Absent where the browser has no NetworkInformation. */ networkInfo?: NetworkInfo; } @@ -70,7 +71,14 @@ export class ConnectivityTracker extends InterceptorBase { constructor(host: ConnectivityHost, onError?: (error: unknown) => void) { const report = { fn: onError }; - super((error) => report.fn?.(error)); + // Guarded: a throwing reporter must not escape the emitter's subscriber isolation into a DOM dispatch. + super((error) => { + try { + report.fn?.(error); + } catch { + /* the reporter itself failed */ + } + }); this.#report = report; this.#window = host.window; this.#navigator = host.navigator; @@ -125,48 +133,54 @@ export class ConnectivityTracker extends InterceptorBase { this.#detach(); // listeners go; the host objects are retained } - // Guarded: the subscriber is registered before this runs, so a hostile host must be reported here, not leak - // out of `on()`. Whatever attached before a throw is removed again. + // Nothing here can throw out of `on()`: every host read is hostRead-guarded, each listener registration is its own + // failure domain (a refused one is reported ONCE and the others still attach โ€” they stay attached, like the other + // trackers; the next deactivation removes them), and the emitter isolates subscriber failures through a guarded + // reporter. #attach(): void { - try { - const win = this.#window as Partial | undefined; - this.#listen(win, 'online', () => this.#changed('online')); - this.#listen(win, 'offline', () => this.#changed('online')); - const nav = this.#navigator; - const connection = - nav === undefined - ? undefined - : hostRead( - () => (nav as { connection?: unknown }).connection, - (e) => this.#onError(e), - ); - this.#listen( - typeof connection === 'object' && connection !== null - ? (connection as Partial) - : undefined, - 'change', - () => this.#changed('networkInfo'), - ); - const state = this.#read(); - if (state !== undefined) { - // Baseline: every stage, so a subscriber to any one of them starts from the current truth. - this.emit('online', { online: state.online }); - if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); - this.emit('state', state); - } - } catch (error) { - this.#detach(); - this.#onError(error); + const win = this.#window as Partial | undefined; + this.#listen(win, 'online', () => this.#changed('online')); + this.#listen(win, 'offline', () => this.#changed('online')); + const nav = this.#navigator; + const connection = + nav === undefined + ? undefined + : hostRead( + () => (nav as { connection?: unknown }).connection, + (e) => this.#onError(e), + ); + this.#listen( + typeof connection === 'object' && connection !== null + ? (connection as Partial) + : undefined, + 'change', + () => this.#changed('networkInfo'), + ); + const state = this.#read(); + if (state !== undefined) { + // Baseline: every stage that has a value, so a subscriber to any one starts from the current truth. + if (state.online !== undefined) this.emit('online', { online: state.online }); + if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); + this.emit('state', state); } } - #listen(target: Partial | undefined, type: string, listener: () => void): void { + #listen(target: Partial | undefined, type: string, run: () => void): void { if (typeof target?.addEventListener !== 'function') return; - // `run` cannot throw into the browser's event dispatch: reads are hostRead-guarded and the emitter isolates - // (and reports) subscriber failures. - // Recorded BEFORE attaching so a failing addEventListener still unwinds exactly what was registered. + const listener = (): void => { + try { + run(); + } catch (error) /* v8 ignore next 3 -- defense in depth: reads and the emitter are already guarded */ { + this.#onError(error); + } + }; + // Recorded BEFORE attaching so a failing addEventListener still leaves a removable record. this.#attached.push({ target, type, listener }); - target.addEventListener(type, listener); + try { + target.addEventListener(type, listener); + } catch (error) { + this.#onError(error); + } } #detach(): void { @@ -184,8 +198,9 @@ export class ConnectivityTracker extends InterceptorBase { #changed(kind: 'online' | 'networkInfo'): void { const state = this.#read(); if (state === undefined) return; - if (kind === 'online') this.emit('online', { online: state.online }); - else if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); + if (kind === 'online') { + if (state.online !== undefined) this.emit('online', { online: state.online }); + } else if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); this.emit('state', state); } @@ -194,9 +209,17 @@ export class ConnectivityTracker extends InterceptorBase { const nav = this.#navigator as { onLine?: unknown; connection?: unknown } | undefined; if (nav === undefined) return undefined; const report = (error: unknown): void => this.#onError(error); - const online = hostRead(() => nav.onLine, report) !== false; + // A failed read is NOT "online": the value is omitted. A merely absent `onLine` stays treated as online. + let failed = false; + const onLine = hostRead( + () => nav.onLine, + (error) => { + failed = true; + report(error); + }, + ); const connection = hostRead(() => nav.connection, report); - const state: ConnectivityState = { online }; + const state: ConnectivityState = failed ? {} : { online: onLine !== false }; if (typeof connection === 'object' && connection !== null) { const c = connection as Record; // Each getter is its own failure domain: a hostile one costs only that field. From 283e91ec229e05c1a5c0157e1d975706d7febaef Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 20 Oct 2026 13:39:53 +0500 Subject: [PATCH 3/3] fix(trackers): ConnectivityTracker PR review (single env reads, event hint when onLine unreadable, guarded addEventListener read) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- docs/PROGRESS.md | 2 +- .../src/browser/connectivity-tracker.test.ts | 80 ++++++++++++++++++- .../src/browser/connectivity-tracker.ts | 63 ++++++++++----- 3 files changed, 122 insertions(+), 23 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 8482033e..a6cc7be5 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -408,7 +408,7 @@ solid), in slices: - **ST4c (DONE, `feat/browser-screen-size-main-thread-lag`):** `screen_size` (`ScreenSizeTracker` + `ScreenSizeProducer`: value shape `{width, height, dpr}` in CSS px โ€” NOT `displays`; held, de-duplicated step trace; initial value at start; re-read on `resize` (listened for on the injected window by the tracker โ€” no new shared-lifecycle event, since nothing else consumes it and it would change every lifecycle subscriber's listener count) and `orientationchange` (via the shared lifecycle); omitted entirely when `screen` or `devicePixelRatio` is not a finite positive number; known staleness: moving the window to a monitor with the same DPR but a different size fires no `resize`, and iOS Safari's `screen.width/height` do not swap on rotation โ€” a `(resolution: Xdppx)` matchMedia/`screen` change listener is a follow-up) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: TIMER DRIFT: on each 1 s scheduler tick on the page's main thread, `lag = max(0, now - (previousTickTime + intervalMs))` with the injected `performance.now`; the first tick compares against the run's start + interval; emitted EVERY tick as a polled (`hold:false`) trace โ€” a measured ~0 is a true value. **What a reading means (measured in Chromium):** a tick fires late by (block end โˆ’ the first due time the block covered), so a block B โ‰ฅ 1 s reads between Bโˆ’1000 and B (1800 ms read 907..1797; 2500 ms read 1807), while a block shorter than 1 s that crosses no due tick reads exactly 0 (probability โ‰ˆ 1 โˆ’ B/1000: ~30% for 700 ms, ~90% for 100 ms); one block is reported once (the next tick clamps to 0). It is NOT Node's ~10 ms event-loop monitor โ€” sampling every 1000 ms is why short blocks can go unseen. Measured ONLY while visible: hidden tears the timer down and every visible start takes a FRESH baseline, so a hidden stretch never counts as lag. A throwing clock/scheduler at start rolls back; a throwing or non-finite clock at a tick is reported/skipped without reading the skipped interval as lag. No clock (`performance.now` must be a function), lifecycle, or a hidden page = omitted, no timer. **Honest limit:** long freezes are reported reliably, short jank only by luck; follow-ups if short jank matters: a finer internal timer reporting the MAX drift per 1 s window, or `PerformanceObserver('longtask')` where supported. Timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`) may also read as lag โ€” UNVERIFIED, it could not be reproduced headless. **History:** a `MessageChannel` ping (re-arm on receipt, then once per tick) was built and rejected after measuring real Chromium: re-arming on receipt was a ~2.2M/s task loop, and a ping per tick reads ~0.1 ms for a block that starts after the ping returned โ€” a plausible-healthy lie; it was deleted entirely, no `MessageChannel` in the traces env). Both are built under the same `env.lifecycle` gate as `app_state`/`fps`, so a `systemMetricsSampler` (`sensors:false`) replaces them too. Open: the viewer has no definition for either name yet (generic value block, design ยง13.3). - **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism. - **TR1 (DONE, `feat/application-tracker`; design ยง15):** `PageLifecycleTracker` is now the domain **`ApplicationTracker`** (`packages/trackers/src/browser/application-tracker.ts`). Stages: `pagehide`, `visibility`, `freeze`, `resume`, plus the NEW aggregated `state` (`{state: 'foreground'|'background'}`, Android vocabulary, emitted when a visibility change CHANGES it) and `current()` (read live from the document, else the retained value; undefined when never known โ€” an unreadable document emits no `state`, never a fabricated background). **Singleton per key** via `createTrackerRegistry`: `applicationTrackerFor(env, onError?)` keys by the document, else the window, else one shared key; a window-only env and a window+document env are DISTINCT trackers (pair a document with its own window); `resetApplicationTracker(env)` is exported from `@bugsee/trackers/browser` for internal/test use and is NOT re-exported by `@bugsee/browser`. Browser + webview launch and the events-source fallback obtain it through the registry. **Retention rule (tested):** DOM listeners attach on the first subscriber and detach on the last, the last known `state` is retained and recomputed silently from the document on re-activation, so the first subscriber after a gap is correct at once and the de-dup baseline is never stale. `AppStateProducer` now takes the tracker only (`on('state')` + `current()` for the initial value); trace/event names and wire shapes are unchanged. **Keying rule:** document, else window, else one module key (design ยง15.1 #5 will be amended from "one per window" to this). **Latest launch wins** through the registry `rebind`: a defined `onError` replaces the shared reporter (undefined keeps it); while IDLE the window/document are merged (a target the request omits is kept), while ACTIVE the binding is kept and a window/document mismatch (only a target the request supplies is compared; the error names which) is reported once. The shared sink is never released on stop: a relaunch with no `onError` keeps the previous launch's (accepted limitation). `resetApplicationTracker` is `@internal` test/teardown use: exported from `@bugsee/trackers/browser` but not re-exported by `@bugsee/browser` (`reset()` removes all subscribers). An unreadable document emits neither `visibility` nor `state` (no fabricated `process_background`/fps pause). **Stays for later:** `online`/`offline` (move to Connectivity, TR3) and `orientationchange` (UI/Display, TR2) remain stages on this tracker so ConnectionTracker/OrientationTracker are untouched. -- **TR3 (DONE, `feat/connectivity-tracker`):** the per-signal `ConnectionTracker` (and its test) is deleted; the domain **`ConnectivityTracker`** (`packages/trackers/src/browser/connectivity-tracker.ts`, `connectivityTrackerFor(env, onError)`, `resetConnectivityTracker`) is a per-window singleton via the registry (keyed on `env.window`, else `env.navigator`, else the env object) with `rebind` (latest `onError` wins; a defined `window`/`navigator` replaces ours, a partial env never drops them; a RUNNING tracker moves its listeners to a changed window/navigator and re-reads). It owns ALL connectivity listeners (window `online`/`offline` + `navigator.connection` `change`) and does NOT depend on the page-lifecycle tracker. Stages: `online` `{online}`, `networkInfo` `{type?, effectiveType?, downlink?, downlinkMax?, rtt?, saveData?}` and the aggregate `state` `{online, networkInfo?}`; activation emits a baseline of every stage. Fields are omitted when absent/invalid; zero/non-finite `downlink`/`downlinkMax`/`rtt` count as "no estimate" (Chromium reports 0 offline and rounds `rtt` to 25 ms, so a 0 rtt is an unmeasured one; the spec reports `downlinkMax` 0 for type `none`) and are omitted, `saveData` only when boolean. Every host read goes through `hostRead` (a hostile getter costs only its field; reported). The emitter's reporter and every DOM listener are guarded, so a throwing subscriber plus a throwing `onError` never escapes a dispatch or `on()`. A refused `addEventListener` is reported once and the listeners that did attach stay attached (no silent death; released on deactivation). A THROWING `navigator.onLine` getter is NOT online: `online` is omitted from the state (no `online` emission, no fabricated true; `ConnectionProducer` writes no row), whereas an absent `onLine` property still counts as online. `state.online` is therefore optional. **Retention:** there is no cached snapshot to lose: state lives in `navigator`, which the tracker keeps and READS LIVE (`current()` and a fresh baseline on each activation); only the listeners are released on the last unsubscribe. `ConnectionProducer` is rewired onto it with UNCHANGED trace name/wire (`connection`: `type`, `effective_type`, `link_downstream_kbps`, `rtt`, `save_data`); `downlinkMax` is added to the open trace data as `link_downstream_max_kbps` (the connection trace is a free-form object with no schema, so this is additive). Consequence: `online`/`offline` are now bound twice on a window while capturing (the lifecycle tracker still serves the events source; the connectivity tracker owns its own), until the Application tracker absorbs the events source. +- **TR3 (DONE, `feat/connectivity-tracker`):** the per-signal `ConnectionTracker` (and its test) is deleted; the domain **`ConnectivityTracker`** (`packages/trackers/src/browser/connectivity-tracker.ts`, `connectivityTrackerFor(env, onError)`, `resetConnectivityTracker`) is a per-window singleton via the registry (keyed on `env.window`, else `env.navigator`, else the env object) with `rebind` (latest `onError` wins; a defined `window`/`navigator` replaces ours, a partial env never drops them; a RUNNING tracker moves its listeners to a changed window/navigator and re-reads). It owns ALL connectivity listeners (window `online`/`offline` + `navigator.connection` `change`) and does NOT depend on the page-lifecycle tracker. Stages: `online` `{online}`, `networkInfo` `{type?, effectiveType?, downlink?, downlinkMax?, rtt?, saveData?}` and the aggregate `state` `{online, networkInfo?}`; activation emits a baseline of every stage. Fields are omitted when absent/invalid; zero/non-finite `downlink`/`downlinkMax`/`rtt` count as "no estimate" (Chromium reports 0 offline and rounds `rtt` to 25 ms, so a 0 rtt is an unmeasured one; the spec reports `downlinkMax` 0 for type `none`) and are omitted, `saveData` only when boolean. Every host read goes through `hostRead` (a hostile getter costs only its field; reported). The emitter's reporter and every DOM listener are guarded, so a throwing subscriber plus a throwing `onError` never escapes a dispatch or `on()`. A refused `addEventListener` is reported once and the listeners that did attach stay attached (no silent death; released on deactivation). A THROWING `navigator.onLine` getter is NOT online: `online` is omitted from the state (no `online` emission, no fabricated true; `ConnectionProducer` writes no row), unless the window `online`/`offline` event that triggered the read supplies the value (the event is evidence; a READABLE `onLine` always wins), and an absent `onLine` property still counts as online. `connectivityTrackerFor` reads `window`/`navigator` once per call (a flaky getter is reported once and the key matches the host it built); `resetConnectivityTracker` is best-effort for such envs (first of window/navigator/env that has a tracker). The `addEventListener` READ itself is guarded too (cross-origin proxies). `state.online` is therefore optional. **Retention:** there is no cached snapshot to lose: state lives in `navigator`, which the tracker keeps and READS LIVE (`current()` and a fresh baseline on each activation); only the listeners are released on the last unsubscribe. `ConnectionProducer` is rewired onto it with UNCHANGED trace name/wire (`connection`: `type`, `effective_type`, `link_downstream_kbps`, `rtt`, `save_data`); `downlinkMax` is added to the open trace data as `link_downstream_max_kbps` (the connection trace is a free-form object with no schema, so this is additive). Consequence: `online`/`offline` are now bound twice on a window while capturing (the lifecycle tracker still serves the events source; the connectivity tracker owns its own), until the Application tracker absorbs the events source. - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/trackers/src/browser/connectivity-tracker.test.ts b/packages/trackers/src/browser/connectivity-tracker.test.ts index bc1349b3..98e802a5 100644 --- a/packages/trackers/src/browser/connectivity-tracker.test.ts +++ b/packages/trackers/src/browser/connectivity-tracker.test.ts @@ -126,8 +126,8 @@ describe('ConnectivityTracker', () => { t.on('online', (e) => online.push(e)); t.on('state', (s) => states.push(s)); win.fire('offline'); - expect(online).toEqual([]); // never a fabricated true - expect(states).toEqual([{}]); // the event (state subscribed after the baseline); online absent + expect(online).toEqual([{ online: false }]); // the event is the evidence; never a fabricated true + expect(states).toEqual([{ online: false }]); }); it('a throwing navigator.connection getter degrades to online-only and is reported once per read', () => { @@ -149,6 +149,59 @@ describe('ConnectivityTracker', () => { off(); }); + it('when onLine is unreadable, the offline/online EVENT itself is the evidence', () => { + const nav = {}; + Object.defineProperty(nav, 'onLine', { + get() { + throw new Error('online boom'); + }, + }); + const win = mkTarget(); + const t = new ConnectivityTracker({ window: win, navigator: nav }); + const online: boolean[] = []; + const states: unknown[] = []; + t.on('online', (e) => online.push(e.online)); // baseline: unreadable -> nothing + t.on('state', (s) => states.push(s)); + win.fire('offline'); + win.fire('online'); + expect(online).toEqual([false, true]); + expect(states).toEqual([{ online: false }, { online: true }]); + }); + + it('a readable onLine wins over the event hint', () => { + const win = mkTarget(); + const nav = { onLine: true }; + const t = new ConnectivityTracker({ window: win, navigator: nav }); + const online: boolean[] = []; + t.on('online', (e) => online.push(e.online)); + win.fire('offline'); // stale event, the browser says online + expect(online).toEqual([true, true]); + }); + + it('a throwing addEventListener READ (cross-origin proxy) is reported and does not stop the other listeners', () => { + const onError = vi.fn(); + const conn = mkTarget(); + const win = {}; + Object.defineProperty(win, 'addEventListener', { + get() { + throw new Error('SecurityError'); + }, + }); + const t = new ConnectivityTracker( + { + window: win, + navigator: { onLine: true, connection: Object.assign(conn, { type: 'wifi' }) }, + }, + onError, + ); + expect(() => t.on('state', () => {})).not.toThrow(); + expect(onError.mock.calls.map((c) => (c[0] as Error).message)).toEqual([ + 'SecurityError', + 'SecurityError', + ]); // online + offline + expect(conn.count()).toBe(1); + }); + it('an absent onLine property is treated as online (old behavior)', () => { expect(new ConnectivityTracker({ navigator: {} }).current()).toEqual({ online: true }); }); @@ -490,6 +543,29 @@ describe('connectivityTrackerFor', () => { expect(first).not.toHaveBeenCalled(); }); + it('a throwing env.window getter is reported ONCE per call and reset still finds the tracker when the getter recovers', () => { + const onError = vi.fn(); + const nav = mkNav({ type: 'wifi' }); + const w = mkTarget(); + let fail = true; + const env = { + get window() { + if (fail) throw new Error('flaky'); + return w; + }, + navigator: nav, + }; + const t = connectivityTrackerFor(env, onError); + expect(onError).toHaveBeenCalledTimes(1); + t.on('state', () => {}); + expect((nav.connection as ReturnType).count()).toBe(1); + fail = false; // reset now resolves window first, but the tracker was keyed on navigator + resetConnectivityTracker(env); + expect((nav.connection as ReturnType).count()).toBe(0); + expect(connectivityTrackerFor({ navigator: nav })).not.toBe(t); + resetConnectivityTracker({ navigator: nav }); + }); + it('a throwing env.window / env.navigator read is reported and never fails', () => { const onError = vi.fn(); const env = {}; diff --git a/packages/trackers/src/browser/connectivity-tracker.ts b/packages/trackers/src/browser/connectivity-tracker.ts index 52692cb8..84a3efe4 100644 --- a/packages/trackers/src/browser/connectivity-tracker.ts +++ b/packages/trackers/src/browser/connectivity-tracker.ts @@ -139,8 +139,8 @@ export class ConnectivityTracker extends InterceptorBase { // reporter. #attach(): void { const win = this.#window as Partial | undefined; - this.#listen(win, 'online', () => this.#changed('online')); - this.#listen(win, 'offline', () => this.#changed('online')); + this.#listen(win, 'online', () => this.#changed('online', true)); + this.#listen(win, 'offline', () => this.#changed('online', false)); const nav = this.#navigator; const connection = nav === undefined @@ -166,7 +166,13 @@ export class ConnectivityTracker extends InterceptorBase { } #listen(target: Partial | undefined, type: string, run: () => void): void { - if (typeof target?.addEventListener !== 'function') return; + if (target === undefined) return; + // The READ can throw too (a cross-origin WindowProxy): reported, and the other listeners still attach. + const add = hostRead( + () => target.addEventListener, + (e) => this.#onError(e), + ); + if (typeof add !== 'function') return; const listener = (): void => { try { run(); @@ -177,7 +183,7 @@ export class ConnectivityTracker extends InterceptorBase { // Recorded BEFORE attaching so a failing addEventListener still leaves a removable record. this.#attached.push({ target, type, listener }); try { - target.addEventListener(type, listener); + add.call(target, type, listener); } catch (error) { this.#onError(error); } @@ -195,9 +201,14 @@ export class ConnectivityTracker extends InterceptorBase { } } - #changed(kind: 'online' | 'networkInfo'): void { - const state = this.#read(); - if (state === undefined) return; + // `hint` is what the event itself says. It is only evidence when `onLine` could not be read (a readable value wins). + #changed(kind: 'online' | 'networkInfo', hint?: boolean): void { + const read = this.#read(); + if (read === undefined) return; + const state: ConnectivityState = + kind === 'online' && read.online === undefined && hint !== undefined + ? { ...read, online: hint } + : read; if (kind === 'online') { if (state.online !== undefined) this.emit('online', { online: state.online }); } else if (state.networkInfo !== undefined) this.emit('networkInfo', state.networkInfo); @@ -244,12 +255,14 @@ export class ConnectivityTracker extends InterceptorBase { const registry = createTrackerRegistry(); -function keyOf(env: ConnectivityHost, onError?: (error: unknown) => void): object { - const win = hostRead(() => env.window, onError); - if (typeof win === 'object' && win !== null) return win; - const nav = hostRead(() => env.navigator, onError); - if (typeof nav === 'object' && nav !== null) return nav; - return env; +// The key is derived from the reads the caller already made (one read of each, so a flaky getter is reported once and +// the key cannot differ from the host it was built with). +function keyOf(win: object | undefined, nav: object | undefined, env: object): object { + return win ?? nav ?? env; +} + +function asObject(value: unknown): object | undefined { + return typeof value === 'object' && value !== null ? value : undefined; } /** @@ -261,20 +274,30 @@ export function connectivityTrackerFor( env: ConnectivityHost, onError?: (error: unknown) => void, ): ConnectivityTracker { - const win = hostRead(() => env.window, onError); - const nav = hostRead(() => env.navigator, onError); + const win = asObject(hostRead(() => env.window, onError)); + const nav = asObject(hostRead(() => env.navigator, onError)); const host: ConnectivityHost = { - ...(typeof win === 'object' && win !== null ? { window: win } : {}), - ...(typeof nav === 'object' && nav !== null ? { navigator: nav } : {}), + ...(win !== undefined ? { window: win } : {}), + ...(nav !== undefined ? { navigator: nav } : {}), }; return registry.for( - keyOf(env, onError), + keyOf(win, nav, env), () => new ConnectivityTracker(host, onError), (tracker) => tracker.rebind(host, onError), ); } -/** Test/teardown: drop the env's tracker (resetting it, so its listeners are released). */ +/** + * Test/teardown: drop the env's tracker (resetting it, so its listeners are released). Best-effort for a hostile env + * whose getters answer differently from call to call: the first of window / navigator / env that HAS a tracker wins. + */ export function resetConnectivityTracker(env: ConnectivityHost): void { - registry.reset(keyOf(env)); + const win = asObject(hostRead(() => env.window)); + const nav = asObject(hostRead(() => env.navigator)); + for (const key of [win, nav, env]) { + if (key !== undefined && registry.peek(key) !== undefined) { + registry.reset(key); + return; + } + } }