[Statsig] Make gate checks lazily (#3594)

zio/stable
dan 2024-04-18 04:39:29 +01:00 committed by GitHub
parent 086dc93a7a
commit 02becdf449
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 67 additions and 62 deletions

View File

@ -25,6 +25,7 @@ exports.create = function create(context) {
"Use useGate() from '#/lib/statsig/statsig' instead of the one on npm.", "Use useGate() from '#/lib/statsig/statsig' instead of the one on npm.",
}) })
} }
// TODO: Verify gate() call results aren't stored in variables.
}, },
} }
} }

View File

@ -31,8 +31,8 @@ async function setExtraParams() {
} }
export function useOTAUpdates() { export function useOTAUpdates() {
const shouldReceiveUpdates = const gate = useGate()
useGate('receive_updates') && isEnabled && !__DEV__ const shouldReceiveUpdates = isEnabled && !__DEV__ && gate('receive_updates')
const appState = React.useRef<AppStateStatus>('active') const appState = React.useRef<AppStateStatus>('active')
const lastMinimize = React.useRef(0) const lastMinimize = React.useRef(0)

View File

@ -2,11 +2,7 @@ import React from 'react'
import {Platform} from 'react-native' import {Platform} from 'react-native'
import {AppState, AppStateStatus} from 'react-native' import {AppState, AppStateStatus} from 'react-native'
import {sha256} from 'js-sha256' import {sha256} from 'js-sha256'
import { import {Statsig, StatsigProvider} from 'statsig-react-native-expo'
Statsig,
StatsigProvider,
useGate as useStatsigGate,
} from 'statsig-react-native-expo'
import {logger} from '#/logger' import {logger} from '#/logger'
import {isWeb} from '#/platform/detection' import {isWeb} from '#/platform/detection'
@ -98,16 +94,24 @@ export function logEvent<E extends keyof LogEvents>(
} }
} }
export function useGate(gateName: Gate): boolean { export function useGate(): (gateName: Gate) => boolean {
const {isLoading, value} = useStatsigGate(gateName) const cache = React.useRef<Map<Gate, boolean>>()
if (isLoading) { if (cache.current === undefined) {
// This should not happen because of waitForInitialization={true}. cache.current = new Map()
console.error('Did not expected isLoading to ever be true.')
} }
// This shouldn't technically be necessary but let's get a strong const gate = React.useCallback((gateName: Gate): boolean => {
// guarantee that a gate value can never change while mounted. // TODO: Replace local cache with a proper session one.
const [initialValue] = React.useState(value) const cachedValue = cache.current!.get(gateName)
return initialValue if (cachedValue !== undefined) {
return cachedValue
}
const value = Statsig.initializeCalled()
? Statsig.checkGate(gateName)
: false
cache.current!.set(gateName, value)
return value
}, [])
return gate
} }
function toStatsigUser(did: string | undefined): StatsigUser { function toStatsigUser(did: string | undefined): StatsigUser {

View File

@ -80,9 +80,7 @@ let ProfileHeaderStandard = ({
}) })
}, [track, openModal, profile]) }, [track, openModal, profile])
const autoExpandSuggestionsOnProfileFollow = useGate( const gate = useGate()
'autoexpand_suggestions_on_profile_follow',
)
const onPressFollow = () => { const onPressFollow = () => {
requireAuth(async () => { requireAuth(async () => {
try { try {
@ -96,7 +94,7 @@ let ProfileHeaderStandard = ({
)}`, )}`,
), ),
) )
if (isWeb && autoExpandSuggestionsOnProfileFollow) { if (isWeb && gate('autoexpand_suggestions_on_profile_follow')) {
setShowSuggestedFollows(true) setShowSuggestedFollows(true)
} }
} catch (e: any) { } catch (e: any) {

View File

@ -1,5 +1,6 @@
import React from 'react' import React from 'react'
import {Gate} from '#/lib/statsig/gates'
import {useGate} from '#/lib/statsig/statsig' import {useGate} from '#/lib/statsig/statsig'
import {isWeb} from '#/platform/detection' import {isWeb} from '#/platform/detection'
import * as persisted from '#/state/persisted' import * as persisted from '#/state/persisted'
@ -10,7 +11,7 @@ type SetContext = (v: string) => void
const stateContext = React.createContext<StateContext>('home') const stateContext = React.createContext<StateContext>('home')
const setContext = React.createContext<SetContext>((_: string) => {}) const setContext = React.createContext<SetContext>((_: string) => {})
function getInitialFeed(startSessionWithFollowing: boolean) { function getInitialFeed(gate: (gateName: Gate) => boolean) {
if (isWeb) { if (isWeb) {
if (window.location.pathname === '/') { if (window.location.pathname === '/') {
const params = new URLSearchParams(window.location.search) const params = new URLSearchParams(window.location.search)
@ -26,7 +27,7 @@ function getInitialFeed(startSessionWithFollowing: boolean) {
return feedFromSession return feedFromSession
} }
} }
if (!startSessionWithFollowing) { if (!gate('start_session_with_following')) {
const feedFromPersisted = persisted.get('lastSelectedHomeFeed') const feedFromPersisted = persisted.get('lastSelectedHomeFeed')
if (feedFromPersisted) { if (feedFromPersisted) {
// Fall back to the last chosen one across all tabs. // Fall back to the last chosen one across all tabs.
@ -37,10 +38,8 @@ function getInitialFeed(startSessionWithFollowing: boolean) {
} }
export function Provider({children}: React.PropsWithChildren<{}>) { export function Provider({children}: React.PropsWithChildren<{}>) {
const startSessionWithFollowing = useGate('start_session_with_following') const gate = useGate()
const [state, setState] = React.useState(() => const [state, setState] = React.useState(() => getInitialFeed(gate))
getInitialFeed(startSessionWithFollowing),
)
const saveState = React.useCallback((feed: string) => { const saveState = React.useCallback((feed: string) => {
setState(feed) setState(feed)

View File

@ -53,6 +53,7 @@ export function FeedPage({
const headerOffset = useHeaderOffset() const headerOffset = useHeaderOffset()
const scrollElRef = React.useRef<ListMethods>(null) const scrollElRef = React.useRef<ListMethods>(null)
const [hasNew, setHasNew] = React.useState(false) const [hasNew, setHasNew] = React.useState(false)
const gate = useGate()
const scrollToTop = React.useCallback(() => { const scrollToTop = React.useCallback(() => {
scrollElRef.current?.scrollToOffset({ scrollElRef.current?.scrollToOffset({
@ -105,9 +106,10 @@ export function FeedPage({
let feedPollInterval let feedPollInterval
if ( if (
useGate('disable_poll_on_discover') &&
feed === // Discover feed === // Discover
'feedgen|at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot' 'feedgen|at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot' &&
// TODO: This gate check is still too early. Move it to where the polling happens.
gate('disable_poll_on_discover')
) { ) {
feedPollInterval = undefined feedPollInterval = undefined
} else { } else {

View File

@ -48,7 +48,7 @@ function PostThreadFollowBtnLoaded({
'PostThreadItem', 'PostThreadItem',
) )
const requireAuth = useRequireAuth() const requireAuth = useRequireAuth()
const showFollowBackLabel = useGate('show_follow_back_label') const gate = useGate()
const isFollowing = !!profile.viewer?.following const isFollowing = !!profile.viewer?.following
const isFollowedBy = !!profile.viewer?.followedBy const isFollowedBy = !!profile.viewer?.followedBy
@ -140,7 +140,7 @@ function PostThreadFollowBtnLoaded({
style={[!isFollowing ? palInverted.text : pal.text, s.bold]} style={[!isFollowing ? palInverted.text : pal.text, s.bold]}
numberOfLines={1}> numberOfLines={1}>
{!isFollowing ? ( {!isFollowing ? (
showFollowBackLabel && isFollowedBy ? ( isFollowedBy && gate('show_follow_back_label') ? (
<Trans>Follow Back</Trans> <Trans>Follow Back</Trans>
) : ( ) : (
<Trans>Follow</Trans> <Trans>Follow</Trans>

View File

@ -40,8 +40,8 @@ function ListImpl<ItemT>(
const isScrolledDown = useSharedValue(false) const isScrolledDown = useSharedValue(false)
const contextScrollHandlers = useScrollHandlers() const contextScrollHandlers = useScrollHandlers()
const pal = usePalette('default') const pal = usePalette('default')
const showsVerticalScrollIndicator = const gate = useGate()
!useGate('hide_vertical_scroll_indicators') || isWeb
function handleScrolledDownChange(didScrollDown: boolean) { function handleScrolledDownChange(didScrollDown: boolean) {
onScrolledDownChange?.(didScrollDown) onScrolledDownChange?.(didScrollDown)
} }
@ -97,7 +97,9 @@ function ListImpl<ItemT>(
scrollEventThrottle={1} scrollEventThrottle={1}
style={style} style={style}
ref={ref} ref={ref}
showsVerticalScrollIndicator={showsVerticalScrollIndicator} showsVerticalScrollIndicator={
isWeb || !gate('hide_vertical_scroll_indicators')
}
/> />
) )
} }

View File

@ -10,14 +10,11 @@ export function CenteredView(props) {
} }
export function ScrollView(props) { export function ScrollView(props) {
const showsVerticalScrollIndicator = !useGate( const gate = useGate()
'hide_vertical_scroll_indicators',
)
return ( return (
<Animated.ScrollView <Animated.ScrollView
{...props} {...props}
showsVerticalScrollIndicator={showsVerticalScrollIndicator} showsVerticalScrollIndicator={!gate('hide_vertical_scroll_indicators')}
/> />
) )
} }

View File

@ -111,21 +111,20 @@ function HomeScreenReady({
}), }),
) )
const disableMinShellOnForegrounding = useGate( const gate = useGate()
'disable_min_shell_on_foregrounding',
)
React.useEffect(() => { React.useEffect(() => {
if (disableMinShellOnForegrounding) {
const listener = AppState.addEventListener('change', nextAppState => { const listener = AppState.addEventListener('change', nextAppState => {
if (nextAppState === 'active') { if (nextAppState === 'active') {
// TODO: Check if minimal shell is on before logging an exposure.
if (gate('disable_min_shell_on_foregrounding')) {
setMinimalShellMode(false) setMinimalShellMode(false)
} }
}
}) })
return () => { return () => {
listener.remove() listener.remove()
} }
} }, [setMinimalShellMode, gate])
}, [setMinimalShellMode, disableMinShellOnForegrounding])
const onPageSelected = React.useCallback( const onPageSelected = React.useCallback(
(index: number) => { (index: number) => {

View File

@ -38,8 +38,7 @@ export function ModerationBlockedAccounts({}: Props) {
const setMinimalShellMode = useSetMinimalShellMode() const setMinimalShellMode = useSetMinimalShellMode()
const {isTabletOrDesktop} = useWebMediaQueries() const {isTabletOrDesktop} = useWebMediaQueries()
const {screen} = useAnalytics() const {screen} = useAnalytics()
const showsVerticalScrollIndicator = const gate = useGate()
!useGate('hide_vertical_scroll_indicators') || isWeb
const [isPTRing, setIsPTRing] = React.useState(false) const [isPTRing, setIsPTRing] = React.useState(false)
const { const {
@ -169,7 +168,9 @@ export function ModerationBlockedAccounts({}: Props) {
)} )}
// @ts-ignore our .web version only -prf // @ts-ignore our .web version only -prf
desktopFixedHeight desktopFixedHeight
showsVerticalScrollIndicator={showsVerticalScrollIndicator} showsVerticalScrollIndicator={
isWeb || !gate('hide_vertical_scroll_indicators')
}
/> />
)} )}
</CenteredView> </CenteredView>

View File

@ -38,8 +38,8 @@ export function ModerationMutedAccounts({}: Props) {
const setMinimalShellMode = useSetMinimalShellMode() const setMinimalShellMode = useSetMinimalShellMode()
const {isTabletOrDesktop} = useWebMediaQueries() const {isTabletOrDesktop} = useWebMediaQueries()
const {screen} = useAnalytics() const {screen} = useAnalytics()
const showsVerticalScrollIndicator = const gate = useGate()
!useGate('hide_vertical_scroll_indicators') || isWeb
const [isPTRing, setIsPTRing] = React.useState(false) const [isPTRing, setIsPTRing] = React.useState(false)
const { const {
data, data,
@ -167,7 +167,9 @@ export function ModerationMutedAccounts({}: Props) {
)} )}
// @ts-ignore our .web version only -prf // @ts-ignore our .web version only -prf
desktopFixedHeight desktopFixedHeight
showsVerticalScrollIndicator={showsVerticalScrollIndicator} showsVerticalScrollIndicator={
isWeb || !gate('hide_vertical_scroll_indicators')
}
/> />
)} )}
</CenteredView> </CenteredView>

View File

@ -143,7 +143,7 @@ function ProfileScreenLoaded({
const setMinimalShellMode = useSetMinimalShellMode() const setMinimalShellMode = useSetMinimalShellMode()
const {openComposer} = useComposerControls() const {openComposer} = useComposerControls()
const {screen, track} = useAnalytics() const {screen, track} = useAnalytics()
const shouldUseScrollableHeader = useGate('new_profile_scroll_component') const gate = useGate()
const { const {
data: labelerInfo, data: labelerInfo,
error: labelerError, error: labelerError,
@ -317,7 +317,7 @@ function ProfileScreenLoaded({
// = // =
const renderHeader = React.useCallback(() => { const renderHeader = React.useCallback(() => {
if (shouldUseScrollableHeader) { if (gate('new_profile_scroll_component')) {
return ( return (
<ExpoScrollForwarderView scrollViewTag={scrollViewTag}> <ExpoScrollForwarderView scrollViewTag={scrollViewTag}>
<ProfileHeader <ProfileHeader
@ -343,7 +343,7 @@ function ProfileScreenLoaded({
) )
} }
}, [ }, [
shouldUseScrollableHeader, gate,
scrollViewTag, scrollViewTag,
profile, profile,
labelerInfo, labelerInfo,

View File

@ -210,7 +210,8 @@ function useSuggestedFollowsV2(): [
function SearchScreenSuggestedFollows() { function SearchScreenSuggestedFollows() {
const pal = usePalette('default') const pal = usePalette('default')
const useSuggestedFollows = useGate('use_new_suggestions_endpoint') const gate = useGate()
const useSuggestedFollows = gate('use_new_suggestions_endpoint')
? // Conditional hook call here is *only* OK because useGate() ? // Conditional hook call here is *only* OK because useGate()
// result won't change until a remount. // result won't change until a remount.
useSuggestedFollowsV2 useSuggestedFollowsV2
@ -406,8 +407,7 @@ export function SearchScreenInner({
const {isDesktop} = useWebMediaQueries() const {isDesktop} = useWebMediaQueries()
const [activeTab, setActiveTab] = React.useState(0) const [activeTab, setActiveTab] = React.useState(0)
const {_} = useLingui() const {_} = useLingui()
const gate = useGate()
const isNewSearch = useGate('new_search')
const onPageSelected = React.useCallback( const onPageSelected = React.useCallback(
(index: number) => { (index: number) => {
@ -420,7 +420,7 @@ export function SearchScreenInner({
const sections = React.useMemo(() => { const sections = React.useMemo(() => {
if (!query) return [] if (!query) return []
if (isNewSearch) { if (gate('new_search')) {
if (hasSession) { if (hasSession) {
return [ return [
{ {
@ -487,7 +487,7 @@ export function SearchScreenInner({
] ]
} }
} }
}, [hasSession, isNewSearch, _, query, activeTab]) }, [hasSession, gate, _, query, activeTab])
if (hasSession) { if (hasSession) {
return query ? ( return query ? (