From 8fa435cb642c371e887b00cefa9cb474882429d5 Mon Sep 17 00:00:00 2001 From: DS Boyce <260543580+ds-boyce@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:03:30 -0700 Subject: [PATCH] Update and correct session reporting (#11747) Co-authored-by: Eric Bailey --- oxlint-suppressions.json | 8 - src/App.web.tsx | 2 + src/analytics/PassiveAnalytics.tsx | 18 +- src/analytics/features/index.ts | 10 +- src/analytics/identifiers/session.test.ts | 357 ++++++++-- src/analytics/identifiers/session.ts | 118 ++-- src/analytics/identifiers/session.web.ts | 54 -- .../identifiers/sessionStorage/index.ts | 22 + .../identifiers/sessionStorage/index.web.ts | 9 + .../sessionStorage/sessionStorage.test.ts | 83 +++ src/analytics/identifiers/util.ts | 9 - src/analytics/index.test.tsx | 607 ++++++++++++++++++ src/analytics/index.tsx | 53 +- src/analytics/metadata.ts | 7 +- src/analytics/metrics/types.ts | 4 +- src/analytics/useSessionActivity/README.md | 130 ++++ .../useSessionActivity/activity.test.ts | 250 ++++++++ src/analytics/useSessionActivity/index.ts | 2 + src/analytics/useSessionActivity/index.web.ts | 117 ++++ .../useSessionActivity.test.ts | 548 ++++++++++++++++ src/components/moderation/AppealForm.tsx | 2 +- src/storage/__tests__/index.test.ts | 18 +- src/storage/index.ts | 12 +- src/storage/schema.ts | 8 +- 24 files changed, 2241 insertions(+), 207 deletions(-) delete mode 100644 src/analytics/identifiers/session.web.ts create mode 100644 src/analytics/identifiers/sessionStorage/index.ts create mode 100644 src/analytics/identifiers/sessionStorage/index.web.ts create mode 100644 src/analytics/identifiers/sessionStorage/sessionStorage.test.ts delete mode 100644 src/analytics/identifiers/util.ts create mode 100644 src/analytics/index.test.tsx create mode 100644 src/analytics/useSessionActivity/README.md create mode 100644 src/analytics/useSessionActivity/activity.test.ts create mode 100644 src/analytics/useSessionActivity/index.ts create mode 100644 src/analytics/useSessionActivity/index.web.ts create mode 100644 src/analytics/useSessionActivity/useSessionActivity.test.ts diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index e5aaa4a40..6d93e2a2d 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -80,14 +80,6 @@ "count": 2 } }, - "src/analytics/identifiers/session.test.ts": { - "typescript/no-unsafe-call": { - "count": 9 - }, - "typescript/no-unsafe-member-access": { - "count": 9 - } - }, "src/analytics/metrics/client.test.ts": { "typescript/no-explicit-any": { "count": 1 diff --git a/src/App.web.tsx b/src/App.web.tsx index 067a5eea3..f6d42888b 100644 --- a/src/App.web.tsx +++ b/src/App.web.tsx @@ -72,6 +72,7 @@ import { setupDeviceId, } from '#/analytics' import {getDeviceId} from '#/analytics/identifiers' +import {useSessionActivity} from '#/analytics/useSessionActivity' import { prefetchLiveEvents, Provider as LiveEventsProvider, @@ -197,6 +198,7 @@ function InnerApp() { } function App() { + useSessionActivity() const [isReady, setIsReady] = useState(false) useEffect(() => { diff --git a/src/analytics/PassiveAnalytics.tsx b/src/analytics/PassiveAnalytics.tsx index c772ed09b..f02a6c399 100644 --- a/src/analytics/PassiveAnalytics.tsx +++ b/src/analytics/PassiveAnalytics.tsx @@ -1,28 +1,20 @@ -import {useEffect, useRef} from 'react' +import {useEffect} from 'react' -import {getCurrentState, onAppStateChange} from '#/lib/appState' +import {onAppStateChange} from '#/lib/appState' import {useAnalytics} from '#/analytics' /** - * Tracks passive analytics like app foreground/background time. + * Tracks app foreground/background transitions without measuring duration. */ export function PassiveAnalytics() { const ax = useAnalytics() - const lastActive = useRef( - getCurrentState() === 'active' ? performance.now() : null, - ) useEffect(() => { const sub = onAppStateChange(state => { if (state === 'active') { - lastActive.current = performance.now() ax.metric('state:foreground', {}) - } else if (lastActive.current !== null) { - ax.metric('state:background', { - secondsActive: Math.round( - (performance.now() - lastActive.current) / 1e3, - ), - }) + } else { + ax.metric('state:background', {}) } // if (IS_DEV || IS_TESTFLIGHT) { diff --git a/src/analytics/features/index.ts b/src/analytics/features/index.ts index b8bfc0828..17f59f1c8 100644 --- a/src/analytics/features/index.ts +++ b/src/analytics/features/index.ts @@ -44,6 +44,11 @@ const sdkOptions = { enableDevMode: env.IS_INTERNAL, } const bootstrap = readFeatureBootstrap(sdkOptions) + +/** + * Shared SDK instance. Assumes a single active account context, with attributes + * supplied by AnalyticsFeaturesContext before its children evaluate features. + */ export const features = createGrowthBook(sdkOptions, bootstrap) /** @@ -166,6 +171,10 @@ export function getTargetedFeatures(i18n: I18n) { * attributes are manually configured in the GrowthBook dashboard. So these * values need to match exactly. Therefore, let's add them here manually to and * not spread them to avoid mistakes. + * + * Analytics session IDs are event metadata only, not feature targeting or + * experiment bucketing inputs. They are intentionally excluded from GrowthBook + * attributes, so session rotation does not require feature reevaluation. */ export function setAttributes({ base, @@ -175,7 +184,6 @@ export function setAttributes({ }: Metadata) { void features.setAttributes({ deviceId: base.deviceId, - sessionId: base.sessionId, platform: base.platform, appVersion: base.appVersion, countryCode: geolocation.countryCode, diff --git a/src/analytics/identifiers/session.test.ts b/src/analytics/identifiers/session.test.ts index ab334ff49..30dad326a 100644 --- a/src/analytics/identifiers/session.test.ts +++ b/src/analytics/identifiers/session.test.ts @@ -1,79 +1,328 @@ +const NOW = new Date('2026-09-22T12:00:00.000Z') +const mockDeviceValues = new Map() +const mockDeviceGetRaw = jest.fn((key: string[]) => { + if (!mockDeviceValues.has(key[0])) return undefined + return JSON.stringify({data: mockDeviceValues.get(key[0])}) +}) +const mockDeviceListeners = new Set<() => void>() +const mockDeviceSet = jest.fn((key: string[], value: unknown) => { + mockDeviceValues.set(key[0], value) + emitStorageChange() +}) +const mockDeviceSubscribe = jest.fn((_key: string[], listener: () => void) => { + mockDeviceListeners.add(listener) + return {remove: () => mockDeviceListeners.delete(listener)} +}) +const mockAppStateListeners = new Set<(state: string) => void>() +const mockOnAppStateChange = jest.fn((listener: (state: string) => void) => { + mockAppStateListeners.add(listener) + return {remove: () => mockAppStateListeners.delete(listener)} +}) +const mockUuidV4 = jest.fn() +let mockIsNative = true +let sessionValidation: jest.SpyInstance + +jest.mock('react-native-uuid', () => ({ + __esModule: true, + default: {v4: mockUuidV4}, +})) +jest.mock('#/env', () => ({IS_NATIVE: mockIsNative})) +jest.mock('#/analytics/identifiers/sessionStorage', () => + jest.requireActual( + mockIsNative + ? '#/analytics/identifiers/sessionStorage/index.ts' + : '#/analytics/identifiers/sessionStorage/index.web.ts', + ), +) jest.mock('#/storage', () => ({ device: { - get: jest.fn(), - set: jest.fn(), + getRaw: mockDeviceGetRaw, + set: mockDeviceSet, + addOnValueChangedListener: mockDeviceSubscribe, }, })) - -jest.mock('#/analytics/identifiers/util', () => ({ - isSessionIdExpired: jest.fn(), -})) - jest.mock('#/lib/appState', () => ({ - onAppStateChange: jest.fn(() => ({remove: jest.fn()})), + onAppStateChange: mockOnAppStateChange, })) beforeEach(() => { - jest.resetModules() + jest.useFakeTimers() + jest.setSystemTime(NOW) jest.clearAllMocks() + mockDeviceValues.clear() + mockDeviceListeners.clear() + mockAppStateListeners.clear() + mockUuidV4.mockReset().mockReturnValue('session-a') +}) +afterEach(() => { + jest.restoreAllMocks() + jest.useRealTimers() }) -function getMocks() { - const {device} = require('#/storage') - const {isSessionIdExpired} = require('#/analytics/identifiers/util') - return { - device: jest.mocked(device), - isSessionIdExpired: jest.mocked(isSessionIdExpired), - } +function emitStorageChange() { + mockDeviceListeners.forEach(listener => listener()) +} + +function setStoredSession(id: string, lastEventAt?: number) { + mockDeviceValues.set('analyticsSession', {id, lastEventAt}) + emitStorageChange() } -describe('session initialization', () => { - it('creates new session and sets timestamp when none exists', () => { - const {device, isSessionIdExpired} = getMocks() - device.get.mockReturnValue(undefined) - isSessionIdExpired.mockReturnValue(false) - - const {getInitialSessionId} = require('./session') - const id = getInitialSessionId() - - expect(id).toBeDefined() - expect(typeof id).toBe('string') - expect(device.set).toHaveBeenCalledWith(['nativeSessionId'], id) - expect(device.set).toHaveBeenCalledWith( - ['nativeSessionIdLastEventAt'], - expect.any(Number), - ) +function emitAppState(state: string) { + mockAppStateListeners.forEach(listener => listener(state)) +} + +function loadSession(): typeof import('./session') { + let session: typeof import('./session') | undefined + jest.isolateModules(() => { + const {z} = require('zod') as typeof import('zod') + sessionValidation = jest.spyOn(z.ZodType.prototype, 'safeParse') + session = require('./session') }) + return session! +} - it('reuses existing session when not expired', () => { - const {device, isSessionIdExpired} = getMocks() - const existingId = 'existing-session-id' - device.get.mockImplementation((key: string[]) => { - if (key[0] === 'nativeSessionId') return existingId - if (key[0] === 'nativeSessionIdLastEventAt') return Date.now() - return undefined +describe('native analytics sessions', () => { + const isNative = true + const ttl = 5 * 60 * 1e3 + beforeEach(() => { + mockIsNative = isNative + }) + + it('creates and persists the ID and timestamp in one write', () => { + const {getSessionId} = loadSession() + + expect(getSessionId()).toBe('session-a') + expect(mockUuidV4).toHaveBeenCalledTimes(1) + expect(mockDeviceSet).toHaveBeenCalledTimes(1) + expect(mockDeviceSet).toHaveBeenCalledWith(['analyticsSession'], { + id: 'session-a', + lastEventAt: NOW.getTime(), }) - isSessionIdExpired.mockReturnValue(false) + }) + + it('reuses validated data with native cached raw reads', () => { + const {getSessionId} = loadSession() + getSessionId() + mockDeviceGetRaw.mockClear() + sessionValidation.mockClear() + const parse = jest.spyOn(JSON, 'parse') + + for (let i = 0; i < 100; i++) getSessionId() + + expect(sessionValidation).not.toHaveBeenCalled() + expect(parse).not.toHaveBeenCalled() + expect(mockDeviceGetRaw).toHaveBeenCalledTimes(isNative ? 0 : 100) + }) + + it('parses and validates a changed raw value once', () => { + const {getSessionId} = loadSession() + getSessionId() + mockDeviceGetRaw.mockClear() + sessionValidation.mockClear() + const parse = jest.spyOn(JSON, 'parse') - const {getInitialSessionId} = require('./session') + setStoredSession('other-runtime-session', Date.now()) + expect(getSessionId()).toBe('other-runtime-session') + expect(getSessionId()).toBe('other-runtime-session') - expect(getInitialSessionId()).toBe(existingId) + expect(parse).toHaveBeenCalledTimes(1) + expect(sessionValidation).toHaveBeenCalledTimes(1) + expect(mockDeviceGetRaw).toHaveBeenCalledTimes(isNative ? 1 : 2) + expect(mockDeviceSubscribe).toHaveBeenCalledTimes(isNative ? 1 : 0) }) - it('creates new session when existing is expired', () => { - const {device, isSessionIdExpired} = getMocks() - const existingId = 'existing-session-id' - device.get.mockImplementation((key: string[]) => { - if (key[0] === 'nativeSessionId') return existingId - if (key[0] === 'nativeSessionIdLastEventAt') return Date.now() - 999999 - return undefined + it('observes timestamp-only changes before deciding whether to rotate', () => { + const {getSessionId} = loadSession() + expect(getSessionId()).toBe('session-a') + setStoredSession('session-a', Date.now() - ttl) + mockUuidV4.mockReturnValueOnce('session-b') + + emitAppState('active') + + expect(getSessionId()).toBe('session-b') + }) + + it('reuses an unexpired stored session', () => { + mockDeviceValues.set('analyticsSession', { + id: 'existing-session', + lastEventAt: NOW.getTime() - ttl + 1, + extra: true, }) - isSessionIdExpired.mockReturnValue(true) + const {getSessionId} = loadSession() + + expect(getSessionId()).toBe('existing-session') + expect(mockUuidV4).not.toHaveBeenCalled() + expect(mockDeviceValues.get('analyticsSession')).toEqual({ + id: 'existing-session', + lastEventAt: NOW.getTime(), + }) + }) + + it('rotates an expired stored session on startup at the exact boundary', () => { + setStoredSession('existing-session', NOW.getTime() - ttl) + const {getSessionId} = loadSession() + + expect(getSessionId()).toBe('session-a') + expect(mockUuidV4).toHaveBeenCalledTimes(1) + }) + + it.each([undefined, null, '123', Number.NaN, Infinity, -Infinity])( + 'preserves a session with an invalid or missing timestamp: %s', + lastEventAt => { + mockDeviceValues.set('analyticsSession', { + id: 'existing-session', + lastEventAt, + }) + const {getSessionId} = loadSession() + + expect(getSessionId()).toBe('existing-session') + expect(mockUuidV4).not.toHaveBeenCalled() + }, + ) + + it.each([undefined, null, 'session-a', [], {}, {id: ''}, {id: 123}])( + 'replaces an invalid record: %j', + record => { + mockDeviceValues.set('analyticsSession', record) + const {getSessionId} = loadSession() + + expect(getSessionId()).toBe('session-a') + expect(mockDeviceSet).toHaveBeenCalledWith(['analyticsSession'], { + id: 'session-a', + lastEventAt: NOW.getTime(), + }) + }, + ) + + it.each(['{', 'null', '[]', '42', '"string"', '{}'])( + 'replaces malformed or invalid serialized storage: %s', + raw => { + mockDeviceGetRaw.mockReturnValueOnce(raw) + expect(loadSession().getSessionId()).toBe('session-a') + }, + ) + + describe.each(['read', 'active', 'inactive', 'background'])( + 'recovering through %s', + trigger => { + it.each(['missing', 'cleared', 'invalid', 'malformed JSON'])( + 'persists a fresh session after rotation when storage is %s', + failure => { + const {getSessionId} = loadSession() + expect(getSessionId()).toBe('session-a') + emitAppState('background') + jest.advanceTimersByTime(ttl) + mockUuidV4.mockReturnValueOnce('session-b') + emitAppState('active') + expect(getSessionId()).toBe('session-b') + + if (failure === 'missing') { + mockDeviceValues.delete('analyticsSession') + } else if (failure === 'cleared') { + mockDeviceValues.clear() + } else if (failure === 'invalid') { + mockDeviceValues.set('analyticsSession', {id: ''}) + } else { + mockDeviceGetRaw.mockReturnValueOnce('{') + } + emitStorageChange() + jest.advanceTimersByTime(1_000) + mockUuidV4.mockReturnValueOnce('session-c') + mockDeviceSet.mockClear() + + if (trigger !== 'read') emitAppState(trigger) + expect(getSessionId()).toBe('session-c') + expect(getSessionId()).toBe('session-c') + expect(mockUuidV4).toHaveBeenCalledTimes(3) + expect(mockDeviceSet).toHaveBeenCalledTimes(1) + expect(mockDeviceValues.get('analyticsSession')).toEqual({ + id: 'session-c', + lastEventAt: Date.now(), + }) + }, + ) + }, + ) + + it('does not rotate before the inactivity threshold', () => { + setStoredSession('existing-session', NOW.getTime()) + const {getSessionId} = loadSession() + + emitAppState('background') + jest.advanceTimersByTime(ttl - 1) + emitAppState('active') + + expect(getSessionId()).toBe('existing-session') + expect(mockUuidV4).not.toHaveBeenCalled() + }) + + it('rotates once at the exact boundary without React consumers', () => { + setStoredSession('existing-session', NOW.getTime()) + const {getSessionId} = loadSession() + expect(mockOnAppStateChange).toHaveBeenCalledTimes(1) + + emitAppState('background') + jest.advanceTimersByTime(ttl) + mockDeviceSet.mockClear() + emitAppState('active') + + expect(mockUuidV4).toHaveBeenCalledTimes(1) + expect([getSessionId(), getSessionId(), getSessionId()]).toEqual([ + 'session-a', + 'session-a', + 'session-a', + ]) + expect(mockDeviceSubscribe).toHaveBeenCalledTimes(isNative ? 1 : 0) + expect(mockDeviceSet).toHaveBeenCalledTimes(1) + expect(mockDeviceSet).toHaveBeenCalledWith(['analyticsSession'], { + id: 'session-a', + lastEventAt: NOW.getTime() + ttl, + }) + expect([...mockDeviceValues.keys()]).toEqual(['analyticsSession']) + }) + + it('keeps the original last-event semantics across intermediate states', () => { + setStoredSession('existing-session', NOW.getTime()) + const {getSessionId} = loadSession() + + emitAppState('inactive') + jest.advanceTimersByTime(ttl - 1) + emitAppState('background') + jest.advanceTimersByTime(1) + emitAppState('active') + + expect(getSessionId()).toBe('existing-session') + expect(mockUuidV4).not.toHaveBeenCalled() + }) + + it('observes local storage writes without React consumers', () => { + const {getSessionId} = loadSession() + + mockDeviceSet(['analyticsSession'], { + id: 'local-session', + lastEventAt: Date.now(), + }) + + expect(getSessionId()).toBe('local-session') + expect(mockDeviceSubscribe).toHaveBeenCalledTimes(isNative ? 1 : 0) + }) + + it('keeps tracking repeated lifecycle events when no one reads the ID', () => { + const {getSessionId} = loadSession() - const {getInitialSessionId} = require('./session') - const id = getInitialSessionId() + emitAppState('background') + jest.advanceTimersByTime(ttl) + mockUuidV4.mockReturnValueOnce('session-b') + emitAppState('active') + emitAppState('background') + jest.advanceTimersByTime(ttl) + mockUuidV4.mockReturnValueOnce('session-c') + emitAppState('active') - expect(id).not.toBe(existingId) - expect(device.set).toHaveBeenCalledWith(['nativeSessionId'], id) + expect(getSessionId()).toBe('session-c') + expect(mockOnAppStateChange).toHaveBeenCalledTimes(1) + expect(mockAppStateListeners.size).toBe(1) + expect(mockDeviceSubscribe).toHaveBeenCalledTimes(isNative ? 1 : 0) }) }) diff --git a/src/analytics/identifiers/session.ts b/src/analytics/identifiers/session.ts index a681d41e1..7c40c3731 100644 --- a/src/analytics/identifiers/session.ts +++ b/src/analytics/identifiers/session.ts @@ -1,50 +1,94 @@ -import {useEffect, useState} from 'react' +import {type AppStateStatus} from 'react-native' import uuid from 'react-native-uuid' +import {z} from 'zod' import {onAppStateChange} from '#/lib/appState' -import {isSessionIdExpired} from '#/analytics/identifiers/util' +import {readRawSessionRecord} from '#/analytics/identifiers/sessionStorage' +import * as env from '#/env' import {device} from '#/storage' -let sessionId = (() => { - const existing = device.get(['nativeSessionId']) - const lastEvent = device.get(['nativeSessionIdLastEventAt']) - const id = existing && !isSessionIdExpired(lastEvent) ? existing : uuid.v4() - device.set(['nativeSessionId'], id) - device.set(['nativeSessionIdLastEventAt'], Date.now()) - return id -})() - -export function getInitialSessionId() { - return sessionId +const ONE_MIN = 60 * 1e3 +const TTL = 5 * ONE_MIN + +const sessionRecordSchema = z.object({ + id: z.string().min(1), + lastEventAt: z.number().finite().optional().catch(undefined), +}) +/** Raw device storage includes the `{data: value}` envelope. */ +const storedSessionRecordSchema = z.object({data: sessionRecordSchema}) + +/** lastEventAt starts at creation, then tracks native lifecycle or web activity. */ +export type SessionRecord = z.infer + +function isSessionIdExpired(since: number | undefined) { + if (since === undefined) return false + return Date.now() - since >= TTL } /** - * Gets the current session ID. Freshness depends on `useSessionId` being - * mounted, which handles refreshing this value between foreground/background - * transitions. Since that's mounted in `analytics/index.tsx`, this value can - * generally be trusted to be up to date. + * Keep only the last raw value and its validation result. Comparing the entire + * serialized record also detects timestamp-only changes that affect expiry. */ +let cachedRaw: string | undefined +let cachedRecord: SessionRecord | undefined + +/** Validate only when the platform-specific reader returns a changed value. */ +export function readSessionRecord() { + const raw = readRawSessionRecord() + + /** + * Lightweight memoization to avoid re-parsing and validating if raw value + * didn't change + */ + if (raw === cachedRaw) return cachedRecord + + let record: SessionRecord | undefined + if (raw) { + try { + const result = storedSessionRecordSchema.safeParse(JSON.parse(raw)) + if (result.success) record = result.data.data + } catch (error) { + if (!(error instanceof SyntaxError)) throw error + } + } + /* + * Missing or invalid data must evict the previous valid result too, allowing + * callers to create a fresh session instead of reviving a stale one. + */ + cachedRaw = raw + cachedRecord = record + return record +} + +function createSessionRecord(): SessionRecord { + const record: SessionRecord = { + id: String(uuid.v4()), + lastEventAt: Date.now(), + } + device.set(['analyticsSession'], record) + return record +} + +/** Resolve identity without refreshing an existing record's activity time. */ export function getSessionId() { - return sessionId + // Missing or corrupt storage starts a fresh session, never an old fallback ID. + return (readSessionRecord() ?? createSessionRecord()).id +} + +function onAppStateChanged(state: AppStateStatus) { + const existing = readSessionRecord() + if ( + !existing || + (state === 'active' && isSessionIdExpired(existing.lastEventAt)) + ) { + createSessionRecord() + return + } + device.set(['analyticsSession'], {...existing, lastEventAt: Date.now()}) } -export function useSessionId() { - const [id, setId] = useState(() => sessionId) - - useEffect(() => { - const sub = onAppStateChange(state => { - if (state === 'active') { - const lastEvent = device.get(['nativeSessionIdLastEventAt']) - if (isSessionIdExpired(lastEvent)) { - sessionId = uuid.v4() - device.set(['nativeSessionId'], sessionId) - setId(sessionId) - } - } - device.set(['nativeSessionIdLastEventAt'], Date.now()) - }) - return () => sub.remove() - }, []) - - return id +// Web activity belongs to the centrally mounted hook, not RN Web AppState. +if (env.IS_NATIVE) { + onAppStateChanged('active') + onAppStateChange(onAppStateChanged) } diff --git a/src/analytics/identifiers/session.web.ts b/src/analytics/identifiers/session.web.ts deleted file mode 100644 index f9e769e29..000000000 --- a/src/analytics/identifiers/session.web.ts +++ /dev/null @@ -1,54 +0,0 @@ -import {useEffect, useState} from 'react' -import uuid from 'react-native-uuid' - -import {onAppStateChange} from '#/lib/appState' -import {isSessionIdExpired} from '#/analytics/identifiers/util' - -const SESSION_ID_KEY = 'bsky_session_id' -const LAST_EVENT_KEY = 'bsky_session_id_last_event_at' - -let sessionId = (() => { - const existing = window.sessionStorage.getItem(SESSION_ID_KEY) - const lastEventStr = window.sessionStorage.getItem(LAST_EVENT_KEY) - const lastEvent = lastEventStr ? Number(lastEventStr) : undefined - const id = existing && !isSessionIdExpired(lastEvent) ? existing : uuid.v4() - window.sessionStorage.setItem(SESSION_ID_KEY, id) - window.sessionStorage.setItem(LAST_EVENT_KEY, String(Date.now())) - return id -})() - -export function getInitialSessionId() { - return sessionId -} - -/** - * Gets the current session ID. Freshness depends on `useSessionId` being - * mounted, which handles refreshing this value between foreground/background - * transitions. Since that's mounted in `analytics/index.tsx`, this value can - * generally be trusted to be up to date. - */ -export function getSessionId() { - return sessionId -} - -export function useSessionId() { - const [id, setId] = useState(() => sessionId) - - useEffect(() => { - const sub = onAppStateChange(state => { - if (state === 'active') { - const lastEventStr = window.sessionStorage.getItem(LAST_EVENT_KEY) - const lastEvent = lastEventStr ? Number(lastEventStr) : undefined - if (isSessionIdExpired(lastEvent)) { - sessionId = uuid.v4() - window.sessionStorage.setItem(SESSION_ID_KEY, sessionId) - setId(sessionId) - } - } - window.sessionStorage.setItem(LAST_EVENT_KEY, String(Date.now())) - }) - return () => sub.remove() - }, []) - - return id -} diff --git a/src/analytics/identifiers/sessionStorage/index.ts b/src/analytics/identifiers/sessionStorage/index.ts new file mode 100644 index 000000000..bebafce9d --- /dev/null +++ b/src/analytics/identifiers/sessionStorage/index.ts @@ -0,0 +1,22 @@ +import {device} from '#/storage' + +let cachedRaw: string | undefined +let needsRead = true + +/* + * MMKV synchronously notifies local writes, deletes, and clears. Keep this + * listener for the module's lifetime so recovery works without React consumers. + * Invalidate lazily rather than reading storage inside another writer's callback. + */ +device.addOnValueChangedListener(['analyticsSession'], () => { + needsRead = true +}) + +/** Native reads stay in memory until the persisted session changes. */ +export function readRawSessionRecord() { + if (needsRead) { + cachedRaw = device.getRaw(['analyticsSession']) + needsRead = false + } + return cachedRaw +} diff --git a/src/analytics/identifiers/sessionStorage/index.web.ts b/src/analytics/identifiers/sessionStorage/index.web.ts new file mode 100644 index 000000000..79816618b --- /dev/null +++ b/src/analytics/identifiers/sessionStorage/index.web.ts @@ -0,0 +1,9 @@ +import {device} from '#/storage' + +/** + * Read through on web so other tabs' writes are visible immediately. MMKV's + * listeners only cover local writes, not changes from another tab. + */ +export function readRawSessionRecord() { + return device.getRaw(['analyticsSession']) +} diff --git a/src/analytics/identifiers/sessionStorage/sessionStorage.test.ts b/src/analytics/identifiers/sessionStorage/sessionStorage.test.ts new file mode 100644 index 000000000..a3e74feea --- /dev/null +++ b/src/analytics/identifiers/sessionStorage/sessionStorage.test.ts @@ -0,0 +1,83 @@ +import {readRawSessionRecord as readNative} from '#/analytics/identifiers/sessionStorage' +import {readRawSessionRecord as readWeb} from '#/analytics/identifiers/sessionStorage/index.web' +import {device} from '#/storage' + +const record = {id: 'session-a', lastEventAt: 1_000} + +beforeEach(() => { + device.set(['analyticsSession'], record) +}) +afterEach(() => { + jest.restoreAllMocks() +}) + +describe('native session reads', () => { + it('avoids storage reads after warming the cache', () => { + const getRaw = jest.spyOn(device, 'getRaw') + expect(readNative()).toBe(JSON.stringify({data: record})) + + for (let i = 0; i < 100; i++) readNative() + + expect(getRaw).toHaveBeenCalledTimes(1) + }) + + it.each(['remove', 'removeAll'] as const)( + 'invalidates lazily on %s and subsequent writes', + operation => { + readNative() + const getRaw = jest.spyOn(device, 'getRaw') + + if (operation === 'remove') { + device.remove(['analyticsSession']) + } else { + device.removeAll() + } + expect(getRaw).not.toHaveBeenCalled() + expect(readNative()).toBeUndefined() + expect(readNative()).toBeUndefined() + expect(getRaw).toHaveBeenCalledTimes(1) + + const next = {...record, id: 'session-b'} + device.set(['analyticsSession'], next) + expect(getRaw).toHaveBeenCalledTimes(1) + expect(readNative()).toBe(JSON.stringify({data: next})) + expect(getRaw).toHaveBeenCalledTimes(2) + }, + ) + + it('ignores writes to unrelated keys', () => { + readNative() + const getRaw = jest.spyOn(device, 'getRaw') + + device.set(['deviceId'], 'device-a') + + expect(readNative()).toBe(JSON.stringify({data: record})) + expect(getRaw).not.toHaveBeenCalled() + }) + + it('retries failed reads instead of caching a failure or returning stale data', () => { + readNative() + const next = {...record, id: 'session-b'} + device.set(['analyticsSession'], next) + const error = new Error('Storage unavailable') + const getRaw = jest.spyOn(device, 'getRaw').mockImplementationOnce(() => { + throw error + }) + + expect(() => readNative()).toThrow(error) + expect(readNative()).toBe(JSON.stringify({data: next})) + expect(getRaw).toHaveBeenCalledTimes(2) + }) +}) + +it('reads through on web, including changes without a local notification', () => { + const getRaw = jest.spyOn(device, 'getRaw') + expect(readWeb()).toBe(JSON.stringify({data: record})) + + // Simulate another tab's write without emitting a local MMKV notification. + const next = JSON.stringify({data: {...record, id: 'other-tab-session'}}) + getRaw.mockReturnValueOnce(next) + + expect(readWeb()).toBe(next) + expect(getRaw).toHaveBeenCalledTimes(2) +}) diff --git a/src/analytics/identifiers/util.ts b/src/analytics/identifiers/util.ts deleted file mode 100644 index 2d68f9b90..000000000 --- a/src/analytics/identifiers/util.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as env from '#/env' - -const ONE_MIN = 60 * 1e3 -const TTL = (env.IS_NATIVE ? 5 : 30) * ONE_MIN // 5 min on native - -export function isSessionIdExpired(since: number | undefined) { - if (since === undefined) return false - return Date.now() - since >= TTL -} diff --git a/src/analytics/index.test.tsx b/src/analytics/index.test.tsx new file mode 100644 index 000000000..aad46fd48 --- /dev/null +++ b/src/analytics/index.test.tsx @@ -0,0 +1,607 @@ +import {act, render} from '@testing-library/react-native' + +import {onAppStateChange} from '#/lib/appState' +import {getEntries} from '#/logger/logDump' +import { + type AnalyticsBaseContextType, + AnalyticsContext, + type AnalyticsContextType, + AnalyticsFeaturesContext, + type Features, + useAnalytics, + useAnalyticsBase, +} from '#/analytics' +import {features, setAttributes} from '#/analytics/features' +import {getDeviceId, getSessionId} from '#/analytics/identifiers' +import { + type MergeableMetadata, + type Metadata, + type MetricMetadata, +} from '#/analytics/metadata' +import {type Metrics, metrics} from '#/analytics/metrics' +import {MetricsClient} from '#/analytics/metrics/client' +import {recordSessionActivity} from '#/analytics/useSessionActivity/index.web' +import {useMeta} from '#/analytics/utils' +import {useGeolocationServiceResponse} from '#/geolocation/service' +import {account, device} from '#/storage' + +jest.mock('#/lib/appState', () => ({ + onAppStateChange: jest.fn(() => ({remove: jest.fn()})), +})) +jest.mock('#/env', () => ({ENV: 'test', IS_NATIVE: true})) +jest.mock('#/logger/transports/sentry', () => ({sentryTransport: jest.fn()})) +jest.mock('#/logger/transports/console', () => ({consoleTransport: jest.fn()})) +jest.mock('#/logger/sentry/featureFlags', () => ({ + recordFeatureFlagEvaluation: jest.fn(), +})) +jest.mock('#/analytics/features/bootstrap', () => ({ + readFeatureBootstrap: () => ({features: {}}), +})) +jest.mock('#/analytics/features/client', () => { + const {GrowthBook} = jest.requireActual< + typeof import('@growthbook/growthbook') + >('@growthbook/growthbook') + return { + createGrowthBook: () => new GrowthBook(), + refreshGrowthBook: () => Promise.resolve(), + } +}) +jest.mock('#/analytics/metrics', () => ({metrics: {track: jest.fn()}})) +jest.mock('#/analytics/identifiers/device', () => ({ + getDeviceId: jest.fn(), + getAndMigrateDeviceId: () => Promise.resolve('device-a'), +})) +jest.mock('#/geolocation/service', () => ({ + useGeolocationServiceResponse: jest.fn(), +})) + +const FIVE_MINUTES = 5 * 60 * 1e3 +let contexts: Metadata[] +let baseAx: AnalyticsBaseContextType +let ax: AnalyticsContextType +let childLogger: AnalyticsContextType['logger'] +let renderCount: number +let featureNumber = 0 + +function CaptureBase({index}: {index: number}) { + baseAx = useAnalyticsBase() + contexts[index] = baseAx.metadata + return null +} + +function CaptureAnalytics() { + renderCount++ + ax = useAnalytics() + childLogger = ax.logger.useChild(ax.logger.Context.Notifications) + return null +} + +function Tree({session, preferences}: MergeableMetadata) { + return ( + + + + + + + + + + + + + ) +} + +beforeEach(() => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-09-22T12:00:00Z')) + jest.mocked(metrics.track).mockReset() + jest.mocked(getDeviceId).mockReturnValue('device-a') + contexts = [] + renderCount = 0 + device.set(['analyticsSession'], {id: 'session-a', lastEventAt: Date.now()}) + account.set(['did:plc:a', 'isBetaUser'], true) + account.set(['did:plc:b', 'isBetaUser'], false) + jest.mocked(useGeolocationServiceResponse).mockReturnValue({ + countryCode: 'US', + regionCode: 'WI', + city: 'Madison', + }) + features.setDeferredTrackingCalls([]) + features.setFeatures({}) +}) +afterEach(() => { + features.setRenderer(null) + jest.restoreAllMocks() + jest.clearAllTimers() + jest.useRealTimers() +}) + +function rotateSession() { + const onChange = jest.mocked(onAppStateChange).mock.calls[0][0] + onChange('background') + jest.setSystemTime(Date.now() + FIVE_MINUTES) + onChange('active') +} + +function lastMetricMetadata() { + return jest.mocked(metrics.track).mock.calls.at(-1)![2] as MetricMetadata +} + +/** Unique keys avoid the SDK's exposure deduplication between test cases. */ +function installFeature(hashAttribute: 'did' | 'deviceId' = 'deviceId') { + const feature = `test-feature-${++featureNumber}` as Features + features.setFeatures({ + [feature]: { + defaultValue: false, + rules: [ + { + key: feature, + hashAttribute, + variations: [true, true], + }, + ], + }, + }) + return feature +} + +function expectExposures(did = 'did:plc:a') { + const calls = jest.mocked(metrics.track).mock.calls + expect(calls.map(([event]) => event)).toEqual([ + 'experiment:viewed', + 'feature:viewed', + ]) + for (const [, , metadata] of calls) { + expect(metadata).toMatchObject({ + base: {deviceId: ax.metadata.base.deviceId, sessionId: getSessionId()}, + session: {did}, + }) + } +} + +it('inherits device identity without session state or rerenders on rotation', () => { + render( + , + ) + const previousContext = ax + const previousMetadata = [...contexts] + const previousRenderCount = renderCount + + act(() => rotateSession()) + expect(getSessionId()).not.toBe('session-a') + expect(renderCount).toBe(previousRenderCount) + expect(ax).toBe(previousContext) + for (const [index, metadata] of contexts.entries()) { + expect(metadata).toBe(previousMetadata[index]) + expect(metadata.base).not.toHaveProperty('sessionId') + expect(metadata.base.deviceId).toBe('device-a') + expect(metadata.geolocation).toEqual({ + countryCode: 'US', + regionCode: 'WI', + city: 'Madison', + }) + } + expect(contexts[0].session).toBeUndefined() + expect(contexts[1].session?.did).toBe('did:plc:a') + expect(contexts[1].preferences).toBeUndefined() + expect(ax.metadata).toMatchObject({ + base: {isBetaUser: true}, + session: {did: 'did:plc:a'}, + preferences: {appLanguage: 'en', contentLanguages: ['en']}, + }) + // Analytics session IDs never participate in feature evaluation. + expect(features.getAttributes()).not.toHaveProperty('sessionId') + expect(metrics.track).not.toHaveBeenCalled() +}) + +it('tracks lifecycle before mount and between mounts without context subscriptions', () => { + rotateSession() + const beforeMount = getSessionId() + expect(beforeMount).not.toBe('session-a') + const view = render() + ax.metric('state:foreground', {}) + expect(lastMetricMetadata().base.sessionId).toBe(beforeMount) + view.unmount() + + rotateSession() + expect(getSessionId()).not.toBe(beforeMount) + render() + ax.metric('state:foreground', {}) + expect(lastMetricMetadata().base.sessionId).toBe(getSessionId()) +}) + +it('updates inherited account, preferences, and geolocation', () => { + const view = render( + , + ) + jest + .mocked(useGeolocationServiceResponse) + .mockReturnValue({countryCode: 'CA', regionCode: 'ON', city: 'Toronto'}) + view.rerender( + , + ) + + expect(ax.metadata).toMatchObject({ + base: {isBetaUser: false}, + session: {did: 'did:plc:b'}, + preferences: {appLanguage: 'fr'}, + geolocation: {countryCode: 'CA'}, + }) + ax.metric('state:foreground', {}) + expect(lastMetricMetadata()).toMatchObject({ + base: {...ax.metadata.base, sessionId: getSessionId()}, + session: ax.metadata.session, + preferences: ax.metadata.preferences, + geolocation: ax.metadata.geolocation, + }) + childLogger.info('updated logger') + expect(getEntries()[0].metadata.__metadata__).toMatchObject({ + countryCode: 'CA', + deviceId: ax.metadata.base.deviceId, + sessionId: getSessionId(), + }) + expect(features.getAttributes()).toMatchObject({ + did: 'did:plc:b', + isBetaUser: false, + appLanguage: 'fr', + countryCode: 'CA', + }) +}) + +it.each(['default', 'nested'])( + 'preserves device identity and snapshots the session for captured metrics in %s context', + context => { + render( + context === 'default' ? ( + + ) : ( + + ), + ) + const metric = baseAx.metric + const metadata = Object.freeze({ + ...baseAx.metadata, + __meta: true, + base: Object.freeze({ + ...baseAx.metadata.base, + deviceId: 'device-a', + sessionId: 'obsolete-session', + }), + }) + metric('state:foreground', {}, metadata) + const previousMetric = lastMetricMetadata() + expect(previousMetric.base).toMatchObject({ + deviceId: 'device-a', + sessionId: getSessionId(), + }) + expect(previousMetric).not.toHaveProperty('__meta') + + act(() => rotateSession()) + jest.mocked(getDeviceId).mockReturnValue('device-b') + metric('state:foreground', {}, metadata) + expect(lastMetricMetadata().base).toMatchObject({ + deviceId: 'device-a', + sessionId: getSessionId(), + }) + expect(previousMetric.base).toMatchObject({ + deviceId: 'device-a', + sessionId: 'session-a', + }) + expect(metadata.__meta).toBe(true) + expect(metadata.base).toMatchObject({ + deviceId: 'device-a', + sessionId: 'obsolete-session', + }) + }, +) + +it.each(['debug', 'info', 'log', 'warn', 'error'] as const)( + 'preserves device identity and snapshots the session in captured parent and child %s callbacks', + level => { + render() + const parentLog = ax.logger[level] + const childLog = childLogger[level] + parentLog('previous parent') + childLog('previous child') + const previousLogs = getEntries().slice(0, 2) + + act(() => rotateSession()) + jest.mocked(getDeviceId).mockReturnValue('device-b') + parentLog('current parent') + childLog('current child') + const currentLogs = getEntries().slice(0, 2) + for (const entry of currentLogs) { + expect(entry.metadata.__metadata__).toMatchObject({ + deviceId: 'device-a', + sessionId: getSessionId(), + }) + } + expect(currentLogs[0].context).toBe(ax.logger.Context.Notifications) + expect(currentLogs[1].context).toBe(ax.logger.Context.Default) + for (const entry of previousLogs) { + expect(entry.metadata.__metadata__).toMatchObject({ + sessionId: 'session-a', + deviceId: 'device-a', + }) + } + }, +) + +it('resolves device identity for events emitted without a provider', () => { + jest.mocked(getDeviceId).mockReturnValue(undefined) + render() + const metric = baseAx.metric + const log = baseAx.logger.info + metric('state:foreground', {}) + log('before device initialization') + const previousMetric = lastMetricMetadata() + const previousLog = getEntries()[0] + expect(previousMetric.base.deviceId).toBe('unknown') + expect(previousLog.metadata.__metadata__).toMatchObject({deviceId: 'unknown'}) + + jest.mocked(getDeviceId).mockReturnValue('initialized-device') + metric('state:foreground', {}) + log('after device initialization') + expect(lastMetricMetadata().base.deviceId).toBe('initialized-device') + expect(getEntries()[0].metadata.__metadata__).toMatchObject({ + deviceId: 'initialized-device', + }) + expect(previousMetric.base.deviceId).toBe('unknown') + expect(previousLog.metadata.__metadata__).toMatchObject({deviceId: 'unknown'}) +}) + +it('flushes queued metrics with emission-time sessions and a stable device ID', () => { + const client = new MetricsClient() + jest + .mocked(metrics.track) + .mockImplementation((...args) => client.track(...args)) + const fetchMock = jest + .spyOn(global, 'fetch') + .mockResolvedValue({ok: true} as Response) + render() + const metric = ax.metric + metric('state:foreground', {}) + + act(() => rotateSession()) + const secondSessionId = getSessionId() + metric('state:foreground', {}) + act(() => rotateSession()) + expect(fetchMock).not.toHaveBeenCalled() + client.flush() + + const body = JSON.parse(fetchMock.mock.calls[0][1]!.body as string) as { + events: {metadata: MetricMetadata}[] + } + expect(body.events.map(event => event.metadata.base)).toEqual([ + expect.objectContaining({deviceId: 'device-a', sessionId: 'session-a'}), + expect.objectContaining({deviceId: 'device-a', sessionId: secondSessionId}), + ]) +}) + +it('keeps passive metrics, logs, evaluations, flushes and retries separate from the web activity clock', async () => { + const lastEventAt = Date.now() + device.set(['analyticsSession'], {id: 'session-a', lastEventAt}) + const client = new MetricsClient() + jest + .mocked(metrics.track) + .mockImplementation((...args) => client.track(...args)) + const fetchMock = jest + .spyOn(global, 'fetch') + .mockRejectedValueOnce(new TypeError('Failed to fetch')) + .mockResolvedValue({ok: true} as Response) + render() + const feature = installFeature() + jest.setSystemTime(lastEventAt + 30 * 60_000) + ax.metric('state:foreground', {}) + ax.logger.info('passive work') + const previousLog = getEntries()[0] + ax.features.enabled(feature) + const previousMetric = lastMetricMetadata() + client.flush() + await Promise.resolve() + // Only the metrics client's lifecycle callback retries the failed batch. + const retry = jest.mocked(onAppStateChange).mock.calls.at(-1)![0] + retry('active') + await Promise.resolve() + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(device.get(['analyticsSession'])).toEqual({ + id: 'session-a', + lastEventAt, + }) + + recordSessionActivity('keydown') + ax.metric('router:navigate', {}) + expect(lastMetricMetadata().base.sessionId).not.toBe('session-a') + expect(previousMetric.base.sessionId).toBe('session-a') + expect(previousLog.metadata.__metadata__).toMatchObject({ + sessionId: 'session-a', + }) + expect(fetchMock.mock.calls[0][1]!.body).toBe( + fetchMock.mock.calls[1][1]!.body, + ) +}) + +describe.each(['did', 'deviceId'] as const)( + 'features bucketed on %s', + hashAttribute => { + it.each([ + 'enabled', + 'getValue', + 'directEnabled', + 'directEvaluation', + ] as const)( + 'uses context identity for %s without rereading device identity or updating attributes', + method => { + render() + const originalContext = ax + const {enabled, getValue} = ax.features + const capturedEvaluate = { + enabled, + getValue: (feature: Features) => getValue(feature, false), + directEnabled: features.isOn.bind(features), + directEvaluation: (feature: Features) => + features.evalFeature(feature).value, + }[method] + const feature = installFeature(hashAttribute) + act(() => rotateSession()) + jest.mocked(getDeviceId).mockClear() + const updateAttributes = jest.spyOn(features, 'updateAttributes') + + expect(capturedEvaluate(feature)).toBe(true) + expect(ax).toBe(originalContext) + expect(features.getAttributes()).toMatchObject({ + deviceId: 'device-a', + did: 'did:plc:a', + isBetaUser: true, + countryCode: 'US', + }) + expect(features.getAttributes()).not.toHaveProperty('sessionId') + expectExposures() + expect(features.getAllResults().get(feature)?.result).toMatchObject({ + hashAttribute, + hashValue: hashAttribute === 'did' ? 'did:plc:a' : 'device-a', + }) + expect(capturedEvaluate(feature)).toBe(true) + expect(updateAttributes).not.toHaveBeenCalled() + expect(getDeviceId).not.toHaveBeenCalled() + }, + ) + }, +) + +it('keeps feature attributes unchanged on rotation while exposures use the reporting session', () => { + render() + const feature = installFeature() + const attributes = features.getAttributes() + expect(attributes).not.toHaveProperty('sessionId') + const updateAttributes = jest.spyOn(features, 'updateAttributes') + const setFeatureAttributes = jest.spyOn(features, 'setAttributes') + + act(() => rotateSession()) + expect(getSessionId()).not.toBe('session-a') + expect(ax.features.enabled(feature)).toBe(true) + expectExposures() + expect(ax.features.getValue(feature, false)).toBe(true) + expect(features.isOn(feature)).toBe(true) + expect(features.evalFeature(feature).value).toBe(true) + expect(features.getAttributes()).toEqual(attributes) + expect(updateAttributes).not.toHaveBeenCalled() + expect(setFeatureAttributes).not.toHaveBeenCalled() +}) + +it('uses the initialized device ID when contexts mount instead of an import-time unknown', () => { + jest.mocked(getDeviceId).mockReturnValue('initialized-device') + render() + expect(contexts.map(metadata => metadata.base.deviceId)).toEqual([ + 'initialized-device', + 'initialized-device', + 'initialized-device', + ]) + ax.metric('state:foreground', {}) + expect(lastMetricMetadata().base.deviceId).toBe('initialized-device') + childLogger.info('initialized device') + expect(getEntries()[0].metadata.__metadata__).toMatchObject({ + deviceId: 'initialized-device', + }) + const feature = installFeature('deviceId') + jest.mocked(metrics.track).mockClear() + expect(ax.features.enabled(feature)).toBe(true) + expect(features.getAttributes().deviceId).toBe('initialized-device') + expectExposures() +}) + +it('uses context device identity when setting attributes triggers synchronous evaluations', () => { + render() + const metadata = ax.metadata + const feature = installFeature('deviceId') + act(() => rotateSession()) + jest.mocked(getDeviceId).mockClear() + features.setRenderer(() => { + features.evalFeature(feature) + }) + + setAttributes(metadata) + + expect(features.getAttributes()).toMatchObject({deviceId: 'device-a'}) + expect(features.getAttributes()).not.toHaveProperty('sessionId') + expect(features.getAllResults().get(feature)?.result.hashValue).toBe( + 'device-a', + ) + expectExposures() + expect(getDeviceId).not.toHaveBeenCalled() +}) + +it('registers current-account callbacks before provider attribute updates evaluate gates', () => { + function AccountTree({did}: {did: string}) { + return + } + const view = render() + const feature = installFeature('did') + act(() => rotateSession()) + features.setRenderer(() => { + features.evalFeature(feature) + }) + + view.rerender() + + expectExposures('did:plc:b') + expect(lastMetricMetadata().session?.isBskyPds).toBe(false) + expect(features.getAllResults().get(feature)?.result.hashValue).toBe( + 'did:plc:b', + ) +}) + +it('attributes both exposures to the bucketed did rather than the ambient account', () => { + render() + const feature = installFeature('did') + setAttributes({ + ...ax.metadata, + session: {did: 'did:plc:b', isBskyPds: false}, + }) + + expect(ax.features.enabled(feature)).toBe(true) + + expectExposures('did:plc:b') + expect(ax.metadata.session?.did).toBe('did:plc:a') +}) + +it.each(['did', 'deviceId'] as const)( + 'preserves did attribution and uses the reporting session for deferred experiments bucketed on %s', + hashAttribute => { + render() + const feature = installFeature(hashAttribute) + // Replay an actual result after the account and analytics session change. + const result = features.evalFeature(feature) + const originalMetadata = lastMetricMetadata() + features.setDeferredTrackingCalls([ + {experiment: result.experiment!, result: result.experimentResult!}, + ]) + jest.mocked(metrics.track).mockClear() + act(() => rotateSession()) + expect(getSessionId()).not.toBe(originalMetadata.base.sessionId) + + render() + + expect(metrics.track).toHaveBeenCalledTimes(1) + expect(lastMetricMetadata().base).toMatchObject({ + deviceId: 'device-a', + sessionId: getSessionId(), + }) + expect(originalMetadata.base.sessionId).toBe('session-a') + expect(lastMetricMetadata().session).toEqual({ + did: hashAttribute === 'did' ? 'did:plc:a' : 'did:plc:b', + isBskyPds: false, + }) + }, +) diff --git a/src/analytics/index.tsx b/src/analytics/index.tsx index fa74a98bb..ed15ec4dc 100644 --- a/src/analytics/index.tsx +++ b/src/analytics/index.tsx @@ -20,14 +20,14 @@ import { import { getAndMigrateDeviceId, getDeviceId, - getInitialSessionId, - useSessionId, + getSessionId, } from '#/analytics/identifiers' import { getMetadataForLogger, getNavigationMetadata, type MergeableMetadata, type Metadata, + type MetricMetadata, } from '#/analytics/metadata' import {type Metrics, metrics} from '#/analytics/metrics' import * as refParams from '#/analytics/misc/refParams' @@ -75,15 +75,24 @@ export type AnalyticsBaseContextType = Omit function createLogger( context: Logger['context'], - metadata: Partial, + metadata: Record, ): LoggerType { const logger = Logger.create(context, metadata) + const currentLogger = () => { + // Replace the snapshot so previously recorded entries stay unchanged. + logger.ambientMetadata = { + ...metadata, + deviceId: metadata.deviceId ?? getDeviceId() ?? 'unknown', + sessionId: getSessionId(), + } + return logger + } return { - debug: logger.debug.bind(logger), - info: logger.info.bind(logger), - log: logger.log.bind(logger), - warn: logger.warn.bind(logger), - error: logger.error.bind(logger), + debug: (...args) => currentLogger().debug(...args), + info: (...args) => currentLogger().info(...args), + log: (...args) => currentLogger().log(...args), + warn: (...args) => currentLogger().warn(...args), + error: (...args) => currentLogger().error(...args), useChild: (context: Exclude) => { // oxlint-disable-next-line react-hooks/exhaustive-deps return useMemo(() => createLogger(context, metadata), [context, metadata]) @@ -94,19 +103,28 @@ function createLogger( const Context = createContext({ logger: createLogger(Logger.Context.Default, {}), - metric: (event, payload, metadata) => { - if (metadata && '__meta' in metadata) { - delete metadata.__meta - } - metrics.track(event, payload, { + /** + * Session IDs are captured when an event is emitted. Deferred exposure events + * use the reporting session, which may differ from the evaluation session. + */ + metric: (event, payload, metadata: Partial = {}) => { + const snapshot: MetricMetadata = { ...metadata, + base: { + ...metadata.base, + deviceId: metadata.base?.deviceId ?? getDeviceId() ?? 'unknown', + sessionId: getSessionId(), + }, navigation: getNavigationMetadata(), - }) + } + if ('__meta' in snapshot) { + delete snapshot.__meta + } + metrics.track(event, payload, snapshot) }, metadata: { base: { deviceId: getDeviceId() ?? 'unknown', - sessionId: getInitialSessionId(), platform: Platform.OS, appVersion: env.APP_VERSION, bundleIdentifier: env.BUNDLE_IDENTIFIER, @@ -180,8 +198,8 @@ export function AnalyticsContext({ ) } } + // Device identity is initialized before mount and stays stable across sessions. const deviceId = getDeviceId() ?? 'unknown' - const sessionId = useSessionId() // only IP based, never GPS const geolocation = useGeolocationServiceResponse() const parentContext = useContext(Context) @@ -202,7 +220,6 @@ export function AnalyticsContext({ base: { ...parentContext.metadata.base, deviceId, - sessionId, isBetaUser, }, geolocation, @@ -222,7 +239,7 @@ export function AnalyticsContext({ }, } return context - }, [parentContext, metadata, deviceId, sessionId, isBetaUser, geolocation]) + }, [parentContext, metadata, deviceId, isBetaUser, geolocation]) return {children} } diff --git a/src/analytics/metadata.ts b/src/analytics/metadata.ts index 7077f5825..837d82b63 100644 --- a/src/analytics/metadata.ts +++ b/src/analytics/metadata.ts @@ -2,7 +2,6 @@ import {type Geolocation} from '#/geolocation' export type BaseMetadata = { deviceId: string - sessionId: string platform: string appVersion: string bundleIdentifier: string @@ -39,6 +38,11 @@ export type Metadata = { geolocation: GeolocationMetadata } & MergeableMetadata +/** Session IDs are only added when a metric is queued, never held in context. */ +export type MetricMetadata = Omit, 'base'> & { + base: Partial & {deviceId: string; sessionId: string} +} + /* * Navigation metadata is handle out-of-band from React, since we don't want to * slow down screen transitions in any way, and there doesn't seem to be a nice @@ -70,7 +74,6 @@ export function getMetadataForLogger({ }: Metadata): Record { return { deviceId: base.deviceId, - sessionId: base.sessionId, platform: base.platform, appVersion: base.appVersion, countryCode: geolocation.countryCode, diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index dba38ad20..6c2e2a6ef 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -60,9 +60,7 @@ export type Events = { notificationType: NotificationType authorCount: number } - 'state:background': { - secondsActive: number - } + 'state:background': {} 'state:foreground': {} 'router:navigate': { from?: string diff --git a/src/analytics/useSessionActivity/README.md b/src/analytics/useSessionActivity/README.md new file mode 100644 index 000000000..b11dff2fc --- /dev/null +++ b/src/analytics/useSessionActivity/README.md @@ -0,0 +1,130 @@ +# Web analytics session activity + +The observer, throttle, and activity recorder live together in `index.web.ts`. + +`App.web.tsx` mounts `useSessionActivity()` once, above account remounts and +nested analytics contexts. Native does not mount the hook; its default +implementation remains a DOM-free no-op. Native keeps its module-level +boot/AppState policy, five-minute TTL, and MMKV-invalidated raw-read cache. + +## Activity and ordering + +- Only a visible, focused document records input or history traversal. Both + focus and visibility notifications check that gate, in either order. Duplicate + return notifications reuse the renewed ID. Returns do not require a prior + departure notification (it might not have been delivered before suspension). + Blur, hidden and pagehide do not write anything. Pageshow handles a return + from the back/forward cache. +- Window capture listeners run before React handlers and document listeners. + Expiry (at least 30 minutes) is checked before renewal, and any new ID is + persisted synchronously, so the triggering interaction gets the new ID. +- Trusted keydown, pointerdown, click, beforeinput, input, and scroll events count, + including scrolls in nested containers. No preceding input is required for a + scroll. Programmatic scrolling also counts while the document is visible and + focused; distinguishing it from user scrolling is intentionally outside this policy. +- Popstate covers browser back/forward. Ordinary in-app navigation follows + pointer/keyboard input. `Navigation.tsx` also reports initial navigation, + redirects and restoration, so its `router:navigate` metrics intentionally do + not count. There is no history monkey patch. A script-triggered history + traversal cannot be distinguished from browser traversal by popstate alone. + +## Click and text-input coverage + +- `click` covers activation without a preceding pointerdown/keydown. The app's + `src/components/Button.tsx` delegates to RN Web Pressable. Its installed + `PressResponder` explicitly supports `onPress` from `onClick` without earlier + press-start/end events. Window capture runs before that handler, including + when the handler stops propagation. +- `beforeinput` runs before editor handlers can process an edit. The composer + (`src/view/com/composer/text-input/TextInput.web.tsx`) uses Tiptap/ProseMirror; + ProseMirror attaches editing handlers to the editor DOM, including beforeinput, + and Tiptap emits `onUpdate` from transaction dispatch. Window capture precedes + these target handlers and also any target capture listener. +- `input` is the fallback when no beforeinput arrives. It runs before input + handlers, including React's delegated change handling used by RN Web TextInput. + It cannot retroactively precede editor work that occurred before the browser + delivered either observed event. Exact browser/OS dictation ordering remains + unverified; the tests do not simulate native editing default actions. +- These events use the same five-second in-memory throttle. Pointerdown/click, + keydown/beforeinput/input, and beforeinput/input sequences within that interval + perform at most one activity read/write and cannot rotate twice. A canceled + beforeinput still counts as interaction, just as a keydown need not edit text. + +The trust policy is unchanged: `dispatchEvent()` events and `element.click()` +are rejected; no fallback accepts untrusted activation just because it reaches +an action. Controlled value assignments and Tiptap transactions are not activity +sources. Browser-dispatched events may be trusted without proving human intent; +this policy is not a universal detector of automatic browser editing. Real +assistive-technology activation and dictation event/trust behavior have not been +verified. No composition, change, clipboard, or per-component activity hooks +were added, and no input text/data is inspected or logged. + +## Shared storage + +Web always reads the shared raw record. Only parsing/validation is cached, keyed +by the entire raw string. It never holds a per-tab current-ID cache. + +Both platforms initialize `lastEventAt` when creating a record. After creation, +native updates it on lifecycle events, while web updates it only on qualifying +activity. Existing records work without a migration or a second timestamp field. Missing/nonfinite timestamps retain +the ID and establish a clock on first activity. Finite old timestamps expire +normally. A future timestamp (clock rollback) is rebased on activity without +rotating. Old app bundles still running the lifecycle-based writer are not made +activity-aware by this change. + +Passive reads recover missing/corrupt records with a creation timestamp, but do +not rotate or refresh valid records. A recovered web session can therefore expire +on its first qualifying activity if at least 30 minutes have passed since creation. +Metrics, logs, feature evaluations, uploads, flushes, and retries otherwise do not +renew activity. Already-captured metadata is never rewritten. + +The hook keeps a separate in-memory timestamp for its last recording. Events +within five seconds of that time are skipped before any storage access. When +the throttle opens, the recorder reads the shared record, checks expiry, then +updates `lastEventAt` and writes synchronously. Clock rollback bypasses the +local throttle. The throttle resets when the observer remounts. + +This limit is per mounted tab, not global across tabs. It throttles activity +reads and writes, not `getSessionId()`: metrics and logs still read through to +adopt another tab's current ID immediately, even during the throttle window. + +There is no cached session ID, pending activity, delayed flush, timer, or +heartbeat. A fresh record object avoids mutating the cached validation result. +The first event after a long idle still publishes a new ID before its metric +metadata is captured. + +The timestamp can lag actual activity by less than five seconds. A return near +the TTL boundary can therefore rotate that much early relative to the last +unpersisted event. Tests cover this explicit precision tradeoff. + +LocalStorage read-modify-write is **not atomic** across tabs. Truly simultaneous +writers can race, including creating competing IDs at expiry; subsequent reads +adopt the last shared write. No cross-tab lock/leader/heartbeat is introduced. + +Development diagnostics report creation, rotation, and mount/return decisions, +not individual high-frequency inputs. Every line starts with the ID's last eight +characters and contains only a source category, decision, and elapsed time. + +## Verification + +- `activity.test.ts`: storage read-through, record compatibility/recovery, timestamps, + exact TTL boundaries, uninterrupted activity, suspended timers, cross-tab + updates and diagnostics. +- `useSessionActivity.test.ts`: controlled focus/visibility in a separate JSDOM, + capture ordering, click/text-only TTL boundaries, RN Web PressResponder click + handling, Tiptap updates from controlled beforeinput/input handlers, programmatic + editor updates, nested scrolling, synthetic event rejection, local five-second + read/write throttling and duplicate-event sequences, boundary precision, + cross-tab ID adoption, Strict Mode/remount cleanup, page-cache return and the + native no-op. The test harness marks selected synthetic inputs as trusted; + these are not real browser-input or assistive-technology tests. +- `../index.test.tsx`: actual metadata snapshots, passive logging/evaluations, + batching/retries and activity rotation. Existing native lifecycle/storage tests + remain in `../identifiers/`. + +Real browser tab switching, visible-but-unfocused windows, composer typing, +feed scrolling, click-only accessibility activation, text editing without physical +keydown (such as OS dictation), and real device sleep/wake still need manual +verification. Controlled wall-clock tests are not evidence of actual sleep/wake +behavior, and controlled DOM event ordering is not evidence of real dictation +or screen-reader event sequences. diff --git a/src/analytics/useSessionActivity/activity.test.ts b/src/analytics/useSessionActivity/activity.test.ts new file mode 100644 index 000000000..ec9acc6e0 --- /dev/null +++ b/src/analytics/useSessionActivity/activity.test.ts @@ -0,0 +1,250 @@ +import uuid from 'react-native-uuid' + +import {onAppStateChange} from '#/lib/appState' +import {getSessionId, readSessionRecord} from '#/analytics/identifiers/session' +import {recordSessionActivity} from '#/analytics/useSessionActivity/index.web' +import {device} from '#/storage' + +let mockRaw: string | undefined +jest.mock('#/env', () => ({IS_NATIVE: false, IS_DEV: true})) +jest.mock('#/lib/appState', () => ({onAppStateChange: jest.fn()})) +jest.mock('react-native-uuid', () => ({ + __esModule: true, + default: {v4: jest.fn()}, +})) +jest.mock('#/storage', () => ({ + device: { + getRaw: jest.fn(() => mockRaw), + set: jest.fn((_key, data) => { + mockRaw = JSON.stringify({data}) + }), + }, +})) +jest.mock('#/analytics/identifiers/sessionStorage', () => + jest.requireActual('#/analytics/identifiers/sessionStorage/index.web'), +) + +const NOW = new Date('2026-09-22T12:00:00Z').getTime() +const TTL = 30 * 60 * 1e3 + +function store(data: unknown) { + mockRaw = JSON.stringify({data}) +} + +beforeEach(() => { + jest.useFakeTimers() + jest.setSystemTime(NOW) + jest.clearAllMocks() + mockRaw = undefined + ;(uuid.v4 as jest.Mock).mockReturnValue('new-session-12345678') + jest.spyOn(console, 'debug').mockImplementation(() => {}) +}) +afterEach(() => { + jest.restoreAllMocks() + jest.useRealTimers() +}) + +it('initializes recovery time once without booting or subscribing to web AppState', () => { + expect(onAppStateChange).not.toHaveBeenCalled() + expect(device.set).not.toHaveBeenCalled() + expect(getSessionId()).toBe('new-session-12345678') + expect(readSessionRecord()).toEqual({ + id: 'new-session-12345678', + lastEventAt: NOW, + }) + jest.setSystemTime(NOW + TTL * 2) + for (let i = 0; i < 100; i++) getSessionId() + expect(device.set).toHaveBeenCalledTimes(1) + expect(readSessionRecord()).toEqual({ + id: 'new-session-12345678', + lastEventAt: NOW, + }) + ;(uuid.v4 as jest.Mock).mockReturnValue('active-session') + recordSessionActivity('click') + expect(readSessionRecord()).toEqual({ + id: 'active-session', + lastEventAt: NOW + TTL * 2, + }) +}) + +it('reads shared raw storage every time but only parses and validates changed records', () => { + store({id: 'a', lastEventAt: NOW}) + getSessionId() + const parse = jest.spyOn(JSON, 'parse') + jest.mocked(device.getRaw).mockClear() + for (let i = 0; i < 100; i++) getSessionId() + expect(device.getRaw).toHaveBeenCalledTimes(100) + expect(parse).not.toHaveBeenCalled() + store({id: 'a', lastEventAt: NOW - TTL}) + recordSessionActivity('pointerdown') + expect(parse).toHaveBeenCalledTimes(1) + expect(getSessionId()).not.toBe('a') + store({id: 'other-tab', lastEventAt: NOW}) + expect(getSessionId()).toBe('other-tab') +}) + +it.each([TTL - 1, TTL, TTL + 1])( + 'checks expiry before renewing at %d ms', + elapsed => { + store({id: 'a', lastEventAt: NOW}) + jest.setSystemTime(NOW + elapsed) + expect(getSessionId()).toBe('a') + recordSessionActivity('keydown') + expect(getSessionId()).toBe(elapsed < TTL ? 'a' : 'new-session-12345678') + expect(readSessionRecord()?.lastEventAt).toBe(NOW + elapsed) + }, +) + +it('uses existing records without migration or passive writes', () => { + store({id: 'existing', lastEventAt: NOW - TTL + 1}) + expect(getSessionId()).toBe('existing') + expect(device.set).not.toHaveBeenCalled() + recordSessionActivity('return') + expect(device.set).toHaveBeenCalledWith(['analyticsSession'], { + id: 'existing', + lastEventAt: NOW, + }) +}) + +it.each([undefined, null, '123', NaN, Infinity, -Infinity])( + 'retains the ID with an unknown timestamp (%s) until first activity establishes its clock', + lastEventAt => { + store({id: 'a', lastEventAt}) + expect(getSessionId()).toBe('a') + expect(device.set).not.toHaveBeenCalled() + recordSessionActivity('mount') + expect(readSessionRecord()).toEqual({id: 'a', lastEventAt: NOW}) + }, +) + +it.each([0, -1])('expires old finite timestamps (%s)', lastEventAt => { + store({id: 'a', lastEventAt}) + recordSessionActivity('return') + expect(getSessionId()).not.toBe('a') +}) + +it('rebases a future timestamp on activity after clock rollback without changing the ID', () => { + store({id: 'a', lastEventAt: NOW + TTL}) + recordSessionActivity('keydown') + expect(readSessionRecord()).toEqual({id: 'a', lastEventAt: NOW}) + jest.setSystemTime(NOW + TTL) + recordSessionActivity('keydown') + expect(getSessionId()).not.toBe('a') +}) + +it.each([undefined, '{', 'null', '{}', '{"data":{"id":""}}'])( + 'recovers invalid raw storage %s', + raw => { + mockRaw = raw + recordSessionActivity('pointerdown') + expect(readSessionRecord()).toEqual({ + id: 'new-session-12345678', + lastEventAt: NOW, + }) + }, +) + +it.each([ + 'keydown', + 'pointerdown', + 'click', + 'beforeinput', + 'input', + 'scroll', +] as const)( + 'continuous %s activity preserves a session beyond 30 minutes', + source => { + store({id: 'a', lastEventAt: NOW}) + for (let i = 1; i <= 40; i++) { + jest.setSystemTime(NOW + i * 60_000) + recordSessionActivity(source) + } + expect(getSessionId()).toBe('a') + expect(readSessionRecord()?.lastEventAt).toBe(NOW + 40 * 60_000) + expect(console.debug).not.toHaveBeenCalled() + }, +) + +it('reads and writes immediately when called, leaving throttling to the hook', () => { + store({id: 'a', lastEventAt: NOW}) + recordSessionActivity('scroll') + expect(device.getRaw).toHaveBeenCalledTimes(1) + expect(device.set).toHaveBeenCalledWith(['analyticsSession'], { + id: 'a', + lastEventAt: NOW, + }) + expect(jest.getTimerCount()).toBe(0) +}) + +it('uses persisted event time at the boundary without needing timers to run', () => { + store({id: 'a', lastEventAt: NOW}) + jest.setSystemTime(NOW + 5_000) + recordSessionActivity('keydown') + expect(readSessionRecord()?.lastEventAt).toBe(NOW + 5_000) + jest.setSystemTime(NOW + TTL) + recordSessionActivity('return') + expect(getSessionId()).toBe('a') + jest.setSystemTime(NOW + TTL * 2) + recordSessionActivity('return') + expect(getSessionId()).not.toBe('a') +}) + +it("uses another tab's recent activity and adopts its rotated ID", () => { + store({id: 'a', lastEventAt: NOW}) + jest.setSystemTime(NOW + TTL) + // Another tab was active just before this one returned. + store({id: 'a', lastEventAt: Date.now() - 1}) + recordSessionActivity('return') + expect(getSessionId()).toBe('a') + jest.setSystemTime(NOW + TTL * 2) + store({id: 'other-tab', lastEventAt: Date.now() - 1}) + expect(getSessionId()).toBe('other-tab') + recordSessionActivity('keydown') + expect(readSessionRecord()).toEqual({ + id: 'other-tab', + lastEventAt: Date.now(), + }) +}) + +it('does not revive a removed ID on the next activity', () => { + store({id: 'a', lastEventAt: NOW}) + recordSessionActivity('keydown') + mockRaw = undefined + recordSessionActivity('keydown') + expect(getSessionId()).not.toBe('a') +}) + +it('does not mutate the cached validation result when writing activity', () => { + store({id: 'a', lastEventAt: NOW}) + const previous = readSessionRecord() + jest.setSystemTime(NOW + 5_000) + recordSessionActivity('keydown') + expect(previous).toEqual({id: 'a', lastEventAt: NOW}) + expect(readSessionRecord()).toEqual({id: 'a', lastEventAt: NOW + 5_000}) +}) + +it.each(['click', 'beforeinput', 'input'] as const)( + 'logs only bounded source/timing diagnostics for %s', + source => { + store({id: 'old-session', lastEventAt: NOW - TTL}) + recordSessionActivity(source) + expect(console.debug).toHaveBeenCalledWith('12345678 analytics session', { + source, + action: 'rotated', + elapsedMs: TTL, + }) + for (let i = 0; i < 100; i++) recordSessionActivity(source) + expect(console.debug).toHaveBeenCalledTimes(1) + }, +) + +it('prefixes bounded diagnostics with only the last eight ID characters', () => { + recordSessionActivity('mount') + expect(console.debug).toHaveBeenCalledWith('12345678 analytics session', { + source: 'mount', + action: 'created', + elapsedMs: undefined, + }) + for (let i = 0; i < 100; i++) recordSessionActivity('keydown') + expect(console.debug).toHaveBeenCalledTimes(1) +}) diff --git a/src/analytics/useSessionActivity/index.ts b/src/analytics/useSessionActivity/index.ts new file mode 100644 index 000000000..bb7c50672 --- /dev/null +++ b/src/analytics/useSessionActivity/index.ts @@ -0,0 +1,2 @@ +/** Native analytics sessions use AppState, not input activity. */ +export function useSessionActivity() {} diff --git a/src/analytics/useSessionActivity/index.web.ts b/src/analytics/useSessionActivity/index.web.ts new file mode 100644 index 000000000..9e4435106 --- /dev/null +++ b/src/analytics/useSessionActivity/index.web.ts @@ -0,0 +1,117 @@ +import {useLayoutEffect} from 'react' +import uuid from 'react-native-uuid' + +import {readSessionRecord} from '#/analytics/identifiers/session' +import {IS_DEV} from '#/env' +import {device} from '#/storage' + +const TTL = 30 * 60 * 1e3 +const ACTIVITY_INTERVAL = 5_000 + +type Source = + | 'mount' + | 'return' + | 'keydown' + | 'pointerdown' + | 'click' + | 'beforeinput' + | 'input' + | 'scroll' + | 'popstate' + +/** + * Capture above React's root and document listeners, including non-bubbling + * nested scrolls. Scrolls count regardless of whether input or code caused them. + */ +export function observeSessionActivity() { + let lastRecordedAt = -Infinity + const isEngaged = () => + document.visibilityState === 'visible' && document.hasFocus() + + function recordActivity(source: Source) { + const now = Date.now() + if (now >= lastRecordedAt && now - lastRecordedAt < ACTIVITY_INTERVAL) + return + recordSessionActivity(source) + lastRecordedAt = now + } + + function onReturn() { + // A suspended tab may return without having delivered a departure event. + if (isEngaged()) recordActivity('return') + } + + function onFocus(event: Event) { + // Element focus also passes through the window capture listener. + if (event.target === window) onReturn() + } + + function onActivity(event: Event) { + if (!event.isTrusted || !isEngaged()) return + recordActivity( + event.type as + | 'keydown' + | 'pointerdown' + | 'click' + | 'beforeinput' + | 'input' + | 'scroll' + | 'popstate', + ) + } + + const listeners = { + keydown: onActivity, + pointerdown: onActivity, + click: onActivity, + // Run before editor handling, with input as a fallback when beforeinput is absent. + beforeinput: onActivity, + input: onActivity, + scroll: onActivity, + popstate: onActivity, + focus: onFocus, + visibilitychange: onReturn, + pageshow: onReturn, + } + for (const [name, listener] of Object.entries(listeners)) { + window.addEventListener(name, listener, {capture: true, passive: true}) + } + if (isEngaged()) recordActivity('mount') + + return () => { + for (const [name, listener] of Object.entries(listeners)) { + window.removeEventListener(name, listener, true) + } + } +} + +/** Mounted once at the app root, above account-specific remounts. */ +export function useSessionActivity() { + useLayoutEffect(observeSessionActivity, []) +} + +/** Check expiry before recording activity, and publish the result immediately. */ +export function recordSessionActivity(source: Source) { + const current = readSessionRecord() + const now = Date.now() + const elapsedMs = + current?.lastEventAt === undefined ? undefined : now - current.lastEventAt + const expired = elapsedMs !== undefined && elapsedMs >= TTL + // Do not mutate the cached validation result returned by readSessionRecord. + const record = { + id: !current || expired ? String(uuid.v4()) : current.id, + lastEventAt: now, + } + device.set(['analyticsSession'], record) + + if ( + IS_DEV && + (!current || expired || source === 'mount' || source === 'return') + ) { + console.debug(`${record.id.slice(-8)} analytics session`, { + source, + action: !current ? 'created' : expired ? 'rotated' : 'retained', + elapsedMs, + }) + } +} diff --git a/src/analytics/useSessionActivity/useSessionActivity.test.ts b/src/analytics/useSessionActivity/useSessionActivity.test.ts new file mode 100644 index 000000000..25917e9eb --- /dev/null +++ b/src/analytics/useSessionActivity/useSessionActivity.test.ts @@ -0,0 +1,548 @@ +import {createElement, StrictMode} from 'react' +import uuid from 'react-native-uuid' +import {renderHook} from '@testing-library/react-native' +import {Editor} from '@tiptap/core' +import {Document} from '@tiptap/extension-document' +import {Paragraph} from '@tiptap/extension-paragraph' +import {Text} from '@tiptap/extension-text' +import {JSDOM} from 'jsdom' + +import {getSessionId, readSessionRecord} from '#/analytics/identifiers/session' +import {useSessionActivity as useNativeSessionActivity} from '#/analytics/useSessionActivity/index' +import { + observeSessionActivity, + useSessionActivity, +} from '#/analytics/useSessionActivity/index.web' +import {device} from '#/storage' + +let mockRaw: string | undefined +jest.mock('#/env', () => ({IS_NATIVE: false})) +jest.mock('#/lib/appState', () => ({onAppStateChange: jest.fn()})) +jest.mock('react-native-uuid', () => ({ + __esModule: true, + default: {v4: jest.fn(() => 'rotated')}, +})) +jest.mock('#/storage', () => ({ + device: { + getRaw: jest.fn(() => mockRaw), + set: jest.fn((_key, data) => { + mockRaw = JSON.stringify({data}) + }), + }, +})) +jest.mock('#/analytics/identifiers/sessionStorage', () => + jest.requireActual('#/analytics/identifiers/sessionStorage/index.web'), +) + +const NOW = new Date('2026-09-22T12:00:00Z').getTime() +const TTL = 30 * 60 * 1e3 +const INPUT_EVENTS = [ + 'keydown', + 'pointerdown', + 'click', + 'beforeinput', + 'input', + 'scroll', + 'popstate', +] as const +let focused: boolean +let visible: DocumentVisibilityState +let cleanup: (() => void) | undefined +let trustedEvent: Event | undefined +let listeners: Map + +/** JSDOM cannot generate trusted input or scroll events. */ +function send(type: string, target: EventTarget = window, trusted = true) { + const EventClass = + type === 'click' + ? dom.window.MouseEvent + : type === 'beforeinput' || type === 'input' + ? dom.window.InputEvent + : dom.window.Event + const event = new EventClass(type) + trustedEvent = trusted ? event : undefined + target.dispatchEvent(event) + trustedEvent = undefined +} + +/** Exercise the composer's actual editor dependencies with controlled DOM events. */ +function createEditor(onUpdate: () => void) { + const element = document.createElement('div') + document.body.append(element) + return new Editor({ + element, + extensions: [Document, Paragraph, Text], + content: '

', + injectCSS: false, + onUpdate, + }) +} + +/** Use a separate DOM so Expo's native Jest setup keeps its own globals. */ +const dom = new JSDOM('') +const domGlobals = { + window: dom.window, + document: dom.window.document, + innerHeight: dom.window.innerHeight, + getComputedStyle: dom.window.getComputedStyle.bind(dom.window), +} +const originalGlobals = Object.keys(domGlobals).map( + key => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const, +) +beforeAll(() => { + for (const [key, value] of Object.entries(domGlobals)) { + Object.defineProperty(globalThis, key, {value, configurable: true}) + } +}) +afterAll(() => { + for (const [key, descriptor] of originalGlobals) { + if (descriptor) Object.defineProperty(globalThis, key, descriptor) + else Reflect.deleteProperty(globalThis, key) + } + dom.window.close() +}) + +beforeEach(() => { + jest.useFakeTimers() + jest.setSystemTime(NOW) + jest.clearAllMocks() + mockRaw = JSON.stringify({data: {id: 'original', lastEventAt: NOW}}) + focused = true + visible = 'visible' + jest.spyOn(document, 'hasFocus').mockImplementation(() => focused) + jest + .spyOn(document, 'visibilityState', 'get') + .mockImplementation(() => visible) + listeners = new Map() + const add = window.addEventListener.bind(window) + const remove = window.removeEventListener.bind(window) + jest + .spyOn(window, 'addEventListener') + .mockImplementation((name, listener, options) => { + if (!listener) return + const wrapped: EventListener = event => { + const input = new Proxy(event, { + get: (target, key) => + key === 'isTrusted' + ? event === trustedEvent + : Reflect.get(target, key, target), + }) + if (typeof listener === 'function') listener(input) + else listener.handleEvent(input) + } + listeners.set(name, wrapped) + add(name, wrapped, options) + }) + jest + .spyOn(window, 'removeEventListener') + .mockImplementation((name, listener, options) => { + if (!listener) return + remove(name, listeners.get(name) ?? listener, options) + listeners.delete(name) + }) +}) +afterEach(() => { + cleanup?.() + cleanup = undefined + document.body.innerHTML = '' + jest.restoreAllMocks() + jest.useRealTimers() +}) + +it.each(['hidden', 'unfocused'])( + 'does not renew on %s startup or passive rerenders', + state => { + visible = state === 'hidden' ? 'hidden' : 'visible' + focused = state === 'hidden' + jest.setSystemTime(NOW + TTL) + const view = renderHook(useSessionActivity) + cleanup = view.unmount + view.rerender({}) + expect(getSessionId()).toBe('original') + for (const event of [...INPUT_EVENTS, 'focus', 'visibilitychange']) + send(event) + expect(device.set).not.toHaveBeenCalled() + expect(readSessionRecord()?.lastEventAt).toBe(NOW) + }, +) + +it.each(['focus-first', 'visibility-first'])( + 'gates and deduplicates a return (%s)', + order => { + focused = false + visible = 'hidden' + cleanup = observeSessionActivity() + jest.setSystemTime(NOW + TTL) + if (order === 'focus-first') { + focused = true + send('focus') + expect(getSessionId()).toBe('original') + visible = 'visible' + send('visibilitychange', document) + } else { + visible = 'visible' + send('visibilitychange', document) + expect(getSessionId()).toBe('original') + focused = true + send('focus') + } + expect(getSessionId()).toBe('rotated') + send('focus') + send('visibilitychange', document) + expect(uuid.v4).toHaveBeenCalledTimes(1) + }, +) + +it.each(['focus', 'visibilitychange', 'pageshow'])( + 'checks a %s return even if suspension delivered no departure event', + type => { + cleanup = observeSessionActivity() + jest.setSystemTime(NOW + TTL) + send(type) + expect(getSessionId()).toBe('rotated') + send(type) + expect(uuid.v4).toHaveBeenCalledTimes(1) + }, +) + +it('does not count a late background/blur notification as new activity', () => { + cleanup = observeSessionActivity() + jest.setSystemTime(NOW + TTL * 5) + focused = false + send('blur') + visible = 'hidden' + send('visibilitychange', document) + expect(readSessionRecord()?.lastEventAt).toBe(NOW) + expect(device.set).toHaveBeenCalledTimes(1) + visible = 'visible' + focused = true + send('focus') + expect(getSessionId()).toBe('rotated') +}) + +it.each(INPUT_EVENTS)( + 'rotates before %s metadata is captured, keeping old snapshots intact', + type => { + cleanup = observeSessionActivity() + const target = document.createElement('div') + document.body.append(target) + const snapshots = [{sessionId: getSessionId()}] + const captureMetric = () => snapshots.push({sessionId: getSessionId()}) + // Even an earlier document capture listener is below window capture. + document.addEventListener(type, captureMetric, true) + jest.setSystemTime(NOW + TTL) + send(type, target) + expect(snapshots).toEqual([{sessionId: 'original'}, {sessionId: 'rotated'}]) + document.removeEventListener(type, captureMetric, true) + }, +) + +describe.each(['click', 'beforeinput', 'input'])( + '%s without pointerdown or keydown', + type => { + it.each([TTL - 1, TTL, TTL + 1])( + 'renews or rotates at %d ms before target handling', + elapsed => { + cleanup = observeSessionActivity() + const target = document.createElement( + type === 'click' ? 'button' : 'textarea', + ) + document.body.append(target) + const snapshots = [{sessionId: getSessionId()}] + target.addEventListener(type, () => + snapshots.push({sessionId: getSessionId()}), + ) + jest.mocked(device.set).mockClear() + jest.setSystemTime(NOW + elapsed) + send(type, target) + const id = elapsed < TTL ? 'original' : 'rotated' + expect(snapshots).toEqual([{sessionId: 'original'}, {sessionId: id}]) + expect(readSessionRecord()).toEqual({id, lastEventAt: NOW + elapsed}) + expect(device.set).toHaveBeenCalledTimes(1) + expect(uuid.v4).toHaveBeenCalledTimes(elapsed < TTL ? 0 : 1) + }, + ) + }, +) + +it.each([ + ['pointerdown', 'click'], + ['keydown', 'beforeinput', 'input'], + ['beforeinput', 'input'], +])('throttles the entire %j interaction sequence', (...events) => { + cleanup = observeSessionActivity() + jest.mocked(device.getRaw).mockClear() + jest.mocked(device.set).mockClear() + jest.setSystemTime(NOW + TTL) + for (const type of events) { + send(type) + jest.setSystemTime(Date.now() + 100) + } + expect(device.getRaw).toHaveBeenCalledTimes(1) + expect(device.set).toHaveBeenCalledTimes(1) + expect(uuid.v4).toHaveBeenCalledTimes(1) + expect(jest.getTimerCount()).toBe(0) +}) + +it('rotates before RN Web PressResponder handles a click-only activation', () => { + const PressResponder = jest.requireActual< + new (config: {onPress: () => void; onPressStart: () => void}) => { + getEventHandlers(): {onClick: (event: MouseEvent) => void} + reset(): void + } + >('react-native-web/dist/cjs/modules/usePressEvents/PressResponder') + cleanup = observeSessionActivity() + const snapshots = [{sessionId: getSessionId()}] + const onPressStart = jest.fn() + const responder = new PressResponder({ + onPress: () => snapshots.push({sessionId: getSessionId()}), + onPressStart, + }) + const button = document.createElement('button') + document.body.append(button) + button.addEventListener('click', responder.getEventHandlers().onClick) + jest.setSystemTime(NOW + TTL) + send('click', button) + expect(onPressStart).not.toHaveBeenCalled() + expect(snapshots).toEqual([{sessionId: 'original'}, {sessionId: 'rotated'}]) + responder.reset() +}) + +it.each(['beforeinput', 'input'])( + 'rotates before a Tiptap update triggered by %s', + type => { + cleanup = observeSessionActivity() + const snapshots = [{sessionId: getSessionId()}] + const editor = createEditor(() => + snapshots.push({sessionId: getSessionId()}), + ) + try { + editor.setOptions({ + editorProps: { + handleDOMEvents: { + [type]: () => { + editor.commands.insertContent('entered text') + return true + }, + }, + }, + }) + jest.setSystemTime(NOW + TTL) + send(type, editor.view.dom) + expect(editor.getText()).toBe('entered text') + expect(snapshots).toEqual([ + {sessionId: 'original'}, + {sessionId: 'rotated'}, + ]) + } finally { + editor.destroy() + } + }, +) + +it('does not count programmatic Tiptap updates as activity', () => { + cleanup = observeSessionActivity() + const snapshots: string[] = [] + const editor = createEditor(() => snapshots.push(getSessionId())) + try { + jest.mocked(device.set).mockClear() + jest.setSystemTime(NOW + TTL) + editor.commands.setContent('

controlled content

', true) + expect(snapshots).toEqual(['original']) + expect(device.set).not.toHaveBeenCalled() + expect(readSessionRecord()?.lastEventAt).toBe(NOW) + } finally { + editor.destroy() + } +}) + +it('ignores programmatic values, element.click(), and script-dispatched input', () => { + cleanup = observeSessionActivity() + const field = document.createElement('textarea') + const button = document.createElement('button') + document.body.append(field, button) + jest.mocked(device.set).mockClear() + jest.setSystemTime(NOW + TTL) + field.value = 'controlled content' + button.click() + send('beforeinput', field, false) + send('input', field, false) + expect(device.set).not.toHaveBeenCalled() + expect(getSessionId()).toBe('original') +}) + +it('ignores synthetic events', () => { + cleanup = observeSessionActivity() + jest.setSystemTime(NOW + TTL) + for (const type of INPUT_EVENTS) { + send(type, window, false) + } + expect(getSessionId()).toBe('original') + expect(device.set).toHaveBeenCalledTimes(1) +}) + +it.each(['scroll', 'input'])( + 'throttles storage reads and writes before recording frequent %s events', + type => { + cleanup = observeSessionActivity() + jest.mocked(device.getRaw).mockClear() + jest.mocked(device.set).mockClear() + for (let i = 1; i <= 150; i++) { + jest.setSystemTime(NOW + i * 100) + send(type) + const recordings = Math.floor((i * 100) / 5_000) + expect(device.getRaw).toHaveBeenCalledTimes(recordings) + expect(device.set).toHaveBeenCalledTimes(recordings) + } + expect(jest.getTimerCount()).toBe(0) + jest.advanceTimersByTime(TTL * 2) + expect(device.getRaw).toHaveBeenCalledTimes(3) + expect(device.set).toHaveBeenCalledTimes(3) + }, +) + +it.each([0, 4_999, 5_000, 5_001])( + 'checks the local throttle before storage at %d ms', + elapsed => { + cleanup = observeSessionActivity() + jest.mocked(device.getRaw).mockClear() + jest.mocked(device.set).mockClear() + jest.setSystemTime(NOW + elapsed) + send('scroll') + expect(device.getRaw).toHaveBeenCalledTimes(elapsed < 5_000 ? 0 : 1) + expect(device.set).toHaveBeenCalledTimes(elapsed < 5_000 ? 0 : 1) + }, +) + +it('can expire less than five seconds early relative to throttled activity', () => { + cleanup = observeSessionActivity() + jest.setSystemTime(NOW + 4_999) + send('scroll') + expect(readSessionRecord()?.lastEventAt).toBe(NOW) + expect(device.set).toHaveBeenCalledTimes(1) + jest.setSystemTime(NOW + TTL) + send('focus') + expect(getSessionId()).toBe('rotated') +}) + +it.each(['keydown', 'click', 'beforeinput', 'input'])( + 'uses local throttle time without caching the shared ID during %s', + type => { + cleanup = observeSessionActivity() + jest.mocked(device.getRaw).mockClear() + jest.mocked(device.set).mockClear() + jest.setSystemTime(NOW + 4_500) + mockRaw = JSON.stringify({data: {id: 'other-tab', lastEventAt: Date.now()}}) + send(type) + expect(device.getRaw).not.toHaveBeenCalled() + expect(device.set).not.toHaveBeenCalled() + // Metrics still adopt the other tab's ID even inside the activity throttle. + expect(getSessionId()).toBe('other-tab') + jest.setSystemTime(NOW + 5_000) + send(type) + expect(device.set).toHaveBeenCalledWith(['analyticsSession'], { + id: 'other-tab', + lastEventAt: Date.now(), + }) + }, +) + +it('bypasses the local throttle after clock rollback', () => { + cleanup = observeSessionActivity() + jest.setSystemTime(NOW - 1) + send('keydown') + expect(device.getRaw).toHaveBeenCalledTimes(2) + expect(device.set).toHaveBeenCalledTimes(2) + expect(readSessionRecord()).toEqual({id: 'original', lastEventAt: NOW - 1}) + expect(uuid.v4).not.toHaveBeenCalled() +}) + +it('counts nested scrolls without preceding keyboard or pointer input', () => { + cleanup = observeSessionActivity() + const outer = document.createElement('div') + const nested = document.createElement('div') + outer.append(nested) + document.body.append(outer) + for (let minute = 1; minute <= 40; minute++) { + jest.setSystemTime(NOW + minute * 60_000) + send('scroll', nested) + } + expect(getSessionId()).toBe('original') + expect(readSessionRecord()?.lastEventAt).toBe(NOW + 40 * 60_000) +}) + +it('ignores blur and unfocused scroll without renewing activity', () => { + cleanup = observeSessionActivity() + jest.advanceTimersByTime(5_000) + send('keydown') + expect(jest.getTimerCount()).toBe(0) + jest.advanceTimersByTime(100) + focused = false + send('blur') + expect(readSessionRecord()?.lastEventAt).toBe(NOW + 5_000) + expect(jest.getTimerCount()).toBe(0) + send('scroll') + expect(jest.getTimerCount()).toBe(0) +}) + +it('ignores blur even if hasFocus has not updated yet', () => { + cleanup = observeSessionActivity() + jest.advanceTimersByTime(5_000) + send('keydown') + send('blur') + expect(readSessionRecord()?.lastEventAt).toBe(NOW + 5_000) + expect(jest.getTimerCount()).toBe(0) + jest.setSystemTime(NOW + 5_000 + TTL) + send('focus') + expect(getSessionId()).toBe('rotated') +}) + +it('ignores element focus changes and returns from page cache using wall-clock time', () => { + cleanup = observeSessionActivity() + jest.setSystemTime(NOW + TTL) + send('focus', document) + expect(getSessionId()).toBe('original') + send('pagehide') + expect(device.set).toHaveBeenCalledTimes(1) + send('pageshow') + expect(getSessionId()).toBe('rotated') +}) + +it('cleans up all capture/passive listeners across Strict Mode and remounts', () => { + const first = renderHook(useSessionActivity, { + wrapper: ({children}) => createElement(StrictMode, null, children), + }) + expect([...listeners.keys()]).toEqual([ + ...INPUT_EVENTS, + 'focus', + 'visibilitychange', + 'pageshow', + ]) + for (const [, , options] of jest.mocked(window.addEventListener).mock.calls) { + expect(options).toEqual({capture: true, passive: true}) + } + jest.advanceTimersByTime(5_000) + send('keydown') + expect(jest.getTimerCount()).toBe(0) + first.unmount() + expect(listeners.size).toBe(0) + expect(jest.getTimerCount()).toBe(0) + expect(readSessionRecord()?.lastEventAt).toBe(NOW + 5_000) + jest.setSystemTime(NOW + TTL + 5_000) + for (const type of INPUT_EVENTS) send(type) + expect(getSessionId()).toBe('original') + const second = renderHook(useSessionActivity) + cleanup = second.unmount + expect(getSessionId()).toBe('rotated') + const writes = jest.mocked(device.set).mock.calls.length + for (const type of INPUT_EVENTS) send(type) + expect(device.set).toHaveBeenCalledTimes(writes) +}) + +it('keeps the default/native hook free of DOM access', () => { + const visibility = jest.spyOn(document, 'visibilityState', 'get') + renderHook(useNativeSessionActivity).unmount() + expect(visibility).not.toHaveBeenCalled() + expect(window.addEventListener).not.toHaveBeenCalled() + expect(device.set).not.toHaveBeenCalled() +}) diff --git a/src/components/moderation/AppealForm.tsx b/src/components/moderation/AppealForm.tsx index 47ab96e2c..6e17fa0dc 100644 --- a/src/components/moderation/AppealForm.tsx +++ b/src/components/moderation/AppealForm.tsx @@ -22,7 +22,7 @@ import {Loader} from '#/components/Loader' import * as Toast from '#/components/Toast' import {Text} from '#/components/Typography' import {IS_ANDROID} from '#/env' -import {com, tools} from '#/lexicons' +import {type com, tools} from '#/lexicons' export function AppealForm({ label, diff --git a/src/storage/__tests__/index.test.ts b/src/storage/__tests__/index.test.ts index 848c07b8e..160d2e036 100644 --- a/src/storage/__tests__/index.test.ts +++ b/src/storage/__tests__/index.test.ts @@ -1,4 +1,4 @@ -import {beforeEach, expect, jest, test} from '@jest/globals' +import {afterEach, beforeEach, expect, jest, test} from '@jest/globals' import {Storage} from '#/storage' @@ -33,6 +33,22 @@ const store = new Storage<['account'], Schema>({id: 'test'}) beforeEach(() => { store.removeMany([scope], ['boo', 'str', 'num', 'obj']) }) +afterEach(() => { + jest.restoreAllMocks() +}) + +test('reads the raw envelope without parsing and observes changes and removal', () => { + expect(store.getRaw([scope, 'obj'])).toBeUndefined() + store.set([scope, 'obj'], {foo: true}) + const parse = jest.spyOn(JSON, 'parse') + + expect(store.getRaw([scope, 'obj'])).toBe('{"data":{"foo":true}}') + store.set([scope, 'obj'], {foo: false}) + expect(store.getRaw([scope, 'obj'])).toBe('{"data":{"foo":false}}') + store.remove([scope, 'obj']) + expect(store.getRaw([scope, 'obj'])).toBeUndefined() + expect(parse).not.toHaveBeenCalled() +}) test(`stores and retrieves data`, () => { store.set([scope, 'boo'], true) diff --git a/src/storage/index.ts b/src/storage/index.ts index 4c4200510..7fd50397f 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -31,6 +31,16 @@ export class Storage { this.store.set(scopes.join(this.sep), JSON.stringify({data})) } + /** + * Read the serialized `{data: value}` envelope without parsing it. Callers can + * compare raw values before repeating expensive parsing or validation. + */ + getRaw( + scopes: [...Scopes, Key], + ): string | undefined { + return this.store.getString(scopes.join(this.sep)) + } + /** * Get a value from storage based on scopes and/or keys * @@ -40,7 +50,7 @@ export class Storage { get( scopes: [...Scopes, Key], ): Schema[Key] | undefined { - const res = this.store.getString(scopes.join(this.sep)) + const res = this.getRaw(scopes) if (!res) return undefined // parsed from storage structure `{ data: }` return JSON.parse(res).data diff --git a/src/storage/schema.ts b/src/storage/schema.ts index 53b4ffb02..9e29d36f5 100644 --- a/src/storage/schema.ts +++ b/src/storage/schema.ts @@ -1,4 +1,5 @@ import {type ID as PolicyUpdate202508} from '#/components/PolicyUpdateOverlay/updates/202508/config' +import {type SessionRecord} from '#/analytics/identifiers/session' import {type Gif} from '#/features/gifPicker/types' import {type InviteThemeKey} from '#/features/inviteFriends/themes' import {type Geolocation} from '#/geolocation/types' @@ -12,11 +13,8 @@ export type Device = { * device, used with our logging and metrics tracking. */ deviceId?: string - /** - * Session ID storage for _native only_. On web, use we `sessionStorage` - */ - nativeSessionId?: string - nativeSessionIdLastEventAt?: number + /** Analytics session ID with creation, native lifecycle, or web activity time. */ + analyticsSession?: SessionRecord fontScale: '-2' | '-1' | '0' | '1' | '2' fontFamily: 'system' | 'theme' -- knotmirror 0.0.1