Repository navigation
feat: Improve Bluesky API resiliency - #1956
Conversation
📝 WalkthroughWalkthroughAdds Bluesky proxy credential support and session management: new credentials config, in-memory JWT cache with refresh/create flows, credential-aware Bluesky XRPC execution with proxy-fallback using shuffled proxy accounts, and propagation of credential keys through Bluesky client and API handlers. (45 words) Changes
Sequence DiagramsequenceDiagram
participant Client as Client
participant PublicAPI as Public API (Bluesky)
participant CredMgr as Credential Manager
participant Session as Session Cache
participant ProxyPDS as Proxy PDS (Account)
Client->>PublicAPI: XRPC request
PublicAPI-->>Client: 5xx / Error or NotFound-like
alt Fallback eligible (not NotFound-like)
Client->>CredMgr: initCredentials(credentialKey)
CredMgr-->>Client: credentials available
Client->>Session: getBlueskyAccessJwt(account)
alt Cached JWT valid
Session-->>Client: accessJwt
else need tokens
Session->>ProxyPDS: refreshSession(refreshJwt) / createSession()
ProxyPDS-->>Session: accessJwt + refreshJwt
Session-->>Client: accessJwt
end
Client->>ProxyPDS: XRPC Request + Authorization: Bearer <jwt>
alt 200 OK
ProxyPDS-->>Client: Response
else 401 Unauthorized
Client->>Session: invalidateBlueskySession(account)
Client->>Session: getBlueskyAccessJwt(nextAccount)
Session-->>Client: next accessJwt
Client->>ProxyPDS: Retry with next account
ProxyPDS-->>Client: Response
end
else Not fallback eligible
Client-->>Client: Return original error / NotFound
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
test/bluesky.client-upstream.test.ts (1)
3-29: Move these provider mocks intotest/mocks/.Keeping the credential/session mocks inline here will get hard to reuse as more fallback cases are added. Extracting them into
test/mocks/will keep the Miniflare test surface consistent with the rest of the suite.As per coding guidelines,
test/**/*.{ts,tsx}: Tests should run inside Miniflare (local Cloudflare Workers simulator) via@cloudflare/vitest-pool-workersand use extensive mocks intest/mocks/.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/bluesky.client-upstream.test.ts` around lines 3 - 29, Extract the inline mocks (credMocks and sessionMocks) into separate files under test/mocks/ (e.g., test/mocks/blueskyCredentialsMock.ts and test/mocks/blueskySessionMock.ts) and export the same mock objects/functions; then replace the inline vi.mock calls in test/bluesky.client-upstream.test.ts with imports from those mock modules and use them in the vi.mock(...) calls for '../src/providers/twitter/proxy/credentials' and '../src/providers/bluesky/session' so the test reuses shared mocks across the suite while preserving the same exported symbols (initCredentials, hasBundledEncryptedCredentials, hasBlueskyProxyAccounts, getShuffledBlueskyAccounts, getBlueskyAccessJwt, invalidateBlueskySession).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/bluesky/client.ts`:
- Around line 129-130: initCredentials(credentialKey) can throw and currently
bubbles out of executeBlueskyXrpc, breaking the graceful fallback; wrap the
initCredentials(credentialKey) call in a try/catch inside executeBlueskyXrpc (or
the surrounding init block), and on error log the failure (include credentialKey
context) and continue as if proxy init failed (i.e., do not rethrow and allow
the hasBlueskyProxyAccounts() false-path to run); ensure any state set by
successful init is only applied on success so downstream logic using
hasBlueskyProxyAccounts() behaves correctly.
- Around line 63-76: The timeout is being cleared immediately after fetch,
allowing res.text()/JSON parsing to block indefinitely; keep the AbortController
timeout (variable t) active through the body read and JSON parse. Move the
clearTimeout(t) so it runs only after awaiting res.text() and any JSON.parse,
and ensure all return paths (res.ok false, JSON parse success, JSON parse
failure, and any thrown errors) clear the timeout or otherwise cancel the timer
before returning so the timer does not leak; reference the existing
variables/functions: ac, t, fetch(url, { signal: ac.signal, headers }),
res.text(), clearTimeout(t).
In `@src/providers/bluesky/session.ts`:
- Around line 45-57: The timeout is being cleared immediately after fetch()
returns, allowing a server to stall after headers; keep the abort timer active
until the response body is fully read by moving clearTimeout(t) to after await
res.text()/body parsing in createSession (and similarly in refreshSession), so
the abort signal can still cancel slow body reads; update the blocks around
fetch → await res.text() → JSON.parse(...) in createSession and refreshSession
and only clear the timeout once the body has been consumed and parsed
(preserving existing checks for res.ok and the access/refresh JWT handling).
---
Nitpick comments:
In `@test/bluesky.client-upstream.test.ts`:
- Around line 3-29: Extract the inline mocks (credMocks and sessionMocks) into
separate files under test/mocks/ (e.g., test/mocks/blueskyCredentialsMock.ts and
test/mocks/blueskySessionMock.ts) and export the same mock objects/functions;
then replace the inline vi.mock calls in test/bluesky.client-upstream.test.ts
with imports from those mock modules and use them in the vi.mock(...) calls for
'../src/providers/twitter/proxy/credentials' and
'../src/providers/bluesky/session' so the test reuses shared mocks across the
suite while preserving the same exported symbols (initCredentials,
hasBundledEncryptedCredentials, hasBlueskyProxyAccounts,
getShuffledBlueskyAccounts, getBlueskyAccessJwt, invalidateBlueskySession).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 2b5274e5-35d4-44fc-a7ab-c7f426bce2dd
📒 Files selected for processing (16)
credentials.example.jsonsrc/providers/bluesky/client.tssrc/providers/bluesky/conversation.tssrc/providers/bluesky/processor.tssrc/providers/bluesky/profile.tssrc/providers/bluesky/profileFollowers.tssrc/providers/bluesky/profileStatuses.tssrc/providers/bluesky/search.tssrc/providers/bluesky/session.tssrc/providers/bluesky/statusLikes.tssrc/providers/bluesky/statusReposts.tssrc/providers/twitter/proxy/credentials.tssrc/providers/twitter/proxy/types.tstest/bluesky.client-upstream.test.tstools/credential-tools.mjstools/stripcredentials.mjs
|
didn't read the code because GitHub is stuck on loading, LGTM |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/providers/bluesky/session.ts (1)
51-56: Validate the session payload before caching it.These are external API responses, but the code only does a bare
JSON.parse(...)+ cast. A malformed payload with truthy non-string JWT fields can still be cached here and later produce brokenAuthorizationheaders. Please gateaccessJwt/refreshJwtwith a small zod schema or explicit string checks before storing them.As per coding guidelines "Use TypeScript with Hono for routing, i18next for localization, and zod for API validation".
Also applies to: 81-86
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/session.ts` around lines 51 - 56, The parsed session payload is accepted without validating that accessJwt and refreshJwt are strings, allowing malformed truthy values to be cached; update the code in src/providers/bluesky/session.ts (the block that parses JSON and returns { accessJwt, refreshJwt, accessExpiresAtMs }) to validate the payload before returning: either add a small zod schema (e.g., schema = z.object({ accessJwt: z.string(), refreshJwt: z.string() })) and parse/throw if invalid, or perform explicit type checks (typeof j.accessJwt === 'string' && typeof j.refreshJwt === 'string') and return null on failure; apply the same validation to the second occurrence that mirrors lines 81-86 and ensure accessExpiresAtMs still uses parseJwtExpMs(j.accessJwt) fallback logic only after the JWTs are confirmed valid.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/bluesky/client.ts`:
- Around line 160-163: When attempt.status === 401, call
invalidateBlueskySession(cred) and then immediately re-acquire a fresh token via
getBlueskyAccessJwt(cred) and retry the request for that same cred exactly once
before continuing; implement logic inside the loop around the existing attempt
handling so that after invalidation you attempt the request again with the new
JWT (but ensure you only retry one extra time for that credential to avoid
infinite retries) and fall back to the existing continue behavior if the retried
request still fails.
- Around line 156-158: The current logic returns a proxy NotFound (the if using
isNotFoundError(attempt.status, attempt.body)) which can mask the original
public outage; update the handler in src/providers/bluesky/client.ts so that
when processing fallback proxy attempts you ignore/skip NotFound responses from
proxies if the original public request (e.g. variable publicAttempt or the
initial public response) already proved the record was not missing — only treat
a proxy NotFound as decisive if there was no prior public failure or if a proxy
actually succeeds; in practice change the isNotFoundError(attempt.status,
attempt.body) branch to preserve and return the original public failure unless a
proxy returns success.
---
Nitpick comments:
In `@src/providers/bluesky/session.ts`:
- Around line 51-56: The parsed session payload is accepted without validating
that accessJwt and refreshJwt are strings, allowing malformed truthy values to
be cached; update the code in src/providers/bluesky/session.ts (the block that
parses JSON and returns { accessJwt, refreshJwt, accessExpiresAtMs }) to
validate the payload before returning: either add a small zod schema (e.g.,
schema = z.object({ accessJwt: z.string(), refreshJwt: z.string() })) and
parse/throw if invalid, or perform explicit type checks (typeof j.accessJwt ===
'string' && typeof j.refreshJwt === 'string') and return null on failure; apply
the same validation to the second occurrence that mirrors lines 81-86 and ensure
accessExpiresAtMs still uses parseJwtExpMs(j.accessJwt) fallback logic only
after the JWTs are confirmed valid.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 9ed424cb-85dc-410a-96c9-b06081f05cfe
📒 Files selected for processing (2)
src/providers/bluesky/client.tssrc/providers/bluesky/session.ts
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/providers/bluesky/client.ts (1)
156-158:⚠️ Potential issue | 🟠 MajorDo not let proxy
NotFoundoverride the original public failure.At Line 156 and Line 171, returning proxy
NotFoundcan convert a transient public outage into a false 404. Skip these proxyNotFoundresponses and continue trying other proxy accounts; if none succeed, returnfirstas you already do at Line 179.Suggested fix
- if (isNotFoundError(attempt.status, attempt.body)) { - return { ok: false, status: attempt.status, body: attempt.body }; - } + if (isNotFoundError(attempt.status, attempt.body)) { + continue; + } ... - if (isNotFoundError(attempt.status, attempt.body)) { - return { ok: false, status: attempt.status, body: attempt.body }; - } + if (isNotFoundError(attempt.status, attempt.body)) { + continue; + }Also applies to: 171-173
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/client.ts` around lines 156 - 158, The current logic returns a proxy NotFound (when isNotFoundError(attempt.status, attempt.body) is true), which can mask the original public error; change the loop in the Bluesky client where attempts are iterated (referencing the attempt variable and isNotFoundError helper) so that if a proxy attempt yields NotFound you skip/continue to the next proxy account instead of returning; only if no proxy succeeds return the previously saved first failure (the first variable) as already done later. Ensure the same change is applied to both places handling attempt results (the earlier branch and the later branch that mirrors it).
🧹 Nitpick comments (1)
src/providers/bluesky/client.ts (1)
41-44: Avoid emitting a trailing?when there are no query params.Small cleanup: this can reduce cache-key variance and noisy URLs.
Suggested refactor
function buildXrpcUrl(baseUrl: string, path: string, params: BlueskyXrpcParams): string { const qs = paramsToSearchString(params); - return `${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}`; + return qs + ? `${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}` + : `${trimBaseUrl(baseUrl)}/xrpc/${path}`; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/client.ts` around lines 41 - 44, buildXrpcUrl currently always appends "?${qs}" which emits a trailing question mark when paramsToSearchString(params) returns an empty string; change buildXrpcUrl to only append the query string segment when qs is non-empty (e.g., call paramsToSearchString(params) and if it returns a truthy string, return `${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}`, otherwise return `${trimBaseUrl(baseUrl)}/xrpc/${path}`) so URLs have no trailing '?' and cache keys/noise are reduced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/providers/bluesky/client.ts`:
- Around line 156-158: The current logic returns a proxy NotFound (when
isNotFoundError(attempt.status, attempt.body) is true), which can mask the
original public error; change the loop in the Bluesky client where attempts are
iterated (referencing the attempt variable and isNotFoundError helper) so that
if a proxy attempt yields NotFound you skip/continue to the next proxy account
instead of returning; only if no proxy succeeds return the previously saved
first failure (the first variable) as already done later. Ensure the same change
is applied to both places handling attempt results (the earlier branch and the
later branch that mirrors it).
---
Nitpick comments:
In `@src/providers/bluesky/client.ts`:
- Around line 41-44: buildXrpcUrl currently always appends "?${qs}" which emits
a trailing question mark when paramsToSearchString(params) returns an empty
string; change buildXrpcUrl to only append the query string segment when qs is
non-empty (e.g., call paramsToSearchString(params) and if it returns a truthy
string, return `${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}`, otherwise return
`${trimBaseUrl(baseUrl)}/xrpc/${path}`) so URLs have no trailing '?' and cache
keys/noise are reduced.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 0ec6a9f0-0b95-41e5-a29f-b9c0ffbb2d7e
📒 Files selected for processing (1)
src/providers/bluesky/client.ts
Co-Authored-By: Kev 🐶 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/providers/bluesky/client.ts (1)
41-44: Minor: Trailing?in URL when no query params.When
paramsis empty,paramsToSearchStringreturns an empty string, resulting in URLs likehttps://api.bsky.app/xrpc/path?. Most servers handle this fine, but it's slightly unclean.♻️ Optional fix
function buildXrpcUrl(baseUrl: string, path: string, params: BlueskyXrpcParams): string { const qs = paramsToSearchString(params); - return `${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}`; + return `${trimBaseUrl(baseUrl)}/xrpc/${path}${qs ? `?${qs}` : ''}`; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/bluesky/client.ts` around lines 41 - 44, The buildXrpcUrl function can produce a trailing '?' when paramsToSearchString(params) returns an empty string; update buildXrpcUrl to only append the query string separator when qs is non-empty (e.g., compute qs = paramsToSearchString(params) and return `${trimBaseUrl(baseUrl)}/xrpc/${path}` when qs is empty, otherwise return `${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}`), referencing the buildXrpcUrl, paramsToSearchString, and trimBaseUrl symbols to locate the change.test/bluesky.client-upstream.test.ts (1)
32-39: Clear all hoisted mocks inbeforeEachfor test isolation.Only
initCredentialsandgetBlueskyAccessJwtare cleared, butinvalidateBlueskySessionand the other credential mocks retain call history between tests. As the test suite grows, this could cause flaky tests or false positives when asserting call counts.♻️ Suggested fix
beforeEach(() => { credMocks.initCredentials.mockClear(); + credMocks.hasBundledEncryptedCredentials.mockClear(); + credMocks.hasBlueskyProxyAccounts.mockClear(); + credMocks.getShuffledBlueskyAccounts.mockClear(); sessionMocks.getBlueskyAccessJwt.mockClear(); + sessionMocks.invalidateBlueskySession.mockClear(); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/bluesky.client-upstream.test.ts` around lines 32 - 39, The tests only clear credMocks.initCredentials and sessionMocks.getBlueskyAccessJwt in beforeEach, leaving other hoisted mocks (e.g., credMocks.invalidateBlueskySession and any other credential/session mock functions) with retained call history; update the setup to clear all mocks at the start of each test by calling vi.clearAllMocks() (or explicitly mockClear() the remaining mocks like credMocks.invalidateBlueskySession) in beforeEach so initCredentials, invalidateBlueskySession, getBlueskyAccessJwt, and any other hoisted mocks are reset before each test while keeping vi.restoreAllMocks() in afterEach.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/providers/bluesky/client.ts`:
- Around line 41-44: The buildXrpcUrl function can produce a trailing '?' when
paramsToSearchString(params) returns an empty string; update buildXrpcUrl to
only append the query string separator when qs is non-empty (e.g., compute qs =
paramsToSearchString(params) and return `${trimBaseUrl(baseUrl)}/xrpc/${path}`
when qs is empty, otherwise return
`${trimBaseUrl(baseUrl)}/xrpc/${path}?${qs}`), referencing the buildXrpcUrl,
paramsToSearchString, and trimBaseUrl symbols to locate the change.
In `@test/bluesky.client-upstream.test.ts`:
- Around line 32-39: The tests only clear credMocks.initCredentials and
sessionMocks.getBlueskyAccessJwt in beforeEach, leaving other hoisted mocks
(e.g., credMocks.invalidateBlueskySession and any other credential/session mock
functions) with retained call history; update the setup to clear all mocks at
the start of each test by calling vi.clearAllMocks() (or explicitly mockClear()
the remaining mocks like credMocks.invalidateBlueskySession) in beforeEach so
initCredentials, invalidateBlueskySession, getBlueskyAccessJwt, and any other
hoisted mocks are reset before each test while keeping vi.restoreAllMocks() in
afterEach.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 7d959697-1ae2-44c6-bdcd-39acbe455db1
📒 Files selected for processing (2)
src/providers/bluesky/client.tstest/bluesky.client-upstream.test.ts
Improve Bluesky API resiliency in response to a major Bluesky outage that left the public API completely inoperable.
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Tools