[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:
Eric Bailey
2026-01-22 15:33:45 -06:00
committed by GitHub
parent 8614e5e105
commit 25a1ed1209
190 changed files with 2358 additions and 1689 deletions
+24 -38
View File
@@ -13,8 +13,6 @@ import * as bcp47Match from 'bcp-47-match'
import {popularInterests, useInterestsDisplayNames} from '#/lib/interests'
import {cleanError} from '#/lib/strings/errors'
import {sanitizeHandle} from '#/lib/strings/handles'
import {logger} from '#/logger'
import {type MetricEvents} from '#/logger/metrics'
import {useLanguagePrefs} from '#/state/preferences/languages'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {RQKEY_ROOT as useActorSearchQueryKeyRoot} from '#/state/queries/actor-search'
@@ -68,6 +66,7 @@ import {Loader} from '#/components/Loader'
import * as ProfileCard from '#/components/ProfileCard'
import {SubtleHover} from '#/components/SubtleHover'
import {Text} from '#/components/Typography'
import {type Metrics, useAnalytics} from '#/analytics'
import {ExploreScreenLiveEventFeedsBanner} from '#/features/liveEvents/components/ExploreScreenLiveEventFeedsBanner'
import * as ModuleHeader from './components/ModuleHeader'
import {
@@ -124,7 +123,7 @@ type ExploreScreenItems =
bottomBorder?: boolean
searchButton?: {
label: string
metricsTag: MetricEvents['explore:module:searchButtonPress']['module']
metricsTag: Metrics['explore:module:searchButtonPress']['module']
tab: 'user' | 'profile' | 'feed'
}
}
@@ -135,7 +134,7 @@ type ExploreScreenItems =
icon: React.ComponentType<SVGIconProps>
searchButton?: {
label: string
metricsTag: MetricEvents['explore:module:searchButtonPress']['module']
metricsTag: Metrics['explore:module:searchButtonPress']['module']
tab: 'user' | 'profile' | 'feed'
}
hideDefaultTab?: boolean
@@ -213,6 +212,7 @@ export function Explore({
focusSearchInput: (tab: 'user' | 'profile' | 'feed') => void
headerHeight: number
}) {
const ax = useAnalytics()
const {_} = useLingui()
const t = useTheme()
const {data: preferences, error: preferencesError} = usePreferencesQuery()
@@ -273,9 +273,10 @@ export function Explore({
try {
await fetchNextFeedsPage()
} catch (err) {
logger.error('Failed to load more suggested follows', {message: err})
ax.logger.error('Failed to load more suggested follows', {message: err})
}
}, [
ax,
isFetchingNextFeedsPage,
hasNextFeedsPage,
feedsError,
@@ -333,9 +334,10 @@ export function Explore({
try {
await fetchNextPageFeedPreviews()
} catch (err) {
logger.error('Failed to load more feed previews', {message: err})
ax.logger.error('Failed to load more feed previews', {message: err})
}
}, [
ax,
isPendingFeedPreviews,
isFetchingNextPageFeedPreviews,
hasNextPageFeedPreviews,
@@ -492,11 +494,7 @@ export function Explore({
if (hasPressedLoadMoreFeeds && index < 6) {
continue
}
logger.metric(
'feed:suggestion:seen',
{feedUrl: item.feed.uri},
{statsig: false},
)
ax.metric('feed:suggestion:seen', {feedUrl: item.feed.uri})
}
}
if (!hasPressedLoadMoreFeeds) {
@@ -609,6 +607,7 @@ export function Explore({
return i
}, [
_,
ax,
useFullExperience,
suggestedFeeds,
preferences,
@@ -729,12 +728,7 @@ export function Explore({
<ModuleHeader.SearchButton
{...item.searchButton}
onPress={() =>
focusSearchInput(
(item.searchButton?.tab || 'user') as
| 'user'
| 'profile'
| 'feed',
)
focusSearchInput(item.searchButton?.tab || 'user')
}
/>
)}
@@ -751,12 +745,7 @@ export function Explore({
<ModuleHeader.SearchButton
{...item.searchButton}
onPress={() =>
focusSearchInput(
(item.searchButton?.tab || 'user') as
| 'user'
| 'profile'
| 'feed',
)
focusSearchInput(item.searchButton?.tab || 'user')
}
/>
)}
@@ -822,7 +811,7 @@ export function Explore({
if (!useFullExperience) {
return
}
logger.metric('feed:suggestion:press', {
ax.metric('feed:suggestion:press', {
feedUrl: item.feed.uri,
})
}}
@@ -1011,6 +1000,7 @@ export function Explore({
}
},
[
ax,
t.atoms.border_contrast_low,
t.atoms.bg_contrast_25,
t.atoms.text_contrast_medium,
@@ -1043,7 +1033,7 @@ export function Explore({
const seenProfilesRef = useRef<Set<string>>(new Set())
const onItemSeen = useCallback(
(item: ExploreScreenItems) => {
let module: MetricEvents['explore:module:seen']['module']
let module: Metrics['explore:module:seen']['module']
if (item.type === 'trendingTopics' || item.type === 'trendingVideos') {
module = item.type
} else if (item.type === 'profile') {
@@ -1054,17 +1044,13 @@ export function Explore({
const position = suggestedFollowsModule.findIndex(
i => i.type === 'profile' && i.profile.did === item.profile.did,
)
logger.metric(
'suggestedUser:seen',
{
logContext: 'Explore',
recId: item.recId,
position: position !== -1 ? position - 1 : 0, // -1 to account for header
suggestedDid: item.profile.did,
category: null,
},
{statsig: true},
)
ax.metric('suggestedUser:seen', {
logContext: 'Explore',
recId: item.recId,
position: position !== -1 ? position - 1 : 0, // -1 to account for header
suggestedDid: item.profile.did,
category: null,
})
}
} else if (item.type === 'feed') {
module = 'suggestedFeeds'
@@ -1077,10 +1063,10 @@ export function Explore({
}
if (!alreadyReportedRef.current.has(module)) {
alreadyReportedRef.current.set(module, module)
logger.metric('explore:module:seen', {module}, {statsig: false})
ax.metric('explore:module:seen', {module})
}
},
[suggestedFollowsModule],
[ax, suggestedFollowsModule],
)
return (
@@ -4,7 +4,6 @@ import {type AppBskyFeedDefs, AtUri} from '@atproto/api'
import {PressableScale} from '#/lib/custom-animations/PressableScale'
import {makeCustomFeedLink} from '#/lib/routes/links'
import {logger} from '#/logger'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, native, useTheme, type ViewStyleProp} from '#/alf'
import {Button, ButtonIcon} from '#/components/Button'
@@ -13,6 +12,7 @@ import {sizes as iconSizes} from '#/components/icons/common'
import {MagnifyingGlass_Stroke2_Corner0_Rounded as SearchIcon} from '#/components/icons/MagnifyingGlass'
import {Link} from '#/components/Link'
import {Text, type TextProps} from '#/components/Typography'
import {useAnalytics} from '#/analytics'
export function Container({
style,
@@ -126,6 +126,7 @@ export function SearchButton({
metricsTag: 'suggestedAccounts' | 'suggestedFeeds'
onPress?: () => void
}) {
const ax = useAnalytics()
return (
<Button
label={label}
@@ -135,11 +136,7 @@ export function SearchButton({
shape="round"
PressableComponent={native(PressableScale)}
onPress={() => {
logger.metric(
'explore:module:searchButtonPress',
{module: metricsTag},
{statsig: true},
)
ax.metric('explore:module:searchButtonPress', {module: metricsTag})
onPress?.()
}}
style={[
@@ -2,7 +2,6 @@ import {View} from 'react-native'
import {type AppBskyUnspeccedDefs} from '@atproto/api'
import {Trans} from '@lingui/macro'
import {logger} from '#/logger'
import {
DEFAULT_LIMIT as RECOMMENDATIONS_COUNT,
useTrendingTopics,
@@ -16,6 +15,7 @@ import {
TrendingTopicSkeleton,
} from '#/components/TrendingTopics'
import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics'
import {IS_WEB} from '#/env'
// Note: This module is not currently used and may be removed in the future.
@@ -27,6 +27,7 @@ export function ExploreRecommendations() {
function Inner() {
const t = useTheme()
const ax = useAnalytics()
const gutters = useGutters([0, 'compact'])
const {data: trending, error, isLoading} = useTrendingTopics()
const noRecs = !isLoading && !error && !trending?.suggested?.length
@@ -88,11 +89,7 @@ function Inner() {
key={topic.link}
topic={topic}
onPress={() => {
logger.metric(
'recommendedTopic:click',
{context: 'explore'},
{statsig: true},
)
ax.metric('recommendedTopic:click', {context: 'explore'})
}}>
{({hovered}) => (
<TrendingTopic
@@ -9,11 +9,11 @@ import {popularInterests, useInterestsDisplayNames} from '#/lib/interests'
import {logger} from '#/logger'
import {usePreferencesQuery} from '#/state/queries/preferences'
import {BlockDrawerGesture} from '#/view/shell/BlockDrawerGesture'
import {useTheme} from '#/alf'
import {atoms as a} from '#/alf'
import {atoms as a, useTheme} from '#/alf'
import {boostInterests, InterestTabs} from '#/components/InterestTabs'
import * as ProfileCard from '#/components/ProfileCard'
import {SubtleHover} from '#/components/SubtleHover'
import {useAnalytics} from '#/analytics'
import type * as bsky from '#/types/bsky'
export function useLoadEnoughProfiles({
@@ -62,6 +62,7 @@ export function SuggestedAccountsTabBar({
defaultTabLabel?: string
}) {
const {_} = useLingui()
const ax = useAnalytics()
const interestsDisplayNames = useInterestsDisplayNames()
const {data: preferences} = usePreferencesQuery()
const personalizedInterests = preferences?.interests?.tags
@@ -77,11 +78,7 @@ export function SuggestedAccountsTabBar({
selectedInterest || (hideDefaultTab ? interests[0] : 'all')
}
onSelectTab={tab => {
logger.metric(
'explore:suggestedAccounts:tabPressed',
{tab: tab},
{statsig: true},
)
ax.metric('explore:suggestedAccounts:tabPressed', {tab: tab})
onSelectInterest(tab === 'all' ? null : tab)
}}
interestsDisplayNames={
@@ -112,22 +109,19 @@ let SuggestedProfileCard = ({
position: number
}): React.ReactNode => {
const t = useTheme()
const ax = useAnalytics()
return (
<ProfileCard.Link
profile={profile}
style={[a.flex_1]}
onPress={() => {
logger.metric(
'suggestedUser:press',
{
logContext: 'Explore',
recId,
position,
suggestedDid: profile.did,
category: null,
},
{statsig: true},
)
ax.metric('suggestedUser:press', {
logContext: 'Explore',
recId,
position,
suggestedDid: profile.did,
category: null,
})
}}>
{s => (
<>
@@ -157,18 +151,14 @@ let SuggestedProfileCard = ({
withIcon={false}
logContext="ExploreSuggestedAccounts"
onFollow={() => {
logger.metric(
'suggestedUser:follow',
{
logContext: 'Explore',
location: 'Card',
recId,
position,
suggestedDid: profile.did,
category: null,
},
{statsig: true},
)
ax.metric('suggestedUser:follow', {
logContext: 'Explore',
location: 'Card',
recId,
position,
suggestedDid: profile.did,
category: null,
})
}}
/>
</ProfileCard.Header>
@@ -4,7 +4,6 @@ import {type AppBskyUnspeccedDefs, moderateProfile} from '@atproto/api'
import {msg, plural, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {logger} from '#/logger'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useTrendingSettings} from '#/state/preferences/trending'
import {useGetTrendsQuery} from '#/state/queries/trending/useGetTrendsQuery'
@@ -19,6 +18,7 @@ import {Trending3_Stroke2_Corner1_Rounded as TrendingIcon} from '#/components/ic
import {Link} from '#/components/Link'
import {SubtleHover} from '#/components/SubtleHover'
import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics'
const TOPIC_COUNT = 5
@@ -29,6 +29,7 @@ export function ExploreTrendingTopics() {
}
function Inner() {
const ax = useAnalytics()
const {data: trending, error, isLoading, isRefetching} = useGetTrendsQuery()
const noTopics = !isLoading && !error && !trending?.trends?.length
@@ -44,11 +45,7 @@ function Inner() {
trend={trend}
rank={index + 1}
onPress={() => {
logger.metric(
'trendingTopic:click',
{context: 'explore'},
{statsig: true},
)
ax.metric('trendingTopic:click', {context: 'explore'})
}}
/>
))}
@@ -8,7 +8,6 @@ import {useQueryClient} from '@tanstack/react-query'
import {VIDEO_FEED_URI} from '#/lib/constants'
import {makeCustomFeedLink} from '#/lib/routes/links'
import {logger} from '#/logger'
import {RQKEY, usePostFeedQuery} from '#/state/queries/post-feed'
import {BlockDrawerGesture} from '#/view/shell/BlockDrawerGesture'
import {atoms as a, tokens, useGutters, useTheme} from '#/alf'
@@ -20,6 +19,7 @@ import {
CompactVideoPostCard,
CompactVideoPostCardPlaceholder,
} from '#/components/VideoPostCard'
import {useAnalytics} from '#/analytics'
const CARD_WIDTH = 100
@@ -151,6 +151,7 @@ function VideoCards({
}) {
const t = useTheme()
const {_} = useLingui()
const ax = useAnalytics()
const items = useMemo(() => {
return data.pages
.flatMap(page => page.slices)
@@ -177,11 +178,7 @@ function VideoCards({
sourceInterstitial: 'explore',
}}
onInteract={() => {
logger.metric(
'videoCard:click',
{context: 'interstitial:explore'},
{statsig: true},
)
ax.metric('videoCard:click', {context: 'interstitial:explore'})
}}
/>
</View>