Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/browser-connectivity-tracker.md
Original file line number Diff line number Diff line change
@@ -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`, `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.
7 changes: 4 additions & 3 deletions docs/PROGRESS.md

Large diffs are not rendered by default.

46 changes: 41 additions & 5 deletions packages/browser/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {
type RequestJson,
Severity,
} from '@bugsee/protocol';
import { applicationTrackerFor } from '@bugsee/trackers/browser';
import { applicationTrackerFor, connectivityTrackerFor } from '@bugsee/trackers/browser';
import { strFromU8, unzipSync } from '@bugsee/util';
import { IDBFactory } from 'fake-indexeddb';
import { afterEach, describe, expect, it, vi } from 'vitest';
Expand Down Expand Up @@ -480,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(
Expand Down Expand Up @@ -1401,15 +1403,49 @@ 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);
expect(w.count('offline')).toBe(0);
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();
Expand Down
51 changes: 43 additions & 8 deletions packages/browser/src/trace-producers.sensors.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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';

Expand Down Expand Up @@ -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([
Expand All @@ -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,
},
Expand All @@ -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');
Expand All @@ -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' } }]);
});
Expand All @@ -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);
Expand All @@ -184,15 +192,42 @@ 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 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 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);
Expand Down
41 changes: 19 additions & 22 deletions packages/browser/src/trace-producers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,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 { MainThreadLagTracker } from './trackers/main-thread-lag-tracker';
import { type MemoryReading, type MemoryState, MemoryTracker } from './trackers/memory-tracker';
Expand Down Expand Up @@ -142,10 +140,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;
}
Expand All @@ -161,9 +159,10 @@ export class ConnectionProducer extends TraceProducerBase {
this.#off = undefined;
}

#publish({ onLine, connection }: ConnectionState): void {
#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),
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
Expand All @@ -173,6 +172,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 } : {}),
});
Expand Down Expand Up @@ -329,13 +332,16 @@ export class MainThreadLagProducer 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'] & ScreenSizeEnv['screen'];
/** Source of `online` / `offline` / `orientationchange` / `resize`, and the live `devicePixelRatio`. */
window?: ConnectionEnv['window'] & ScreenSizeEnv['window'];
window?: OrientationEnv['window'] & ScreenSizeEnv['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`. */
Expand All @@ -348,7 +354,7 @@ export interface BrowserTraceEnv extends BatteryEnv {
sensors?: boolean;
/** Drives the heap poll; default the global timers. */
scheduler?: Scheduler;
/** The shared ApplicationTracker feeding connection/orientation, app_state and fps; when absent connection/orientation listen on `window` and app_state/fps are omitted. */
/** The shared ApplicationTracker feeding orientation, app_state and fps; when absent orientation listens on `window` and app_state/fps are omitted. */
lifecycle?: Pick<ApplicationTracker, 'on' | 'current'>;
}

Expand Down Expand Up @@ -479,16 +485,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(
{
Expand Down
Loading