Pare back persisted state to clarify source of truth

This commit is contained in:
Eric Bailey
2024-04-05 14:03:50 -05:00
parent 5be41c967b
commit d0ffb90fb3
5 changed files with 107 additions and 50 deletions
+2 -2
View File
@@ -16,7 +16,6 @@ import {useQueryClient} from '@tanstack/react-query'
import {Provider as StatsigProvider} from '#/lib/statsig/statsig' import {Provider as StatsigProvider} from '#/lib/statsig/statsig'
import {init as initPersistedState} from '#/state/persisted' import {init as initPersistedState} from '#/state/persisted'
import * as persisted from '#/state/persisted'
import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs' import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs'
import {useIntentHandler} from 'lib/hooks/useIntentHandler' import {useIntentHandler} from 'lib/hooks/useIntentHandler'
import {useOTAUpdates} from 'lib/hooks/useOTAUpdates' import {useOTAUpdates} from 'lib/hooks/useOTAUpdates'
@@ -33,6 +32,7 @@ import {Provider as PrefsStateProvider} from 'state/preferences'
import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread' import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread'
import { import {
Provider as SessionProvider, Provider as SessionProvider,
readLastActiveAccount,
useSession, useSession,
useSessionApi, useSessionApi,
} from 'state/session' } from 'state/session'
@@ -66,7 +66,7 @@ function InnerApp() {
Toast.show(_(msg`Sorry! Your session expired. Please log in again.`)) Toast.show(_(msg`Sorry! Your session expired. Please log in again.`))
}) })
const account = persisted.get('session').currentAccount const account = readLastActiveAccount()
resumeSession(account) resumeSession(account)
}, [resumeSession, _]) }, [resumeSession, _])
+2 -2
View File
@@ -7,7 +7,6 @@ import {SafeAreaProvider} from 'react-native-safe-area-context'
import {Provider as StatsigProvider} from '#/lib/statsig/statsig' import {Provider as StatsigProvider} from '#/lib/statsig/statsig'
import {init as initPersistedState} from '#/state/persisted' import {init as initPersistedState} from '#/state/persisted'
import * as persisted from '#/state/persisted'
import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs' import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs'
import {useIntentHandler} from 'lib/hooks/useIntentHandler' import {useIntentHandler} from 'lib/hooks/useIntentHandler'
import {QueryProvider} from 'lib/react-query' import {QueryProvider} from 'lib/react-query'
@@ -21,6 +20,7 @@ import {Provider as PrefsStateProvider} from 'state/preferences'
import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread' import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread'
import { import {
Provider as SessionProvider, Provider as SessionProvider,
readLastActiveAccount,
useSession, useSession,
useSessionApi, useSessionApi,
} from 'state/session' } from 'state/session'
@@ -42,7 +42,7 @@ function InnerApp() {
// init // init
useEffect(() => { useEffect(() => {
const account = persisted.get('session').currentAccount const account = readLastActiveAccount()
resumeSession(account) resumeSession(account)
}, [resumeSession]) }, [resumeSession])
+11 -6
View File
@@ -1,11 +1,16 @@
import EventEmitter from 'eventemitter3' import EventEmitter from 'eventemitter3'
import {logger} from '#/logger'
import {defaults, Schema} from '#/state/persisted/schema'
import {migrate} from '#/state/persisted/legacy'
import * as store from '#/state/persisted/store'
import BroadcastChannel from '#/lib/broadcast'
export type {Schema, PersistedAccount} from '#/state/persisted/schema' import BroadcastChannel from '#/lib/broadcast'
import {logger} from '#/logger'
import {migrate} from '#/state/persisted/legacy'
import {defaults, Schema} from '#/state/persisted/schema'
import * as store from '#/state/persisted/store'
export type {
PersistedAccount,
PersistedCurrentAccount,
Schema,
} from '#/state/persisted/schema'
export {defaults} from '#/state/persisted/schema' export {defaults} from '#/state/persisted/schema'
const broadcast = new BroadcastChannel('BSKY_BROADCAST_CHANNEL') const broadcast = new BroadcastChannel('BSKY_BROADCAST_CHANNEL')
+7 -1
View File
@@ -1,4 +1,5 @@
import {z} from 'zod' import {z} from 'zod'
import {deviceLocales} from '#/platform/detection' import {deviceLocales} from '#/platform/detection'
const externalEmbedOptions = ['show', 'hide'] as const const externalEmbedOptions = ['show', 'hide'] as const
@@ -16,12 +17,17 @@ const accountSchema = z.object({
}) })
export type PersistedAccount = z.infer<typeof accountSchema> export type PersistedAccount = z.infer<typeof accountSchema>
const currentAccountSchema = z.object({
did: z.string(),
})
export type PersistedCurrentAccount = z.infer<typeof currentAccountSchema>
export const schema = z.object({ export const schema = z.object({
colorMode: z.enum(['system', 'light', 'dark']), colorMode: z.enum(['system', 'light', 'dark']),
darkTheme: z.enum(['dim', 'dark']).optional(), darkTheme: z.enum(['dim', 'dark']).optional(),
session: z.object({ session: z.object({
accounts: z.array(accountSchema), accounts: z.array(accountSchema),
currentAccount: accountSchema.optional(), currentAccount: currentAccountSchema.optional(),
}), }),
reminders: z.object({ reminders: z.object({
lastEmailConfirm: z.string().optional(), lastEmailConfirm: z.string().optional(),
+85 -39
View File
@@ -38,18 +38,24 @@ export function getAgent() {
return __globalAgent return __globalAgent
} }
;(() => {
window.__id = Math.floor(Math.random() * 100).toString(36)
console.log(`\nID ${window.__id}\n\n`)
})()
export type SessionAccount = persisted.PersistedAccount export type SessionAccount = persisted.PersistedAccount
export type StateContext = { export type StateContext = {
agent: BskyAgent currentAgent: BskyAgent
isInitialLoad: boolean isInitialLoad: boolean
isSwitchingAccounts: boolean isSwitchingAccounts: boolean
hasSession: boolean hasSession: boolean
accounts: SessionAccount[] accounts: SessionAccount[]
/** /**
* This value is derived from `BskyAgent.session` * This value is derived from `BskyAgent.session` and should contain the full
* account object persisted to storage, minus the access tokens.
*/ */
currentAccount: SessionAccount | undefined currentAccount: Omit<SessionAccount, 'accessJwt' | 'refreshJwt'> | undefined
} }
export type ApiContext = { export type ApiContext = {
@@ -100,7 +106,7 @@ export type ApiContext = {
} }
const StateContext = React.createContext<StateContext>({ const StateContext = React.createContext<StateContext>({
agent: PUBLIC_BSKY_AGENT, currentAgent: PUBLIC_BSKY_AGENT,
isInitialLoad: true, isInitialLoad: true,
isSwitchingAccounts: false, isSwitchingAccounts: false,
accounts: [], accounts: [],
@@ -135,6 +141,15 @@ function agentToSessionAccount(agent: BskyAgent): SessionAccount | undefined {
} }
} }
function agentToCurrentAccount(
agent: BskyAgent,
): StateContext['currentAccount'] {
const sessionAccount = agentToSessionAccount(agent)
delete sessionAccount?.accessJwt
delete sessionAccount?.refreshJwt
return sessionAccount
}
function sessionAccountToAgentSession( function sessionAccountToAgentSession(
account: SessionAccount, account: SessionAccount,
): BskyAgent['session'] { ): BskyAgent['session'] {
@@ -150,15 +165,16 @@ function sessionAccountToAgentSession(
export function Provider({children}: React.PropsWithChildren<{}>) { export function Provider({children}: React.PropsWithChildren<{}>) {
const isDirty = React.useRef(false) const isDirty = React.useRef(false)
const [agent, setAgent] = React.useState<BskyAgent>(PUBLIC_BSKY_AGENT) const [currentAgent, setCurrentAgent] =
React.useState<BskyAgent>(PUBLIC_BSKY_AGENT)
const [accounts, setAccounts] = React.useState<SessionAccount[]>( const [accounts, setAccounts] = React.useState<SessionAccount[]>(
persisted.get('session').accounts, persisted.get('session').accounts,
) )
const [isInitialLoad, setIsInitialLoad] = React.useState(true) const [isInitialLoad, setIsInitialLoad] = React.useState(true)
const [isSwitchingAccounts, setIsSwitchingAccounts] = React.useState(false) const [isSwitchingAccounts, setIsSwitchingAccounts] = React.useState(false)
const currentAccount = React.useMemo( const currentAccount = React.useMemo(
() => agentToSessionAccount(agent), () => agentToCurrentAccount(currentAgent),
[agent], [currentAgent],
) )
const persistNextUpdate = React.useCallback( const persistNextUpdate = React.useCallback(
@@ -180,9 +196,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
const clearCurrentAccount = React.useCallback(() => { const clearCurrentAccount = React.useCallback(() => {
logger.warn(`session: clear current account`) logger.warn(`session: clear current account`)
persistNextUpdate() persistNextUpdate()
setAgent(PUBLIC_BSKY_AGENT) setCurrentAgent(PUBLIC_BSKY_AGENT)
BskyAgent.configure({appLabelers: [BSKY_LABELER_DID]}) BskyAgent.configure({appLabelers: [BSKY_LABELER_DID]})
}, [persistNextUpdate, setAgent]) }, [persistNextUpdate, setCurrentAgent])
const persistSession = React.useCallback< const persistSession = React.useCallback<
(agent: BskyAgent) => AtpPersistSessionHandler (agent: BskyAgent) => AtpPersistSessionHandler
@@ -194,6 +210,10 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
{event}, {event},
logger.DebugContext.session, logger.DebugContext.session,
) )
console.log('PERSIST', window.__id, {
event,
refreshJwt: session?.refreshJwt?.slice(-10),
})
const expired = event === 'expired' || event === 'create-failed' const expired = event === 'expired' || event === 'create-failed'
@@ -290,7 +310,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
agent.setPersistSessionHandler(persistSession(agent)) agent.setPersistSessionHandler(persistSession(agent))
setAgent(agent) setCurrentAgent(agent)
upsertAndPersistAccount(account) upsertAndPersistAccount(account)
logger.debug(`session: created account`, {}, logger.DebugContext.session) logger.debug(`session: created account`, {}, logger.DebugContext.session)
@@ -316,7 +336,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
agent.setPersistSessionHandler(persistSession(agent)) agent.setPersistSessionHandler(persistSession(agent))
setAgent(agent) setCurrentAgent(agent)
upsertAndPersistAccount(account) upsertAndPersistAccount(account)
logger.debug(`session: logged in`, {}, logger.DebugContext.session) logger.debug(`session: logged in`, {}, logger.DebugContext.session)
@@ -386,7 +406,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
logger.DebugContext.session, logger.DebugContext.session,
) )
agent.session = prevSession agent.session = prevSession
setAgent(agent) setCurrentAgent(agent)
upsertAndPersistAccount(account) upsertAndPersistAccount(account)
} else { } else {
logger.debug( logger.debug(
@@ -397,9 +417,10 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
try { try {
// will call `persistSession` on `BskyAgent` instance above if success // will call `persistSession` on `BskyAgent` instance above if success
await networkRetry(1, () => agent.resumeSession(prevSession)) await networkRetry(1, () => agent.resumeSession(prevSession))
setAgent(agent) setCurrentAgent(agent)
} catch (e) { } catch (e) {
logger.error(`session: resumeSession failed`, {message: e}) logger.error(`session: resumeSession failed`, {message: e})
// TODO flaky connectin could cause this too
setAccounts(accounts => { setAccounts(accounts => {
return accounts.map(a => return accounts.map(a =>
a.did === account.did a.did === account.did
@@ -440,15 +461,21 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
const refreshSession = React.useCallback< const refreshSession = React.useCallback<
ApiContext['refreshSession'] ApiContext['refreshSession']
>(async () => { >(async () => {
if (!currentAccount) return const {accounts: persistedAccounts} = persisted.get('session')
await agent.resumeSession(sessionAccountToAgentSession(currentAccount)!) const selectedAccount = persistedAccounts.find(
a => a.did === currentAccount?.did,
)
if (!selectedAccount) return
await currentAgent.resumeSession(
sessionAccountToAgentSession(selectedAccount)!,
)
persistNextUpdate() persistNextUpdate()
upsertAndPersistAccount(agentToSessionAccount(agent)!) upsertAndPersistAccount(agentToSessionAccount(currentAgent)!)
setAgent(agent.clone()) setCurrentAgent(currentAgent.clone())
}, [ }, [
currentAccount, currentAccount,
agent, currentAgent,
setAgent, setCurrentAgent,
persistNextUpdate, persistNextUpdate,
upsertAndPersistAccount, upsertAndPersistAccount,
]) ])
@@ -475,7 +502,11 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
isDirty.current = false isDirty.current = false
persisted.write('session', { persisted.write('session', {
accounts, accounts,
currentAccount, currentAccount: currentAccount
? {
did: currentAccount.did,
}
: undefined,
}) })
} }
}, [accounts, currentAccount]) }, [accounts, currentAccount])
@@ -493,11 +524,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
// already persisted on other side of broadcast // already persisted on other side of broadcast
setAccounts(persistedSession.accounts) setAccounts(persistedSession.accounts)
if ( const selectedAccount = persistedSession.accounts.find(
persistedSession.currentAccount && a => a.did === persistedSession.currentAccount?.did,
persistedSession.currentAccount.refreshJwt )
) {
if (persistedSession.currentAccount?.did !== currentAccount?.did) { if (selectedAccount && selectedAccount.refreshJwt) {
if (selectedAccount?.did !== currentAccount?.did) {
logger.debug( logger.debug(
`session: persisted onUpdate, switching accounts`, `session: persisted onUpdate, switching accounts`,
{ {
@@ -506,26 +538,29 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
handle: currentAccount?.handle, handle: currentAccount?.handle,
}, },
to: { to: {
did: persistedSession.currentAccount.did, did: selectedAccount.did,
handle: persistedSession.currentAccount.handle, handle: selectedAccount.handle,
}, },
}, },
logger.DebugContext.session, logger.DebugContext.session,
) )
await initSession(persistedSession.currentAccount) await initSession(selectedAccount)
} else { } else {
logger.debug( logger.debug(
`session: persisted onUpdate, updating session`, `session: persisted onUpdate, updating session`,
{}, {},
logger.DebugContext.session, logger.DebugContext.session,
) )
agent.session = sessionAccountToAgentSession( // updates silently, all subsequent calls will use the new session
persistedSession.currentAccount, currentAgent.session = sessionAccountToAgentSession(selectedAccount)
) // replace agent to re-derive currentAccount and trigger rerender with fresh data
setAgent(agent.clone()) setCurrentAgent(currentAgent.clone())
console.log('UPDATE', window.__id, {
refreshJwt: currentAgent.session.refreshJwt.slice(-10),
})
} }
} else if (!persistedSession.currentAccount && currentAccount) { } else if (!selectedAccount && currentAccount) {
logger.debug( logger.debug(
`session: persisted onUpdate, logging out`, `session: persisted onUpdate, logging out`,
{}, {},
@@ -546,20 +581,26 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
setAccounts, setAccounts,
clearCurrentAccount, clearCurrentAccount,
initSession, initSession,
agent, currentAgent,
setAgent, setCurrentAgent,
]) ])
const stateContext = React.useMemo( const stateContext = React.useMemo(
() => ({ () => ({
agent, currentAgent,
isInitialLoad, isInitialLoad,
isSwitchingAccounts, isSwitchingAccounts,
currentAccount, currentAccount,
accounts, accounts,
hasSession: Boolean(currentAccount), hasSession: Boolean(currentAccount),
}), }),
[agent, isInitialLoad, isSwitchingAccounts, accounts, currentAccount], [
currentAgent,
isInitialLoad,
isSwitchingAccounts,
accounts,
currentAccount,
],
) )
const api = React.useMemo( const api = React.useMemo(
@@ -588,11 +629,11 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
) )
// as we migrate, continue to keep this updated // as we migrate, continue to keep this updated
__globalAgent = agent __globalAgent = currentAgent
if (IS_DEV && isWeb) { if (IS_DEV && isWeb) {
// @ts-ignore // @ts-ignore
window.agent = agent window.agent = currentAgent
} }
return ( return (
@@ -659,3 +700,8 @@ export function isSessionDeactivated(accessJwt: string | undefined) {
} }
return false return false
} }
export function readLastActiveAccount() {
const {currentAccount, accounts} = persisted.get('session')
return accounts.find(a => a.did === currentAccount?.did)
}