This commit is contained in:
Hailey
2024-07-31 00:32:01 -07:00
parent 755f4a5890
commit a8cde82afc
2 changed files with 58 additions and 67 deletions
+48 -45
View File
@@ -33,7 +33,18 @@ export async function createAgentAndResume(
event: AtpSessionEvent, event: AtpSessionEvent,
) => void, ) => void,
) { ) {
const agent = new BskyAgent({service: storedAccount.service}) const agent = new BskyAgent({
service: storedAccount.service,
persistSession: event => {
const {session} = agent
if (!session?.did) return // @TODO SESSION - ?
onSessionChange(agent, session.did, event)
if (event !== 'create' && event !== 'update') {
addSessionErrorLog(session.did, event)
}
},
})
if (storedAccount.pdsUrl) { if (storedAccount.pdsUrl) {
agent.sessionManager.pdsUrl = new URL(storedAccount.pdsUrl) agent.sessionManager.pdsUrl = new URL(storedAccount.pdsUrl)
} }
@@ -43,10 +54,9 @@ export async function createAgentAndResume(
if (isSessionExpired(storedAccount)) { if (isSessionExpired(storedAccount)) {
await networkRetry(1, () => agent.resumeSession(prevSession)) await networkRetry(1, () => agent.resumeSession(prevSession))
} else { } else {
agent.session = prevSession
if (!storedAccount.signupQueued) { if (!storedAccount.signupQueued) {
// Intentionally not awaited to unblock the UI: // @TODO SESSION - We were not awaiting this before. Why? And why is it now broken if we do not await?
networkRetry(3, () => agent.resumeSession(prevSession)).catch( await networkRetry(3, () => agent.resumeSession(prevSession)).catch(
(e: any) => { (e: any) => {
logger.error(`networkRetry failed to resume session`, { logger.error(`networkRetry failed to resume session`, {
status: e?.status || 'unknown', status: e?.status || 'unknown',
@@ -60,7 +70,7 @@ export async function createAgentAndResume(
} }
} }
return prepareAgent(agent, gates, moderation, onSessionChange) return prepareAgent(agent, gates, moderation)
} }
export async function createAgentAndLogin( export async function createAgentAndLogin(
@@ -81,41 +91,45 @@ export async function createAgentAndLogin(
event: AtpSessionEvent, event: AtpSessionEvent,
) => void, ) => void,
) { ) {
const agent = new BskyAgent({service}) const agent = new BskyAgent({
service,
persistSession: event => {
const {session} = agent
if (!session?.did) return // @TODO SESSION - ?
onSessionChange(agent, session.did, event)
if (event !== 'create' && event !== 'update') {
addSessionErrorLog(session.did, event)
}
},
})
await agent.login({identifier, password, authFactorToken}) await agent.login({identifier, password, authFactorToken})
const account = agentToSessionAccountOrThrow(agent) const account = agentToSessionAccountOrThrow(agent)
const gates = tryFetchGates(account.did, 'prefer-fresh-gates') const gates = tryFetchGates(account.did, 'prefer-fresh-gates')
const moderation = configureModerationForAccount(agent, account) const moderation = configureModerationForAccount(agent, account)
return prepareAgent(agent, moderation, gates, onSessionChange) return prepareAgent(agent, moderation, gates)
} }
export async function createAgentAndCreateAccount( export async function createAgentAndCreateAccount({
{ service,
service, email,
email, password,
password, handle,
handle, birthDate,
birthDate, inviteCode,
inviteCode, verificationPhone,
verificationPhone, verificationCode,
verificationCode, }: {
}: { service: string
service: string email: string
email: string password: string
password: string handle: string
handle: string birthDate: Date
birthDate: Date inviteCode?: string
inviteCode?: string verificationPhone?: string
verificationPhone?: string verificationCode?: string
verificationCode?: string }) {
},
onSessionChange: (
agent: BskyAgent,
did: string,
event: AtpSessionEvent,
) => void,
) {
const agent = new BskyAgent({service}) const agent = new BskyAgent({service})
await agent.createAccount({ await agent.createAccount({
email, email,
@@ -174,7 +188,7 @@ export async function createAgentAndCreateAccount(
logger.error(e, {context: `session: failed snoozeEmailConfirmationPrompt`}) logger.error(e, {context: `session: failed snoozeEmailConfirmationPrompt`})
} }
return prepareAgent(agent, gates, moderation, onSessionChange) return prepareAgent(agent, gates, moderation)
} }
async function prepareAgent( async function prepareAgent(
@@ -182,23 +196,12 @@ async function prepareAgent(
// Not awaited in the calling code so we can delay blocking on them. // Not awaited in the calling code so we can delay blocking on them.
gates: Promise<void>, gates: Promise<void>,
moderation: Promise<void>, moderation: Promise<void>,
onSessionChange: (
agent: BskyAgent,
did: string,
event: AtpSessionEvent,
) => void,
) { ) {
// There's nothing else left to do, so block on them here. // There's nothing else left to do, so block on them here.
await Promise.all([gates, moderation]) await Promise.all([gates, moderation])
// Now the agent is ready. // Now the agent is ready.
const account = agentToSessionAccountOrThrow(agent) const account = agentToSessionAccountOrThrow(agent)
agent.setPersistSessionHandler(event => {
onSessionChange(agent, account.did, event)
if (event !== 'create' && event !== 'update') {
addSessionErrorLog(account.did, event)
}
})
return {agent, account} return {agent, account}
} }
+10 -22
View File
@@ -14,7 +14,6 @@ import {
createAgentAndCreateAccount, createAgentAndCreateAccount,
createAgentAndLogin, createAgentAndLogin,
createAgentAndResume, createAgentAndResume,
sessionAccountToSession,
} from './agent' } from './agent'
import {getInitialState, reducer} from './reducer' import {getInitialState, reducer} from './reducer'
@@ -70,10 +69,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
const signal = cancelPendingTask() const signal = cancelPendingTask()
track('Try Create Account') track('Try Create Account')
logEvent('account:create:begin', {}) logEvent('account:create:begin', {})
const {agent, account} = await createAgentAndCreateAccount( const {agent, account} = await createAgentAndCreateAccount(params)
params,
onAgentSessionChange,
)
if (signal.aborted) { if (signal.aborted) {
return return
@@ -87,7 +83,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
logEvent('account:create:success', {}) logEvent('account:create:success', {})
addSessionDebugLog({type: 'method:end', method: 'createAccount', account}) addSessionDebugLog({type: 'method:end', method: 'createAccount', account})
}, },
[onAgentSessionChange, cancelPendingTask], [cancelPendingTask],
) )
const login = React.useCallback<SessionApiContext['login']>( const login = React.useCallback<SessionApiContext['login']>(
@@ -196,20 +192,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
const syncedAccount = synced.accounts.find( const syncedAccount = synced.accounts.find(
a => a.did === synced.currentAccount?.did, a => a.did === synced.currentAccount?.did,
) )
if (syncedAccount && syncedAccount.refreshJwt) { if (
if (syncedAccount.did !== state.currentAgentState.did) { syncedAccount &&
resumeSession(syncedAccount) syncedAccount.refreshJwt &&
} else { syncedAccount.did !== state.currentAgentState.did
const agent = state.currentAgentState.agent as BskyAgent ) {
const prevSession = agent.session resumeSession(syncedAccount)
agent.session = sessionAccountToSession(syncedAccount)
addSessionDebugLog({
type: 'agent:patch',
agent,
prevSession,
nextSession: agent.session,
})
}
} }
}) })
}, [state, resumeSession]) }, [state, resumeSession])
@@ -249,8 +237,8 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
addSessionDebugLog({type: 'agent:switch', prevAgent, nextAgent: agent}) addSessionDebugLog({type: 'agent:switch', prevAgent, nextAgent: agent})
// We never reuse agents so let's fully neutralize the previous one. // We never reuse agents so let's fully neutralize the previous one.
// This ensures it won't try to consume any refresh tokens. // This ensures it won't try to consume any refresh tokens.
prevAgent.session = undefined // prevAgent.session = undefined
prevAgent.setPersistSessionHandler(undefined) // prevAgent.setPersistSessionHandler(undefined)
} }
}, [agent]) }, [agent])