Skip to content

Commit 672aef4

Browse files
committed
fix pds credential manager cache (KAR-393)
1 parent 2fbd0a6 commit 672aef4

1 file changed

Lines changed: 35 additions & 5 deletions

File tree

src/labeler/declare-labeler.ts

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,14 @@ const DEFAULT_DECLARE_OPTIONS: Required<Pick<DeclareLabelerOptions, 'subjectType
2525
subjectCollections: [PROFILE_COLLECTION, ORGANIZATION_COLLECTION],
2626
}
2727

28-
let xrpc: Client | undefined
29-
let credentialManager: CredentialManager | undefined
28+
const DEFAULT_PDS = 'https://bsky.social'
29+
30+
type CachedLoginAgent = {
31+
credentialManager: CredentialManager
32+
xrpc: Client
33+
}
34+
35+
const loginAgentCache = new Map<string, CachedLoginAgent>()
3036

3137
type XrpcAgent = {
3238
get: (name: string, options?: unknown) => Promise<{ data?: { value?: unknown } }>
@@ -43,8 +49,8 @@ type XrpcPostResponse = {
4349
}
4450

4551
async function loginAgent({ pds, ...credentials }: LoginCredentials) {
46-
credentialManager ??= new CredentialManager({ service: pds || 'https://bsky.social' })
47-
xrpc ??= new Client({ handler: credentialManager })
52+
const normalizedPds = normalizeLoginPds(pds)
53+
const { credentialManager, xrpc } = getCachedLoginAgent(normalizedPds)
4854

4955
if (credentialManager.session && credentialsMatchSession({ pds, ...credentials }, credentialManager.session)) {
5056
return { agent: xrpc as unknown as XrpcAgent, session: credentialManager.session }
@@ -54,11 +60,35 @@ async function loginAgent({ pds, ...credentials }: LoginCredentials) {
5460
return { agent: xrpc as unknown as XrpcAgent, session }
5561
}
5662

63+
function getCachedLoginAgent(normalizedPds: string) {
64+
const cachedLoginAgent = loginAgentCache.get(normalizedPds)
65+
if (cachedLoginAgent) return cachedLoginAgent
66+
67+
const credentialManager = new CredentialManager({ service: normalizedPds })
68+
const xrpc = new Client({ handler: credentialManager })
69+
const loginAgent = { credentialManager, xrpc }
70+
71+
loginAgentCache.set(normalizedPds, loginAgent)
72+
return loginAgent
73+
}
74+
75+
function normalizePds(pds: string) {
76+
return pds.replace(/\/+$/, '')
77+
}
78+
79+
function normalizeLoginPds(pds?: string) {
80+
return normalizePds(pds || DEFAULT_PDS)
81+
}
82+
5783
function credentialsMatchSession(
5884
credentials: LoginCredentials,
5985
session: { did: string; handle: string; email?: string | null; pdsUri?: string },
6086
) {
61-
return (!!credentials.pds ? credentials.pds === session.pdsUri : true)
87+
const pdsMatches = credentials.pds === undefined
88+
? true
89+
: !!session.pdsUri && normalizeLoginPds(credentials.pds) === normalizePds(session.pdsUri)
90+
91+
return pdsMatches
6292
&& [session.did, session.handle, session.email].includes(credentials.identifier)
6393
}
6494

0 commit comments

Comments
 (0)