diff --git a/src/state/queries/__tests__/profile-enrichment.test.tsx b/src/state/queries/__tests__/profile-enrichment.test.tsx index e27eebf2a..38e8a1b15 100644 --- a/src/state/queries/__tests__/profile-enrichment.test.tsx +++ b/src/state/queries/__tests__/profile-enrichment.test.tsx @@ -1,11 +1,11 @@ import {QueryClient, QueryClientProvider} from '@tanstack/react-query' import {act, renderHook} from '@testing-library/react-native' -const mockFetchRecordViaSlingshot = jest.fn() +const mockFetchRecord = jest.fn() jest.mock('../microcosm-fallback', () => ({ - fetchRecordViaSlingshot: (...args: unknown[]) => - mockFetchRecordViaSlingshot(...args), + fetchRecordViaSlingshotOrNotFound: (...args: unknown[]) => + mockFetchRecord(...args), })) jest.mock('#/state/queries', () => ({PERSISTED_QUERY_ROOT: 'PERSISTED'})) @@ -15,7 +15,7 @@ import { } from '../profile-enrichment' const DID = 'did:plc:alice' -const NO_AVATAR_DID = 'did:plc:bob' +const MISSING_DID = 'did:plc:bob' const AVATAR = `https://cdn.bsky.app/img/avatar/plain/${DID}/bafyavatar@jpeg` type Author = { @@ -23,6 +23,7 @@ type Author = { handle: string displayName: string avatar?: string + labels?: {val: string}[] } type Post = {uri: string; author: Author} @@ -53,11 +54,21 @@ async function flush() { }) } +function avatarOf(queryClient: QueryClient, id: string, index = 0) { + return queryClient.getQueryData(['thread', id])![index].author.avatar +} + +function setThread(queryClient: QueryClient, id: string, posts: Post[]) { + act(() => { + queryClient.setQueryData(['thread', id], posts) + }) +} + describe('useProfileEnrichment', () => { beforeEach(() => { jest.useFakeTimers() - mockFetchRecordViaSlingshot.mockReset() - mockFetchRecordViaSlingshot.mockImplementation((uri: string) => + mockFetchRecord.mockReset() + mockFetchRecord.mockImplementation((uri: string) => Promise.resolve( uri.startsWith(`at://${DID}/`) ? { @@ -66,7 +77,7 @@ describe('useProfileEnrichment', () => { avatar: {ref: {$link: 'bafyavatar'}}, }, } - : {value: {}}, + : null, ), ) }) @@ -78,27 +89,13 @@ describe('useProfileEnrichment', () => { it('patches the avatar into data that arrives after the first repair', async () => { const queryClient = mount() - act(() => { - queryClient.setQueryData( - ['thread', 'a'], - [post('at://a', emptyAuthor(DID))], - ) - }) + setThread(queryClient, 'a', [post('at://a', emptyAuthor(DID))]) await flush() - expect( - queryClient.getQueryData(['thread', 'a'])![0].author.avatar, - ).toBe(AVATAR) + expect(avatarOf(queryClient, 'a')).toBe(AVATAR) - act(() => { - queryClient.setQueryData( - ['thread', 'b'], - [post('at://b', emptyAuthor(DID))], - ) - }) + setThread(queryClient, 'b', [post('at://b', emptyAuthor(DID))]) await flush() - expect( - queryClient.getQueryData(['thread', 'b'])![0].author.avatar, - ).toBe(AVATAR) + expect(avatarOf(queryClient, 'b')).toBe(AVATAR) act(() => { queryClient.setQueryData(['profile', DID], emptyAuthor(DID)) @@ -107,71 +104,108 @@ describe('useProfileEnrichment', () => { AVATAR, ) - expect(mockFetchRecordViaSlingshot).toHaveBeenCalledTimes(1) + expect(mockFetchRecord).toHaveBeenCalledTimes(1) }) - it('treats a profile with a display name but no avatar as incomplete', async () => { + it('patches every reference to a shared profile object', async () => { const queryClient = mount() - act(() => { - queryClient.setQueryData( - ['thread', 'a'], - [post('at://a', emptyAuthor(DID, 'Alice'))], - ) - }) + const author = emptyAuthor(DID) + setThread(queryClient, 'a', [ + post('at://a', author), + post('at://b', author), + ]) await flush() + expect(avatarOf(queryClient, 'a', 0)).toBe(AVATAR) + expect(avatarOf(queryClient, 'a', 1)).toBe(AVATAR) + + const author2 = emptyAuthor(DID) + setThread(queryClient, 'b', [ + post('at://c', author2), + post('at://d', author2), + ]) + expect(avatarOf(queryClient, 'b', 0)).toBe(AVATAR) + expect(avatarOf(queryClient, 'b', 1)).toBe(AVATAR) + }) + + it('does not fetch a profile that has a display name', async () => { + const queryClient = mount() - const author = queryClient.getQueryData(['thread', 'a'])![0].author - expect(author.avatar).toBe(AVATAR) - expect(author.displayName).toBe('Alice') + setThread(queryClient, 'a', [post('at://a', emptyAuthor(DID, 'Alice'))]) + await flush() + + expect(mockFetchRecord).not.toHaveBeenCalled() }) - it('fetches a profile without an avatar once and remembers the miss', async () => { + it('remembers a profile record that does not exist', async () => { const queryClient = mount() - act(() => { - queryClient.setQueryData( - ['thread', 'a'], - [post('at://a', emptyAuthor(NO_AVATAR_DID, 'Bob'))], - ) - }) + setThread(queryClient, 'a', [post('at://a', emptyAuthor(MISSING_DID))]) await flush() - act(() => { - queryClient.setQueryData( - ['thread', 'b'], - [post('at://b', emptyAuthor(NO_AVATAR_DID, 'Bob'))], - ) - }) + setThread(queryClient, 'b', [post('at://b', emptyAuthor(MISSING_DID))]) await flush() - expect(mockFetchRecordViaSlingshot).toHaveBeenCalledTimes(1) - expect( - queryClient.getQueryData(['thread', 'b'])![0].author.avatar, - ).toBeUndefined() + expect(mockFetchRecord).toHaveBeenCalledTimes(1) + expect(avatarOf(queryClient, 'b')).toBeUndefined() }) - it('refetches a profile after it is forgotten', async () => { + it('retries a profile after a failed fetch', async () => { + const queryClient = mount() + mockFetchRecord.mockRejectedValueOnce(new Error('ServerError')) + + setThread(queryClient, 'a', [post('at://a', emptyAuthor(DID))]) + await flush() + expect(avatarOf(queryClient, 'a')).toBeUndefined() + + setThread(queryClient, 'b', [post('at://b', emptyAuthor(DID))]) + await flush() + expect(avatarOf(queryClient, 'b')).toBe(AVATAR) + expect(mockFetchRecord).toHaveBeenCalledTimes(2) + }) + + it('never enriches a taken-down profile', async () => { + const queryClient = mount() + + const takenDown = {...emptyAuthor(DID), labels: [{val: '!takedown'}]} + setThread(queryClient, 'a', [post('at://a', takenDown)]) + await flush() + expect(mockFetchRecord).not.toHaveBeenCalled() + + setThread(queryClient, 'b', [ + post('at://b', emptyAuthor(DID)), + post('at://c', takenDown), + ]) + await flush() + expect(avatarOf(queryClient, 'b', 0)).toBe(AVATAR) + expect(avatarOf(queryClient, 'b', 1)).toBeUndefined() + }) + + it('keeps the original dataUpdatedAt', async () => { const queryClient = mount() act(() => { queryClient.setQueryData( ['thread', 'a'], [post('at://a', emptyAuthor(DID))], + {updatedAt: 1000}, ) }) await flush() + + expect(avatarOf(queryClient, 'a')).toBe(AVATAR) + expect(queryClient.getQueryState(['thread', 'a'])!.dataUpdatedAt).toBe(1000) + }) + + it('refetches a profile after it is forgotten', async () => { + const queryClient = mount() + + setThread(queryClient, 'a', [post('at://a', emptyAuthor(DID))]) + await flush() forgetProfileEnrichment(DID) - act(() => { - queryClient.setQueryData( - ['thread', 'b'], - [post('at://b', emptyAuthor(DID))], - ) - }) - expect( - queryClient.getQueryData(['thread', 'b'])![0].author.avatar, - ).toBeUndefined() + setThread(queryClient, 'b', [post('at://b', emptyAuthor(DID))]) + expect(avatarOf(queryClient, 'b')).toBeUndefined() await flush() - expect(mockFetchRecordViaSlingshot).toHaveBeenCalledTimes(2) + expect(mockFetchRecord).toHaveBeenCalledTimes(2) }) }) diff --git a/src/state/queries/microcosm-fallback.ts b/src/state/queries/microcosm-fallback.ts index 11c1778a7..73fde7a2a 100644 --- a/src/state/queries/microcosm-fallback.ts +++ b/src/state/queries/microcosm-fallback.ts @@ -59,6 +59,23 @@ export async function fetchRecordViaSlingshot( ) } +/** + * Like fetchRecordViaSlingshot, but resolves null only when the record does + * not exist and throws on any other failure. + */ +export async function fetchRecordViaSlingshotOrNotFound( + atUri: string, +): Promise { + const queryString = new URLSearchParams({at_uri: atUri}).toString() + const res = await fetch( + `${SLINGSHOT_URL}/xrpc/com.bad-example.repo.getUriRecord?${queryString}`, + ) + if (res.ok) return await res.json() + const body = (await res.json().catch(() => null)) as {error?: string} | null + if (body?.error === 'RecordNotFound') return null + throw new Error(`Slingshot getUriRecord failed: ${res.status}`) +} + /** * Resolve identity (DID/handle) via Slingshot * diff --git a/src/state/queries/profile-enrichment.ts b/src/state/queries/profile-enrichment.ts index 2b0ed258f..27e3326b9 100644 --- a/src/state/queries/profile-enrichment.ts +++ b/src/state/queries/profile-enrichment.ts @@ -7,7 +7,7 @@ import { } from '@tanstack/react-query' import {PERSISTED_QUERY_ROOT} from '#/state/queries' -import {fetchRecordViaSlingshot} from './microcosm-fallback' +import {fetchRecordViaSlingshotOrNotFound} from './microcosm-fallback' type Enrichment = { displayName: string @@ -18,16 +18,34 @@ type Enrichment = { /** * A profile is "incomplete" when the appview has the account but hasn't - * synced the profile record yet: it has no avatar. A profile that - * genuinely has none is fetched once and remembered as a miss. + * synced the profile record yet. Detection heuristics: + * - No avatar at all, AND + * - displayName is missing/empty or equals the handle (appview echoes handle + * as displayName when the profile record hasn't synced) */ function isIncompleteProfile(obj: any): boolean { if (!obj || typeof obj !== 'object') return false if (typeof obj.did !== 'string' || !obj.did.startsWith('did:')) return false if (!('handle' in obj)) return false if (obj.__enriched || obj.__fallbackMode) return false + if (isTakenDown(obj)) return false - return !obj.avatar + const hasAvatar = !!obj.avatar + const hasRealDisplayName = !!obj.displayName && obj.displayName !== obj.handle // appview echoes handle when unsynced + + // Incomplete if missing avatar AND missing a real display name + if (!hasAvatar && !hasRealDisplayName) return true + return false +} + +function isTakenDown(obj: {labels?: unknown}): boolean { + return ( + Array.isArray(obj.labels) && + obj.labels.some( + (l: {val?: string; neg?: boolean} | undefined) => + !l?.neg && (l?.val === '!takedown' || l?.val === '!suspend'), + ) + ) } /** @@ -60,11 +78,14 @@ function collectIncompleteProfileDids( } /** - * Fetch profile record from PDS via Slingshot. + * Fetch profile record from PDS via Slingshot. Resolves null when there is + * nothing to enrich with and undefined when the fetch failed. */ -async function fetchProfileEnrichment(did: string): Promise { +async function fetchProfileEnrichment( + did: string, +): Promise { try { - const record = await fetchRecordViaSlingshot( + const record = await fetchRecordViaSlingshotOrNotFound( `at://${did}/app.bsky.actor.profile/self`, ) if (!record?.value) return null @@ -82,7 +103,7 @@ async function fetchProfileEnrichment(did: string): Promise { : undefined, } } catch { - return null + return undefined } } @@ -93,13 +114,24 @@ async function fetchProfileEnrichment(did: string): Promise { function deepEnrich( data: any, enrichments: Map, - visited: WeakSet, + visited: Map, depth: number, ): [any, boolean] { if (!data || typeof data !== 'object' || depth > 12) return [data, false] - if (visited.has(data)) return [data, false] - visited.add(data) + const seen = visited.get(data) + if (seen) return seen + visited.set(data, [data, false]) + const result = deepEnrichUncached(data, enrichments, visited, depth) + visited.set(data, result) + return result +} +function deepEnrichUncached( + data: any, + enrichments: Map, + visited: Map, + depth: number, +): [any, boolean] { if (Array.isArray(data)) { let changed = false const out = data.map(item => { @@ -118,6 +150,7 @@ function deepEnrich( data.did.startsWith('did:') && 'handle' in data && !data.__enriched && + !isTakenDown(data) && enrichments.get(data.did) ) { const e = enrichments.get(data.did)! @@ -184,11 +217,13 @@ function enrichQuery( const qk = query.queryKey if (Array.isArray(qk) && qk[0] === PERSISTED_QUERY_ROOT) return - const [next, changed] = deepEnrich(data, enrichments, new WeakSet(), 0) + const [next, changed] = deepEnrich(data, enrichments, new Map(), 0) if (changed) { suppressSubscriber = true try { - queryClient.setQueryData(qk, next) + queryClient.setQueryData(qk, next, { + updatedAt: query.state.dataUpdatedAt, + }) } finally { suppressSubscriber = false } @@ -272,6 +307,7 @@ async function processBatch( for (const result of results) { if (result.status === 'fulfilled') { inFlightDids.delete(result.value.did) + if (result.value.enrichment === undefined) continue knownEnrichments.set(result.value.did, result.value.enrichment) if (result.value.enrichment) { enrichments.set(result.value.did, result.value.enrichment)