[APP-1782] Analytics migration (#9734)
* WIP * Clean up growthbook code, integrate into init and sessions * Move everything out of React * Add metrics client * Move to separate file * Shared metadata cache * Ensure we update metadata when session ID changes * Ensure userMetadata is cleared when logging out * WIP revamp * Integrate feature gates into analytics context * Clean up old code * Fix useMeta util * Some comments and cleanup * Add logger to base analytics context * Refactor current route handling * Rip out LogEvent from navigation * Update tracking endpoint * Migrate toClout * Clear out statsig client * Add todo, reset logger readme * Ope fix statsig noop * Refactor logging in feed-feedback, add debug logging to metrics client * Remove LogEvents alias for Metrics * Prefer root package export * Remove Metrics alias from logger * [APP-1782] Migrate to new analytics APIs (#9735) * Migrate logEvent to useAnalytics * Migrate logger.metric to useAnalytics * Migrate tricky spot, fix types * Migrate remaining tricky spot * Missed one * Remove metric() from logger * Migrate useGate to useAnalytics * Remove all other StatSig mentions * Update event payload * Update logger tests * Mock expo method * Fix session ID bug * Add session ID test * Add test for metrics client * Clarify intent * Clean up core analytics file * Clean up the call once utils * Fix TODO * Fix TODO * Fix TODO * Fix TODO * Fix TODO * Remove debug code * Fix navigation context * OK nav context is not working, todo * Checkpoint: works but feels hacky * Fix navigation context issue * Improve feature API * Improve metric logging * Update logger tests
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import {useEffect, useRef} from 'react'
|
||||
|
||||
import {getCurrentState, onAppStateChange} from '#/lib/appState'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
/**
|
||||
* Tracks passive analytics like app foreground/background time.
|
||||
*/
|
||||
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,
|
||||
),
|
||||
})
|
||||
}
|
||||
})
|
||||
return () => sub.remove()
|
||||
}, [ax])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import {GrowthBook} from '@growthbook/growthbook-react'
|
||||
|
||||
import {type Metadata} from '#/analytics/metadata'
|
||||
import * as env from '#/env'
|
||||
|
||||
export {Features} from '#/analytics/features/types'
|
||||
|
||||
/**
|
||||
* We vary the amount of time we wait for GrowthBook to fetch feature
|
||||
* gates based on the strategy specified.
|
||||
*/
|
||||
export type FeatureFetchStrategy = 'prefer-low-latency' | 'prefer-fresh-gates'
|
||||
|
||||
const TIMEOUT_INIT = 500 // TODO should base on p99 or something
|
||||
const TIMEOUT_PREFER_LOW_LATENCY = 250
|
||||
const TIMEOUT_PREFER_FRESH_GATES = 1500
|
||||
|
||||
export const features = new GrowthBook({
|
||||
apiHost: env.GROWTHBOOK_API_HOST,
|
||||
clientKey: env.GROWTHBOOK_CLIENT_KEY,
|
||||
})
|
||||
|
||||
/**
|
||||
* Initializer promise that must be awaited before using the GrowthBook
|
||||
* instance or rendering the `AnalyticsFeaturesContext`. Note: this may not be
|
||||
* fully initialized if it takes longer than `TIMEOUT_INIT` to initialize. In
|
||||
* that case, we may see a flash of uncustomized content until the
|
||||
* initialization completes.
|
||||
*/
|
||||
export const init = new Promise<void>(async y => {
|
||||
await features.init({timeout: TIMEOUT_INIT})
|
||||
y()
|
||||
})
|
||||
|
||||
/**
|
||||
* Refresh feature gates from GrowthBook. Updates attributes based on the
|
||||
* provided account, if any.
|
||||
*/
|
||||
export async function refresh({strategy}: {strategy: FeatureFetchStrategy}) {
|
||||
await features.refreshFeatures({
|
||||
timeout:
|
||||
strategy === 'prefer-low-latency'
|
||||
? TIMEOUT_PREFER_LOW_LATENCY
|
||||
: TIMEOUT_PREFER_FRESH_GATES,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts our metadata into GrowthBook attributes and sets them.
|
||||
*/
|
||||
export function setAttributes({base, session, preferences}: Metadata) {
|
||||
const {deviceId, sessionId, ...br} = base
|
||||
features.setAttributes({
|
||||
device_id: deviceId, // GrowthBook special field
|
||||
session_id: sessionId, // GrowthBook special field
|
||||
user_id: session?.did, // GrowthBook special field
|
||||
id: session?.did, // GrowthBook special field
|
||||
...br,
|
||||
...(session || {}),
|
||||
...(preferences || {}),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export enum Features {
|
||||
DebugFeedContext = 'debug_show_feedcontext',
|
||||
IsBskyTeam = 'is_bsky_team_member',
|
||||
DisableOnboardingFindContacts = 'disable_onboarding_find_contacts',
|
||||
DisableSettingsFindContacts = 'disable_settings_find_contacts',
|
||||
DisableLiveNowBeta = 'disable_live_now_beta',
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import uuid from 'react-native-uuid'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
import {device} from '#/storage'
|
||||
|
||||
const LEGACY_STABLE_ID = 'STATSIG_LOCAL_STORAGE_STABLE_ID'
|
||||
|
||||
export async function getAndMigrateDeviceId() {
|
||||
const migrated = getDeviceId()
|
||||
if (migrated) return migrated
|
||||
const id = (await AsyncStorage.getItem(LEGACY_STABLE_ID)) || uuid.v4()
|
||||
device.set(['deviceId'], id)
|
||||
return id
|
||||
}
|
||||
|
||||
export function getDeviceId() {
|
||||
return device.get(['deviceId'])
|
||||
}
|
||||
|
||||
export function getDeviceIdOrThrow() {
|
||||
const id = device.get(['deviceId'])
|
||||
if (!id) {
|
||||
throw new Error(`deviceId is not set, call getAndMigrateDeviceId first`)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from '#/analytics/identifiers/device'
|
||||
export * from '#/analytics/identifiers/session'
|
||||
@@ -0,0 +1,79 @@
|
||||
jest.mock('#/storage', () => ({
|
||||
device: {
|
||||
get: jest.fn(),
|
||||
set: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('#/analytics/identifiers/util', () => ({
|
||||
isSessionIdExpired: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('#/lib/appState', () => ({
|
||||
onAppStateChange: jest.fn(() => ({remove: jest.fn()})),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetModules()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
function getMocks() {
|
||||
const {device} = require('#/storage')
|
||||
const {isSessionIdExpired} = require('#/analytics/identifiers/util')
|
||||
return {
|
||||
device: jest.mocked(device),
|
||||
isSessionIdExpired: jest.mocked(isSessionIdExpired),
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
)
|
||||
})
|
||||
|
||||
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
|
||||
})
|
||||
isSessionIdExpired.mockReturnValue(false)
|
||||
|
||||
const {getInitialSessionId} = require('./session')
|
||||
|
||||
expect(getInitialSessionId()).toBe(existingId)
|
||||
})
|
||||
|
||||
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
|
||||
})
|
||||
isSessionIdExpired.mockReturnValue(true)
|
||||
|
||||
const {getInitialSessionId} = require('./session')
|
||||
const id = getInitialSessionId()
|
||||
|
||||
expect(id).not.toBe(existingId)
|
||||
expect(device.set).toHaveBeenCalledWith(['nativeSessionId'], id)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useEffect, useState} from 'react'
|
||||
import uuid from 'react-native-uuid'
|
||||
|
||||
import {onAppStateChange} from '#/lib/appState'
|
||||
import {isSessionIdExpired} from '#/analytics/identifiers/util'
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import {createContext, useContext, useEffect, useMemo} from 'react'
|
||||
import {Platform} from 'react-native'
|
||||
|
||||
import {Logger} from '#/logger'
|
||||
import {
|
||||
Features,
|
||||
features as feats,
|
||||
init,
|
||||
refresh,
|
||||
setAttributes,
|
||||
} from '#/analytics/features'
|
||||
import {
|
||||
getAndMigrateDeviceId,
|
||||
getDeviceId,
|
||||
getInitialSessionId,
|
||||
useSessionId,
|
||||
} from '#/analytics/identifiers'
|
||||
import {
|
||||
getNavigationMetadata,
|
||||
type MergeableMetadata,
|
||||
type Metadata,
|
||||
} from '#/analytics/metadata'
|
||||
import {type Metrics, metrics} from '#/analytics/metrics'
|
||||
import * as refParams from '#/analytics/misc/refParams'
|
||||
import {getMetadataForLogger} from '#/analytics/utils'
|
||||
import * as env from '#/env'
|
||||
import {useGeolocation} from '#/geolocation'
|
||||
import {device} from '#/storage'
|
||||
|
||||
export * as utils from '#/analytics/utils'
|
||||
export const features = {init, refresh}
|
||||
export {Features} from '#/analytics/features'
|
||||
export {type Metrics} from '#/analytics/metrics'
|
||||
|
||||
type LoggerType = {
|
||||
debug: Logger['debug']
|
||||
info: Logger['info']
|
||||
log: Logger['log']
|
||||
warn: Logger['warn']
|
||||
error: Logger['error']
|
||||
/**
|
||||
* Clones the existing logger and overrides the `context` value. Existing
|
||||
* metadata is inherited.
|
||||
*
|
||||
* ```ts
|
||||
* const ax = useAnalytics()
|
||||
* const logger = ax.logger.useChild(ax.logger.Context.Notifications)
|
||||
* ```
|
||||
*/
|
||||
useChild: (context: Exclude<Logger['context'], undefined>) => LoggerType
|
||||
Context: typeof Logger.Context
|
||||
}
|
||||
export type AnalyticsContextType = {
|
||||
metadata: Metadata
|
||||
logger: LoggerType
|
||||
metric: <E extends keyof Metrics>(
|
||||
event: E,
|
||||
payload: Metrics[E],
|
||||
metadata?: MergeableMetadata,
|
||||
) => void
|
||||
features: typeof Features & {
|
||||
enabled(feature: Features): boolean
|
||||
}
|
||||
}
|
||||
export type AnalyticsBaseContextType = Omit<AnalyticsContextType, 'features'>
|
||||
|
||||
function createLogger(
|
||||
context: Logger['context'],
|
||||
metadata: Partial<Metadata>,
|
||||
): LoggerType {
|
||||
const logger = Logger.create(context, metadata)
|
||||
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),
|
||||
useChild: (context: Exclude<Logger['context'], undefined>) => {
|
||||
return useMemo(() => createLogger(context, metadata), [context, metadata])
|
||||
},
|
||||
Context: Logger.Context,
|
||||
}
|
||||
}
|
||||
|
||||
const Context = createContext<AnalyticsBaseContextType>({
|
||||
logger: createLogger(Logger.Context.Default, {}),
|
||||
metric: (event, payload, metadata) => {
|
||||
if (metadata && '__meta' in metadata) {
|
||||
delete metadata.__meta
|
||||
}
|
||||
metrics.track(event, payload, {
|
||||
...metadata,
|
||||
navigation: getNavigationMetadata(),
|
||||
})
|
||||
},
|
||||
metadata: {
|
||||
base: {
|
||||
deviceId: getDeviceId() ?? 'unknown',
|
||||
sessionId: getInitialSessionId(),
|
||||
platform: Platform.OS,
|
||||
appVersion: env.APP_VERSION,
|
||||
bundleIdentifier: env.BUNDLE_IDENTIFIER,
|
||||
bundleDate: env.BUNDLE_DATE,
|
||||
referrerSrc: refParams.src,
|
||||
referrerUrl: refParams.url,
|
||||
},
|
||||
geolocation: device.get(['mergedGeolocation']) || {
|
||||
countryCode: '',
|
||||
regionCode: '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* Ensures that deviceId is set and migrated from legacy storage. Handled on
|
||||
* startup in `App.<platform>.tsx`. This must be awaited prior to the app
|
||||
* booting up.
|
||||
*/
|
||||
export const setupDeviceId = getAndMigrateDeviceId()
|
||||
|
||||
/**
|
||||
* Analytics context provider. Decorates the parent analytics context with
|
||||
* additional metadata. Nesting should be done carefully and sparingly.
|
||||
*/
|
||||
export function AnalyticsContext({
|
||||
children,
|
||||
metadata,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
metadata?: MergeableMetadata
|
||||
}) {
|
||||
if (metadata) {
|
||||
if (!('__meta' in metadata)) {
|
||||
throw new Error(
|
||||
'Use the useMeta() helper when passing metadata to AnalyticsContext',
|
||||
)
|
||||
}
|
||||
}
|
||||
const sessionId = useSessionId()
|
||||
const geolocation = useGeolocation()
|
||||
const parentContext = useContext(Context)
|
||||
const childContext = useMemo(() => {
|
||||
const combinedMetadata = {
|
||||
...parentContext.metadata,
|
||||
...metadata,
|
||||
base: {
|
||||
...parentContext.metadata.base,
|
||||
sessionId,
|
||||
},
|
||||
geolocation,
|
||||
}
|
||||
const context: AnalyticsBaseContextType = {
|
||||
...parentContext,
|
||||
logger: createLogger(
|
||||
Logger.Context.Default,
|
||||
getMetadataForLogger(combinedMetadata),
|
||||
),
|
||||
metadata: combinedMetadata,
|
||||
metric: (event, payload, extraMetadata) => {
|
||||
parentContext.metric(event, payload, {
|
||||
...combinedMetadata,
|
||||
...extraMetadata,
|
||||
})
|
||||
},
|
||||
}
|
||||
return context
|
||||
}, [sessionId, geolocation, parentContext, metadata])
|
||||
return <Context.Provider value={childContext}>{children}</Context.Provider>
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature gates provider. Decorates the parent analytics context with
|
||||
* feature gate capabilities. Should be mounted within `AnalyticsContext`,
|
||||
* and below the `<Fragment key={did} />` breaker in `App.<platform>.tsx`.
|
||||
*/
|
||||
export function AnalyticsFeaturesContext({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const parentContext = useContext(Context)
|
||||
|
||||
useEffect(() => {
|
||||
feats.setTrackingCallback((experiment, result) => {
|
||||
parentContext.metric('experiment:viewed', {
|
||||
experimentId: experiment.key,
|
||||
variationId: result.key,
|
||||
})
|
||||
})
|
||||
}, [parentContext.metric])
|
||||
|
||||
useEffect(() => {
|
||||
setAttributes(parentContext.metadata)
|
||||
}, [parentContext.metadata])
|
||||
|
||||
const childContext = useMemo<AnalyticsContextType>(() => {
|
||||
return {
|
||||
...parentContext,
|
||||
features: {
|
||||
enabled: feats.isOn.bind(feats),
|
||||
...Features,
|
||||
},
|
||||
}
|
||||
}, [parentContext])
|
||||
|
||||
return <Context.Provider value={childContext}>{children}</Context.Provider>
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic analytics context without feature gates. Should really only be used
|
||||
* above the `AnalyticsFeaturesContext` provider.
|
||||
*/
|
||||
export function useAnalyticsBase() {
|
||||
return useContext(Context)
|
||||
}
|
||||
|
||||
/**
|
||||
* The main analytics context, including feature gates. Use this everywhere you
|
||||
* need metrics, features, or logging within the React tree.
|
||||
*/
|
||||
export function useAnalytics() {
|
||||
const ctx = useContext(Context)
|
||||
if (!('features' in ctx)) {
|
||||
throw new Error(
|
||||
'useAnalytics must be used within an AnalyticsFeaturesContext',
|
||||
)
|
||||
}
|
||||
return ctx as AnalyticsContextType
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import {type Geolocation} from '#/geolocation'
|
||||
|
||||
export type BaseMetadata = {
|
||||
deviceId: string
|
||||
sessionId: string
|
||||
platform: string
|
||||
appVersion: string
|
||||
bundleIdentifier: string
|
||||
bundleDate: number
|
||||
referrerSrc: string
|
||||
referrerUrl: string
|
||||
}
|
||||
|
||||
export type GeolocationMetadata = Geolocation
|
||||
|
||||
export type SessionMetadata = {
|
||||
did: string
|
||||
isBskyPds: boolean
|
||||
}
|
||||
|
||||
export type PreferencesMetadata = {
|
||||
appLanguage: string
|
||||
contentLanguages: string[]
|
||||
}
|
||||
|
||||
export type MergeableMetadata = {
|
||||
session?: SessionMetadata
|
||||
preferences?: PreferencesMetadata
|
||||
/**
|
||||
* Navigation metadata is not actually available on this object, instead it's
|
||||
* merged in at time-of-log/metric. See `#/analytics/metadata.ts` for details.
|
||||
*/
|
||||
navigation?: NavigationMetadata
|
||||
}
|
||||
|
||||
export type Metadata = {
|
||||
base: BaseMetadata
|
||||
geolocation: GeolocationMetadata
|
||||
} & MergeableMetadata
|
||||
|
||||
/*
|
||||
* 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
|
||||
* way to get current navigation state without an additional re-render between
|
||||
* navigations.
|
||||
*
|
||||
* So instead of this data being available on the Metadata object, it's stored
|
||||
* here and merged in at time-of-log/metric.
|
||||
*/
|
||||
export type NavigationMetadata = {
|
||||
previousScreen?: string
|
||||
currentScreen?: string
|
||||
}
|
||||
let navigationMetadata: NavigationMetadata | undefined
|
||||
export function getNavigationMetadata() {
|
||||
console.log('metadata', JSON.stringify(navigationMetadata, null, 2))
|
||||
return navigationMetadata
|
||||
}
|
||||
export function setNavigationMetadata(meta: NavigationMetadata | undefined) {
|
||||
navigationMetadata = meta
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import {MetricsClient} from './client'
|
||||
|
||||
let appStateCallback: (state: string) => void
|
||||
|
||||
jest.mock('#/lib/appState', () => ({
|
||||
onAppStateChange: jest.fn(cb => {
|
||||
appStateCallback = cb
|
||||
return {remove: jest.fn()}
|
||||
}),
|
||||
}))
|
||||
|
||||
jest.mock('#/logger', () => ({
|
||||
Logger: {
|
||||
create: () => ({
|
||||
info: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}),
|
||||
Context: {Metric: 'metric'},
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('#/env', () => ({
|
||||
METRICS_API_HOST: 'https://test.metrics.api',
|
||||
IS_WEB: false,
|
||||
}))
|
||||
|
||||
type TestEvents = {
|
||||
click: {button: string}
|
||||
view: {screen: string}
|
||||
}
|
||||
|
||||
describe('MetricsClient', () => {
|
||||
let fetchMock: jest.Mock
|
||||
let fetchRequests: {body: any}[]
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers({advanceTimers: true})
|
||||
fetchRequests = []
|
||||
fetchMock = jest.fn().mockImplementation(async (_url, options) => {
|
||||
const body = JSON.parse(options.body)
|
||||
fetchRequests.push({body})
|
||||
return {ok: true, status: 200}
|
||||
})
|
||||
global.fetch = fetchMock
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('flushes events on interval', async () => {
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
client.track('view', {screen: 'home'})
|
||||
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// Advance past the 10 second interval
|
||||
await jest.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events).toHaveLength(2)
|
||||
expect(fetchRequests[0].body.events[0].event).toBe('click')
|
||||
expect(fetchRequests[0].body.events[1].event).toBe('view')
|
||||
})
|
||||
|
||||
it('flushes when maxBatchSize is exceeded', async () => {
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.maxBatchSize = 5
|
||||
|
||||
// Add events up to maxBatchSize (should not flush yet)
|
||||
for (let i = 0; i < 5; i++) {
|
||||
client.track('click', {button: `btn-${i}`})
|
||||
}
|
||||
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// One more event should trigger flush (> maxBatchSize)
|
||||
client.track('click', {button: 'btn-trigger'})
|
||||
|
||||
// Allow microtasks to run
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events).toHaveLength(6)
|
||||
})
|
||||
|
||||
it('retries failed events once on 500 response', async () => {
|
||||
let requestCount = 0
|
||||
|
||||
fetchMock.mockImplementation(async (_url, options) => {
|
||||
requestCount++
|
||||
const body = JSON.parse(options.body)
|
||||
|
||||
if (requestCount === 1) {
|
||||
// First request fails with 500 - "Failed to fetch" triggers isNetworkError
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => 'Internal Server Error',
|
||||
}
|
||||
}
|
||||
|
||||
// Retry succeeds
|
||||
fetchRequests.push({body})
|
||||
return {ok: true, status: 200}
|
||||
})
|
||||
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
|
||||
// Trigger flush via interval
|
||||
await jest.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(requestCount).toBe(1)
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// Simulate app coming to foreground to trigger retry
|
||||
appStateCallback('active')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(requestCount).toBe(2)
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events[0].event).toBe('click')
|
||||
})
|
||||
|
||||
it('does not retry more than once', async () => {
|
||||
let requestCount = 0
|
||||
|
||||
fetchMock.mockImplementation(async () => {
|
||||
requestCount++
|
||||
// Always fail with network-like error
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => 'Internal Server Error',
|
||||
}
|
||||
})
|
||||
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
|
||||
// First flush fails
|
||||
await jest.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(requestCount).toBe(1)
|
||||
|
||||
// Retry also fails
|
||||
appStateCallback('active')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(requestCount).toBe(2)
|
||||
|
||||
// Another foreground event should not retry again (events are dropped)
|
||||
appStateCallback('active')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(requestCount).toBe(2) // No additional requests
|
||||
})
|
||||
|
||||
it('flushes when app goes to background', async () => {
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// Simulate app going to background
|
||||
appStateCallback('background')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
import {onAppStateChange} from '#/lib/appState'
|
||||
import {isNetworkError} from '#/lib/strings/errors'
|
||||
import {Logger} from '#/logger'
|
||||
import * as env from '#/env'
|
||||
|
||||
type Event<M extends Record<string, any>> = {
|
||||
time: number
|
||||
event: keyof M
|
||||
payload: M[keyof M]
|
||||
metadata: Record<string, any>
|
||||
}
|
||||
|
||||
const TRACKING_ENDPOINT = env.METRICS_API_HOST + '/t'
|
||||
const logger = Logger.create(Logger.Context.Metric, {})
|
||||
|
||||
export class MetricsClient<M extends Record<string, any>> {
|
||||
maxBatchSize = 100
|
||||
|
||||
private started: boolean = false
|
||||
private queue: Event<M>[] = []
|
||||
private failedQueue: Event<M>[] = []
|
||||
private flushInterval: NodeJS.Timeout | null = null
|
||||
|
||||
start() {
|
||||
if (this.started) return
|
||||
this.started = true
|
||||
this.flushInterval = setInterval(() => {
|
||||
this.flush()
|
||||
}, 10_000)
|
||||
onAppStateChange(state => {
|
||||
if (state === 'active') {
|
||||
this.retryFailedLogs()
|
||||
} else {
|
||||
this.flush()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
track<E extends keyof M>(
|
||||
event: E,
|
||||
payload: M[E],
|
||||
metadata: Record<string, any> = {},
|
||||
) {
|
||||
this.start()
|
||||
|
||||
const e = {
|
||||
time: Date.now(),
|
||||
event,
|
||||
payload,
|
||||
metadata,
|
||||
}
|
||||
this.queue.push(e)
|
||||
|
||||
logger.info(`event: ${e.event as string}`, e)
|
||||
|
||||
if (this.queue.length > this.maxBatchSize) {
|
||||
this.flush()
|
||||
}
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (!this.queue.length) return
|
||||
const events = this.queue.splice(0, this.queue.length)
|
||||
this.sendBatch(events)
|
||||
}
|
||||
|
||||
private async sendBatch(events: Event<M>[], isRetry: boolean = false) {
|
||||
logger.debug(`sendBatch: ${events.length}`, {
|
||||
isRetry,
|
||||
})
|
||||
|
||||
try {
|
||||
const body = JSON.stringify({events})
|
||||
if (env.IS_WEB && 'navigator' in globalThis && navigator.sendBeacon) {
|
||||
const success = navigator.sendBeacon(
|
||||
TRACKING_ENDPOINT,
|
||||
new Blob([body], {type: 'application/json'}),
|
||||
)
|
||||
if (!success) {
|
||||
// construct a "network error" for `isNetworkError` to work
|
||||
throw new Error(`Failed to fetch: sendBeacon returned false`)
|
||||
}
|
||||
} else {
|
||||
const res = await fetch(TRACKING_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({events}),
|
||||
keepalive: true,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.text().catch(() => 'Unknown error')
|
||||
// construct a "network error" for `isNetworkError` to work
|
||||
throw new Error(`${res.status} Failed to fetch — ${error}`)
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (isNetworkError(e)) {
|
||||
if (isRetry) return // retry once
|
||||
this.failedQueue.push(...events)
|
||||
return
|
||||
}
|
||||
logger.error(`Failed to send metrics`, {
|
||||
safeMessage: e.toString(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private retryFailedLogs() {
|
||||
if (!this.failedQueue.length) return
|
||||
const events = this.failedQueue.splice(0, this.failedQueue.length)
|
||||
this.sendBatch(events, true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import {MetricsClient} from '#/analytics/metrics/client'
|
||||
import {type Events} from '#/analytics/metrics/types'
|
||||
|
||||
export type {Events as Metrics} from '#/analytics/metrics/types'
|
||||
export * from '#/analytics/metrics/utils'
|
||||
export const metrics = new MetricsClient<Events>()
|
||||
@@ -0,0 +1,831 @@
|
||||
/*
|
||||
* Do not import runtime code into this file
|
||||
*/
|
||||
|
||||
import {type NotificationReason} from '#/lib/hooks/useNotificationHandler'
|
||||
import {type FeedDescriptor} from '#/state/queries/post-feed'
|
||||
import {type LiveEventFeedMetricContext} from '#/features/liveEvents/types'
|
||||
|
||||
export type Events = {
|
||||
// App events
|
||||
init: {
|
||||
initMs: number
|
||||
}
|
||||
'experiment:viewed': {
|
||||
experimentId: string
|
||||
variationId: string
|
||||
}
|
||||
|
||||
'account:loggedIn': {
|
||||
logContext:
|
||||
| 'LoginForm'
|
||||
| 'SwitchAccount'
|
||||
| 'ChooseAccountForm'
|
||||
| 'Settings'
|
||||
| 'Notification'
|
||||
withPassword: boolean
|
||||
}
|
||||
'account:loggedOut': {
|
||||
logContext:
|
||||
| 'SwitchAccount'
|
||||
| 'Settings'
|
||||
| 'SignupQueued'
|
||||
| 'Deactivated'
|
||||
| 'Takendown'
|
||||
| 'AgeAssuranceNoAccessScreen'
|
||||
scope: 'current' | 'every'
|
||||
}
|
||||
'notifications:openApp': {
|
||||
reason: NotificationReason
|
||||
causedBoot: boolean
|
||||
}
|
||||
'notifications:request': {
|
||||
context: 'StartOnboarding' | 'AfterOnboarding' | 'Login' | 'Home'
|
||||
status: 'granted' | 'denied' | 'undetermined'
|
||||
}
|
||||
'state:background': {
|
||||
secondsActive: number
|
||||
}
|
||||
'state:foreground': {}
|
||||
'router:navigate': {
|
||||
from?: string
|
||||
}
|
||||
'deepLink:referrerReceived': {
|
||||
to: string
|
||||
referrer: string
|
||||
hostname: string
|
||||
}
|
||||
|
||||
// Screen events
|
||||
'splash:signInPressed': {}
|
||||
'splash:createAccountPressed': {}
|
||||
'welcomeModal:signupClicked': {}
|
||||
'welcomeModal:exploreClicked': {}
|
||||
'welcomeModal:signinClicked': {}
|
||||
'welcomeModal:dismissed': {}
|
||||
'welcomeModal:presented': {}
|
||||
'signup:nextPressed': {
|
||||
activeStep: number
|
||||
phoneVerificationRequired?: boolean
|
||||
}
|
||||
'signup:backPressed': {
|
||||
activeStep: number
|
||||
}
|
||||
'signup:captchaSuccess': {}
|
||||
'signup:captchaFailure': {}
|
||||
'signup:fieldError': {
|
||||
field: string
|
||||
errorCount: number
|
||||
errorMessage: string
|
||||
activeStep: number
|
||||
}
|
||||
'signup:backgrounded': {
|
||||
activeStep: number
|
||||
backgroundCount: number
|
||||
}
|
||||
'signup:handleTaken': {typeahead?: boolean}
|
||||
'signup:handleAvailable': {typeahead?: boolean}
|
||||
'signup:handleSuggestionSelected': {method: string}
|
||||
'signin:hostingProviderPressed': {
|
||||
hostingProviderDidChange: boolean
|
||||
}
|
||||
'signin:hostingProviderFailedResolution': {}
|
||||
'signin:success': {
|
||||
failedAttemptsCount: number
|
||||
isUsingCustomProvider: boolean
|
||||
timeTakenSeconds: number
|
||||
}
|
||||
'signin:backPressed': {
|
||||
failedAttemptsCount: number
|
||||
}
|
||||
'signin:forgotPasswordPressed': {}
|
||||
'signin:passwordReset': {}
|
||||
'signin:passwordResetSuccess': {}
|
||||
'signin:passwordResetFailure': {}
|
||||
'onboarding:interests:nextPressed': {
|
||||
selectedInterests: string[]
|
||||
selectedInterestsLength: number
|
||||
}
|
||||
'onboarding:suggestedAccounts:tabPressed': {
|
||||
tab: string
|
||||
}
|
||||
'onboarding:suggestedAccounts:followAllPressed': {
|
||||
tab: string
|
||||
numAccounts: number
|
||||
}
|
||||
'onboarding:suggestedAccounts:nextPressed': {
|
||||
selectedAccountsLength: number
|
||||
skipped: boolean
|
||||
}
|
||||
'onboarding:followingFeed:nextPressed': {}
|
||||
'onboarding:algoFeeds:nextPressed': {
|
||||
selectedPrimaryFeeds: string[]
|
||||
selectedPrimaryFeedsLength: number
|
||||
selectedSecondaryFeeds: string[]
|
||||
selectedSecondaryFeedsLength: number
|
||||
}
|
||||
'onboarding:topicalFeeds:nextPressed': {
|
||||
selectedFeeds: string[]
|
||||
selectedFeedsLength: number
|
||||
}
|
||||
'onboarding:moderation:nextPressed': {}
|
||||
'onboarding:profile:nextPressed': {}
|
||||
'onboarding:finished:nextPressed': {
|
||||
usedStarterPack: boolean
|
||||
starterPackName?: string
|
||||
starterPackCreator?: string
|
||||
starterPackUri?: string
|
||||
profilesFollowed: number
|
||||
feedsPinned: number
|
||||
}
|
||||
'onboarding:finished:avatarResult': {
|
||||
avatarResult: 'default' | 'created' | 'uploaded'
|
||||
}
|
||||
'onboarding:valueProp:stepOne:nextPressed': {}
|
||||
'onboarding:valueProp:stepTwo:nextPressed': {}
|
||||
'onboarding:valueProp:skipPressed': {}
|
||||
'home:feedDisplayed': {
|
||||
feedUrl: string
|
||||
feedType: string
|
||||
index: number
|
||||
reason?: string
|
||||
}
|
||||
'feed:endReached': {
|
||||
feedUrl: string
|
||||
feedType: string
|
||||
itemCount: number
|
||||
}
|
||||
'feed:refresh': {
|
||||
feedUrl: string
|
||||
feedType: string
|
||||
reason: 'pull-to-refresh' | 'soft-reset' | 'load-latest'
|
||||
}
|
||||
'feed:save': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:unsave': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:pin': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:unpin': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:like': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:unlike': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:share': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:suggestion:seen': {
|
||||
feedUrl: string
|
||||
}
|
||||
'feed:suggestion:press': {
|
||||
feedUrl: string
|
||||
}
|
||||
'post:showMore': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:showLess': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'feed:clickthrough': {
|
||||
feed: string
|
||||
count: number
|
||||
}
|
||||
'feed:engaged': {
|
||||
feed: string
|
||||
count: number
|
||||
}
|
||||
'feed:seen': {
|
||||
feed: string
|
||||
count: number
|
||||
}
|
||||
|
||||
'feed:discover:emptyError': {
|
||||
userDid: string
|
||||
}
|
||||
|
||||
'composer:gif:open': {}
|
||||
'composer:gif:select': {}
|
||||
'composerPrompt:press': {}
|
||||
'composerPrompt:camera:press': {}
|
||||
'composerPrompt:gallery:press': {}
|
||||
|
||||
'composer:threadgate:open': {
|
||||
nudged: boolean
|
||||
}
|
||||
'composer:threadgate:save': {
|
||||
replyOptions: string
|
||||
quotesEnabled: boolean
|
||||
persist: boolean
|
||||
hasChanged: boolean
|
||||
}
|
||||
|
||||
// Data events
|
||||
'account:create:begin': {}
|
||||
'account:create:success': {
|
||||
signupDuration: number
|
||||
fieldErrorsTotal: number
|
||||
backgroundCount: number
|
||||
}
|
||||
'post:create': {
|
||||
imageCount: number
|
||||
isReply: boolean
|
||||
isPartOfThread: boolean
|
||||
hasLink: boolean
|
||||
hasQuote: boolean
|
||||
langs: string
|
||||
logContext: 'Composer'
|
||||
}
|
||||
'thread:create': {
|
||||
postCount: number
|
||||
isReply: boolean
|
||||
}
|
||||
'post:like': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
doesLikerFollowPoster: boolean | undefined
|
||||
doesPosterFollowLiker: boolean | undefined
|
||||
likerClout: number | undefined
|
||||
postClout: number | undefined
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
}
|
||||
'post:repost': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
}
|
||||
'post:unlike': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
}
|
||||
'post:unrepost': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
}
|
||||
'post:mute': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:unmute': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:pin': {}
|
||||
'post:unpin': {}
|
||||
'post:bookmark': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:unbookmark': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:clickReply': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:clickQuotePost': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:clickthroughAuthor': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:clickthroughItem': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:clickthroughEmbed': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'post:view': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext:
|
||||
| 'FeedItem'
|
||||
| 'PostThreadItem'
|
||||
| 'Post'
|
||||
| 'ImmersiveVideo'
|
||||
| 'SearchResults'
|
||||
| 'Bookmarks'
|
||||
| 'Notifications'
|
||||
| 'Hashtag'
|
||||
| 'Topic'
|
||||
| 'PostQuotes'
|
||||
feedDescriptor?: string
|
||||
position?: number
|
||||
}
|
||||
'bookmarks:view': {}
|
||||
'bookmarks:post-clicked': {}
|
||||
'profile:follow': {
|
||||
contextProfileDid?: string
|
||||
didBecomeMutual: boolean | undefined
|
||||
followeeClout: number | undefined
|
||||
followeeDid: string
|
||||
followerClout: number | undefined
|
||||
position?: number
|
||||
logContext:
|
||||
| 'RecommendedFollowsItem'
|
||||
| 'PostThreadItem'
|
||||
| 'ProfileCard'
|
||||
| 'ProfileHeader'
|
||||
| 'ProfileHeaderSuggestedFollows'
|
||||
| 'ProfileMenu'
|
||||
| 'ProfileHoverCard'
|
||||
| 'AvatarButton'
|
||||
| 'StarterPackProfilesList'
|
||||
| 'FeedInterstitial'
|
||||
| 'PostOnboardingFindFollows'
|
||||
| 'ImmersiveVideo'
|
||||
| 'ExploreSuggestedAccounts'
|
||||
| 'OnboardingSuggestedAccounts'
|
||||
| 'FindContacts'
|
||||
}
|
||||
'profile:followers:view': {
|
||||
contextProfileDid: string
|
||||
isOwnProfile: boolean
|
||||
}
|
||||
'profile:followers:paginate': {
|
||||
contextProfileDid: string
|
||||
itemCount: number
|
||||
page: number
|
||||
}
|
||||
'profile:following:view': {
|
||||
contextProfileDid: string
|
||||
isOwnProfile: boolean
|
||||
}
|
||||
'profile:following:paginate': {
|
||||
contextProfileDid: string
|
||||
itemCount: number
|
||||
page: number
|
||||
}
|
||||
'profileCard:seen': {
|
||||
contextProfileDid?: string
|
||||
profileDid: string
|
||||
position?: number
|
||||
}
|
||||
'suggestedUser:follow': {
|
||||
logContext:
|
||||
| 'Explore'
|
||||
| 'InterstitialDiscover'
|
||||
| 'InterstitialProfile'
|
||||
| 'Profile'
|
||||
| 'Onboarding'
|
||||
location: 'Card' | 'Profile'
|
||||
recId?: number
|
||||
position: number
|
||||
suggestedDid: string
|
||||
category: string | null
|
||||
}
|
||||
'suggestedUser:press': {
|
||||
logContext:
|
||||
| 'Explore'
|
||||
| 'InterstitialDiscover'
|
||||
| 'InterstitialProfile'
|
||||
| 'Onboarding'
|
||||
recId?: number
|
||||
position: number
|
||||
suggestedDid: string
|
||||
category: string | null
|
||||
}
|
||||
'suggestedUser:seen': {
|
||||
logContext:
|
||||
| 'Explore'
|
||||
| 'InterstitialDiscover'
|
||||
| 'InterstitialProfile'
|
||||
| 'Profile'
|
||||
| 'Onboarding'
|
||||
| 'ProgressGuide'
|
||||
recId?: number
|
||||
position: number
|
||||
suggestedDid: string
|
||||
category: string | null
|
||||
}
|
||||
'suggestedUser:seeMore': {
|
||||
logContext:
|
||||
| 'Explore'
|
||||
| 'InterstitialDiscover'
|
||||
| 'InterstitialProfile'
|
||||
| 'Profile'
|
||||
| 'Onboarding'
|
||||
}
|
||||
'suggestedUser:dismiss': {
|
||||
logContext: 'InterstitialDiscover' | 'InterstitialProfile'
|
||||
recId?: number
|
||||
position: number
|
||||
suggestedDid: string
|
||||
}
|
||||
'profile:unfollow': {
|
||||
logContext:
|
||||
| 'RecommendedFollowsItem'
|
||||
| 'PostThreadItem'
|
||||
| 'ProfileCard'
|
||||
| 'ProfileHeader'
|
||||
| 'ProfileHeaderSuggestedFollows'
|
||||
| 'ProfileMenu'
|
||||
| 'ProfileHoverCard'
|
||||
| 'Chat'
|
||||
| 'AvatarButton'
|
||||
| 'StarterPackProfilesList'
|
||||
| 'FeedInterstitial'
|
||||
| 'PostOnboardingFindFollows'
|
||||
| 'ImmersiveVideo'
|
||||
| 'ExploreSuggestedAccounts'
|
||||
| 'OnboardingSuggestedAccounts'
|
||||
| 'FindContacts'
|
||||
}
|
||||
'chat:create': {
|
||||
logContext: 'ProfileHeader' | 'NewChatDialog' | 'SendViaChatDialog'
|
||||
}
|
||||
'chat:open': {
|
||||
logContext:
|
||||
| 'ProfileHeader'
|
||||
| 'NewChatDialog'
|
||||
| 'ChatsList'
|
||||
| 'SendViaChatDialog'
|
||||
}
|
||||
'starterPack:addUser': {
|
||||
starterPack?: string
|
||||
}
|
||||
'starterPack:removeUser': {
|
||||
starterPack?: string
|
||||
}
|
||||
'starterPack:share': {
|
||||
starterPack: string
|
||||
shareType: 'link' | 'qrcode'
|
||||
qrShareType?: 'save' | 'copy' | 'share'
|
||||
}
|
||||
'starterPack:followAll': {
|
||||
logContext: 'StarterPackProfilesList' | 'Onboarding'
|
||||
starterPack: string
|
||||
count: number
|
||||
}
|
||||
'starterPack:delete': {}
|
||||
'starterPack:create': {
|
||||
setName: boolean
|
||||
setDescription: boolean
|
||||
profilesCount: number
|
||||
feedsCount: number
|
||||
}
|
||||
'starterPack:ctaPress': {
|
||||
starterPack: string
|
||||
}
|
||||
'starterPack:opened': {
|
||||
starterPack: string
|
||||
}
|
||||
'link:clicked': {
|
||||
url: string
|
||||
domain: string
|
||||
}
|
||||
|
||||
'feed:interstitial:feedCard:press': {}
|
||||
'desktopFeeds:feed:click': {
|
||||
feedUri: string
|
||||
feedDescriptor: string
|
||||
}
|
||||
|
||||
'profile:header:suggestedFollowsCard:press': {}
|
||||
'profile:addToStarterPack': {}
|
||||
|
||||
'test:all:always': {}
|
||||
'test:all:sometimes': {}
|
||||
'test:all:boosted_by_gate1': {reason: 'base' | 'gate1'}
|
||||
'test:all:boosted_by_gate2': {reason: 'base' | 'gate2'}
|
||||
'test:all:boosted_by_both': {reason: 'base' | 'gate1' | 'gate2'}
|
||||
'test:gate1:always': {}
|
||||
'test:gate1:sometimes': {}
|
||||
'test:gate2:always': {}
|
||||
'test:gate2:sometimes': {}
|
||||
|
||||
'tmd:share': {}
|
||||
'tmd:download': {}
|
||||
'tmd:post': {}
|
||||
|
||||
'trendingTopics:show': {
|
||||
context: 'settings'
|
||||
}
|
||||
'trendingTopics:hide': {
|
||||
context: 'settings' | 'sidebar' | 'interstitial' | 'explore:trending'
|
||||
}
|
||||
'trendingTopic:click': {
|
||||
context: 'sidebar' | 'interstitial' | 'explore'
|
||||
}
|
||||
'recommendedTopic:click': {
|
||||
context: 'explore'
|
||||
}
|
||||
'trendingVideos:show': {
|
||||
context: 'settings'
|
||||
}
|
||||
'trendingVideos:hide': {
|
||||
context: 'settings' | 'interstitial:discover' | 'interstitial:explore'
|
||||
}
|
||||
'videoCard:click': {
|
||||
context: 'interstitial:discover' | 'interstitial:explore' | 'feed'
|
||||
}
|
||||
|
||||
'explore:module:seen': {
|
||||
module:
|
||||
| 'trendingTopics'
|
||||
| 'trendingVideos'
|
||||
| 'suggestedAccounts'
|
||||
| 'suggestedFeeds'
|
||||
| 'suggestedStarterPacks'
|
||||
| `feed:${FeedDescriptor}`
|
||||
}
|
||||
'explore:module:searchButtonPress': {
|
||||
module: 'suggestedAccounts' | 'suggestedFeeds'
|
||||
}
|
||||
'explore:suggestedAccounts:tabPressed': {
|
||||
tab: string
|
||||
}
|
||||
|
||||
'progressGuide:hide': {}
|
||||
'progressGuide:followDialog:open': {}
|
||||
|
||||
'moderation:subscribedToLabeler': {}
|
||||
'moderation:unsubscribedFromLabeler': {}
|
||||
'moderation:changeLabelPreference': {
|
||||
preference: string
|
||||
}
|
||||
|
||||
'moderation:subscribedToList': {
|
||||
listType: 'mute' | 'block'
|
||||
}
|
||||
'moderation:unsubscribedFromList': {
|
||||
listType: 'mute' | 'block'
|
||||
}
|
||||
|
||||
'reportDialog:open': {
|
||||
subjectType: string
|
||||
}
|
||||
'reportDialog:close': {}
|
||||
'reportDialog:success': {
|
||||
reason: string
|
||||
labeler: string
|
||||
details: boolean
|
||||
}
|
||||
'reportDialog:failure': {}
|
||||
|
||||
translate: {
|
||||
sourceLanguages: string[]
|
||||
targetLanguage: string
|
||||
textLength: number
|
||||
}
|
||||
|
||||
'verification:create': {}
|
||||
'verification:revoke': {}
|
||||
'verification:badge:click': {}
|
||||
'verification:learn-more': {
|
||||
location:
|
||||
| 'initialAnnouncementeNux'
|
||||
| 'verificationsDialog'
|
||||
| 'verifierDialog'
|
||||
| 'verificationSettings'
|
||||
}
|
||||
'verification:settings:hideBadges': {}
|
||||
'verification:settings:unHideBadges': {}
|
||||
|
||||
'live:create': {duration: number}
|
||||
'live:edit': {}
|
||||
'live:remove': {}
|
||||
'live:card:open': {subject: string; from: 'post' | 'profile'}
|
||||
'live:card:watch': {subject: string}
|
||||
'live:card:openProfile': {subject: string}
|
||||
'live:view:profile': {subject: string}
|
||||
'live:view:post': {subject: string; feed?: string}
|
||||
|
||||
'post:share': {
|
||||
uri: string
|
||||
authorDid: string
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
feedDescriptor?: string
|
||||
postContext: 'feed' | 'thread'
|
||||
position?: number
|
||||
}
|
||||
'share:press:copyLink': {}
|
||||
'share:press:nativeShare': {}
|
||||
'share:press:openDmSearch': {}
|
||||
'share:press:dmSelected': {}
|
||||
'share:press:recentDm': {}
|
||||
'share:press:embed': {}
|
||||
|
||||
'thread:click:showOtherReplies': {}
|
||||
'thread:click:hideReplyForMe': {}
|
||||
'thread:click:hideReplyForEveryone': {}
|
||||
'thread:preferences:load': {
|
||||
[key: string]: any
|
||||
}
|
||||
'thread:preferences:update': {
|
||||
[key: string]: any
|
||||
}
|
||||
'thread:click:headerMenuOpen': {}
|
||||
'thread:click:editOwnThreadgate': {}
|
||||
'thread:click:viewSomeoneElsesThreadgate': {}
|
||||
'activitySubscription:enable': {
|
||||
setting: 'posts' | 'posts_and_replies'
|
||||
}
|
||||
'activitySubscription:disable': {}
|
||||
'activityPreference:changeChannels': {
|
||||
name: string
|
||||
push: boolean
|
||||
list: boolean
|
||||
}
|
||||
'activityPreference:changeFilter': {
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
|
||||
'ageAssurance:navigateToSettings': {}
|
||||
'ageAssurance:dismissFeedBanner': {}
|
||||
'ageAssurance:dismissSettingsNotice': {}
|
||||
'ageAssurance:initDialogOpen': {
|
||||
hasInitiatedPreviously: boolean
|
||||
}
|
||||
'ageAssurance:initDialogSubmit': {}
|
||||
'ageAssurance:api:begin': {
|
||||
platform: string
|
||||
countryCode: string
|
||||
regionCode?: string
|
||||
}
|
||||
'ageAssurance:initDialogError': {
|
||||
code: string
|
||||
}
|
||||
'ageAssurance:redirectDialogOpen': {}
|
||||
'ageAssurance:redirectDialogSuccess': {}
|
||||
'ageAssurance:redirectDialogFail': {}
|
||||
'ageAssurance:appealDialogOpen': {}
|
||||
'ageAssurance:appealDialogSubmit': {}
|
||||
'ageAssurance:noAccessScreen:shown': {
|
||||
accountCreatedAt: string
|
||||
isAARegion: boolean
|
||||
hasDeclaredAge: boolean
|
||||
canUpdateBirthday: boolean
|
||||
}
|
||||
'ageAssurance:noAccessScreen:openBirthdateDialog': {}
|
||||
|
||||
/*
|
||||
* Specifically for the `BlockedGeoOverlay`
|
||||
*/
|
||||
'blockedGeoOverlay:shown': {}
|
||||
|
||||
'geo:debug': {}
|
||||
|
||||
/*
|
||||
* Find Contacts stuff
|
||||
*/
|
||||
|
||||
// user presses the button on the new feature NUX
|
||||
'contacts:nux:ctaPressed': {}
|
||||
// user presses the banner NUX
|
||||
'contacts:nux:bannerPressed': {}
|
||||
// user dismisses the banner
|
||||
'contacts:nux:bannerDismissed': {}
|
||||
|
||||
// user lands on the contacts step
|
||||
'onboarding:contacts:presented': {}
|
||||
// user pressed "Import Contacts" button to begin flow
|
||||
'onboarding:contacts:begin': {}
|
||||
// skips the step entirely
|
||||
'onboarding:contacts:skipPressed': {}
|
||||
// user shared their contacts
|
||||
'onboarding:contacts:contactsShared': {}
|
||||
// user leaves the matches page
|
||||
'onboarding:contacts:nextPressed': {
|
||||
matchCount: number
|
||||
followCount: number
|
||||
dismissedMatchCount: number
|
||||
}
|
||||
|
||||
// user entered a number
|
||||
'contacts:phone:phoneEntered': {
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user entered the correct one-time-code
|
||||
'contacts:phone:phoneVerified': {
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user responded to the contacts permission prompt
|
||||
'contacts:permission:request': {
|
||||
status: 'granted' | 'denied'
|
||||
accessLevelIOS?: 'all' | 'limited' | 'none'
|
||||
}
|
||||
// contacts were successfully imported and matched
|
||||
'contacts:import:success': {
|
||||
contactCount: number
|
||||
matchCount: number
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// contacts import failed
|
||||
'contacts:import:failure': {
|
||||
reason: 'noValidNumbers' | 'networkError' | 'unknown'
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user followed a single match
|
||||
'contacts:matches:follow': {
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user pressed "Follow All" on matches
|
||||
'contacts:matches:followAll': {
|
||||
followCount: number
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user dismissed a match
|
||||
'contacts:matches:dismiss': {
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user pressed invite to send an SMS to a non-match
|
||||
'contacts:matches:invite': {
|
||||
entryPoint: 'Onboarding' | 'Standalone'
|
||||
}
|
||||
// user opened the Find Contacts settings screen
|
||||
'contacts:settings:presented': {
|
||||
hasPreviouslySynced: boolean
|
||||
matchCount?: number
|
||||
}
|
||||
// user followed a single match from settings
|
||||
'contacts:settings:follow': {}
|
||||
// user pressed "Follow All" from settings
|
||||
'contacts:settings:followAll': {
|
||||
followCount: number
|
||||
}
|
||||
// user dismissed a match from settings
|
||||
'contacts:settings:dismiss': {}
|
||||
// user re-entered the flow via the resync button
|
||||
'contacts:settings:resync': {
|
||||
daysSinceLastSync: number
|
||||
}
|
||||
// user pressed the remove all data button
|
||||
'contacts:settings:removeData': {}
|
||||
|
||||
'liveEvents:feedBanner:seen': {
|
||||
feed: string
|
||||
context: LiveEventFeedMetricContext
|
||||
}
|
||||
'liveEvents:feedBanner:click': {
|
||||
feed: string
|
||||
context: LiveEventFeedMetricContext
|
||||
}
|
||||
'liveEvents:feedBanner:hide': {
|
||||
feed: string
|
||||
context: LiveEventFeedMetricContext
|
||||
}
|
||||
'liveEvents:feedBanner:unhide': {
|
||||
feed: string
|
||||
context: LiveEventFeedMetricContext
|
||||
}
|
||||
'liveEvents:hideAllFeedBanners': {
|
||||
context: LiveEventFeedMetricContext
|
||||
}
|
||||
'liveEvents:unhideAllFeedBanners': {
|
||||
context: LiveEventFeedMetricContext
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function toClout(n: number | null | undefined): number | undefined {
|
||||
if (n == null) {
|
||||
return undefined
|
||||
} else {
|
||||
return Math.max(0, Math.round(Math.log(n)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* This is used for our own Bluesky post embeds, and maybe other things.
|
||||
*
|
||||
* In the case of our embeds, `ref_src=embed`. Not sure if `ref_url` is used.
|
||||
*/
|
||||
|
||||
import * as env from '#/env'
|
||||
|
||||
let refSrc = ''
|
||||
let refUrl = ''
|
||||
if (env.IS_WEB) {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
refSrc = params.get('ref_src') ?? ''
|
||||
refUrl = decodeURIComponent(params.get('ref_url') ?? '')
|
||||
}
|
||||
|
||||
export const src = refSrc
|
||||
export const url = refUrl
|
||||
@@ -0,0 +1,50 @@
|
||||
import {useMemo} from 'react'
|
||||
|
||||
import {BSKY_SERVICE} from '#/lib/constants'
|
||||
import {type SessionAccount} from '#/state/session'
|
||||
import {
|
||||
type MergeableMetadata,
|
||||
type Metadata,
|
||||
type SessionMetadata,
|
||||
} from '#/analytics/metadata'
|
||||
|
||||
/**
|
||||
* Thin `useMemo` wrapper that marks the metadata as memoized and provides a
|
||||
* type guard.
|
||||
*/
|
||||
export function useMeta(metadata?: MergeableMetadata) {
|
||||
const m = useMemo(() => metadata, [metadata])
|
||||
if (!m) return
|
||||
// @ts-ignore
|
||||
m.__meta = true
|
||||
return m
|
||||
}
|
||||
|
||||
export function accountToSessionMetadata(
|
||||
account: SessionAccount | undefined,
|
||||
): SessionMetadata | undefined {
|
||||
if (!account) {
|
||||
return
|
||||
} else {
|
||||
return {
|
||||
did: account.did,
|
||||
isBskyPds: account.service.startsWith(BSKY_SERVICE),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getMetadataForLogger({
|
||||
base,
|
||||
geolocation,
|
||||
session,
|
||||
}: Metadata): Record<string, any> {
|
||||
return {
|
||||
deviceId: base.deviceId,
|
||||
sessionId: base.sessionId,
|
||||
platform: base.platform,
|
||||
appVersion: base.appVersion,
|
||||
countryCode: geolocation.countryCode,
|
||||
regionCode: geolocation.regionCode,
|
||||
isBskyPds: session?.isBskyPds || 'anonymous',
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user