diff --git a/package.json b/package.json
index 980241c6a..00cc28070 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "blacksky.community",
- "version": "1.129.0",
+ "version": "1.130.0",
"private": true,
"packageManager": "pnpm@11.7.0",
"engines": {
diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx
index a7f700074..17e2c1ee5 100644
--- a/src/components/PostControls/PostMenu/PostMenuItems.tsx
+++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx
@@ -17,7 +17,10 @@ import {plural} from '@lingui/core/macro'
import {useLingui} from '@lingui/react/macro'
import {useNavigation} from '@react-navigation/native'
-import {getCommunitySpaceUri} from '#/lib/api/community-post'
+import {
+ getCommunitySpaceUri,
+ isPeerModLabelableUri,
+} from '#/lib/api/community-post'
import {isSpaceRecordUri} from '#/lib/api/space-uri'
import {getCurrentRoute} from '#/lib/routes/helpers'
import {makeProfileLink, postPermalink} from '#/lib/routes/links'
@@ -159,13 +162,11 @@ let PostMenuItems = ({
const rootUri = record.reply?.root?.uri || postUri
const isReply = Boolean(record.reply)
- const isCommunityPost = useMemo(
- () => new AtUri(postUri).collection === 'community.blacksky.feed.post',
- [postUri],
- )
const {data: peerModPerms} = useMyPeerModPermissions()
const canLabelPost =
- !!peerModPerms?.isPeerMod && isCommunityPost && !getCommunitySpaceUri(post)
+ !!peerModPerms?.isPeerMod &&
+ isPeerModLabelableUri(postUri) &&
+ !getCommunitySpaceUri(post)
const [isThreadMuted, muteThread, unmuteThread] = useThreadMuteMutationQueue(
post,
rootUri,
diff --git a/src/lib/api/__tests__/community-post.test.ts b/src/lib/api/__tests__/community-post.test.ts
index 775949210..546a62c68 100644
--- a/src/lib/api/__tests__/community-post.test.ts
+++ b/src/lib/api/__tests__/community-post.test.ts
@@ -1,4 +1,4 @@
-import {getCommunitySpaceUri} from '../community-post'
+import {getCommunitySpaceUri, isPeerModLabelableUri} from '../community-post'
const post = (communitySpace?: unknown) =>
({
@@ -27,3 +27,20 @@ describe(getCommunitySpaceUri, () => {
expect(getCommunitySpaceUri(post(communitySpace))).toBeUndefined()
})
})
+
+describe(isPeerModLabelableUri, () => {
+ it.each([
+ 'at://did:plc:a/app.bsky.feed.post/3k',
+ 'at://did:plc:a/community.blacksky.feed.post/3k',
+ ])('accepts %s', uri => {
+ expect(isPeerModLabelableUri(uri)).toBe(true)
+ })
+
+ it.each([
+ 'at://did:plc:a/app.bsky.feed.generator/3k',
+ 'at://did:plc:a/app.bsky.feed.repost/3k',
+ 'at://did:plc:c/space/community.blacksky.feed/main/did:plc:a/app.bsky.feed.post/3k',
+ ])('rejects %s', uri => {
+ expect(isPeerModLabelableUri(uri)).toBe(false)
+ })
+})
diff --git a/src/lib/api/community-post.ts b/src/lib/api/community-post.ts
index 4eb41154a..d6b290b41 100644
--- a/src/lib/api/community-post.ts
+++ b/src/lib/api/community-post.ts
@@ -1,6 +1,7 @@
import {
type AppBskyFeedDefs,
AppBskyFeedPost,
+ AtUri,
type BskyAgent,
jsonToLex,
} from '@atproto/api'
@@ -13,6 +14,14 @@ import * as bsky from '#/types/bsky'
export const GET_COMMUNITY_POST = 'community.blacksky.feed.getCommunityPost'
const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post'
+const PEER_MOD_LABELABLE_COLLECTIONS = [
+ 'app.bsky.feed.post',
+ COMMUNITY_POST_COLLECTION,
+]
+
+export function isPeerModLabelableUri(uri: string): boolean {
+ return PEER_MOD_LABELABLE_COLLECTIONS.includes(new AtUri(uri).collection)
+}
/**
* Whether this post is community content — the appview-stored stub, or a
diff --git a/src/state/queries/__tests__/peer-mod-label.test.tsx b/src/state/queries/__tests__/peer-mod-label.test.tsx
new file mode 100644
index 000000000..9f9b8593a
--- /dev/null
+++ b/src/state/queries/__tests__/peer-mod-label.test.tsx
@@ -0,0 +1,241 @@
+import {QueryClient, QueryClientProvider} from '@tanstack/react-query'
+import {act, renderHook, waitFor} from '@testing-library/react-native'
+
+import {
+ BLUESKY_FALLBACK_PROXY_HEADER,
+ BLUESKY_PROXY_HEADER,
+ HOME_APPVIEW_PINNED_OPTS,
+} from '#/lib/constants'
+
+const mockQueryLabels = jest.fn()
+const mockCommunityXrpc = jest.fn()
+const mockWarn = jest.fn()
+const mockAgent = {
+ com: {atproto: {label: {queryLabels: mockQueryLabels}}},
+}
+
+jest.mock('#/lib/api/community', () => ({
+ communityXrpc: (...args: unknown[]) => mockCommunityXrpc(...args),
+}))
+jest.mock('#/logger', () => ({
+ logger: {warn: (...args: unknown[]) => mockWarn(...args)},
+}))
+jest.mock('#/state/session', () => ({
+ useAgent: () => mockAgent,
+}))
+jest.mock('#/state/queries/community-feed', () => ({
+ COMMUNITY_POST_RQKEY: (uri: string) => ['community-post', uri],
+ RQKEY_ROOT: 'community-feed',
+ TIMELINE_RQKEY: () => ['community-timeline'],
+}))
+jest.mock('#/state/queries/post', () => ({
+ RQKEY: (uri: string) => ['post', uri],
+}))
+jest.mock('#/state/queries/post-feed', () => ({RQKEY_ROOT: 'post-feed'}))
+
+import {
+ useApplyLabelMutation,
+ usePostBlackskyLabelsQuery,
+ useRemoveLabelMutation,
+} from '../peer-mod-label'
+
+const URI = 'at://did:plc:author/app.bsky.feed.post/3kpost'
+const CID = 'bafyreipost'
+const INTERVAL = 750
+const REQUEST_TIMEOUT = 3000
+const ATTEMPTS = 8
+const RENDER_KEYS = [['post', URI], ['post-feed'], ['post-thread-v2']]
+
+const labelsResponse = (vals: string[]) => ({
+ data: {labels: vals.map(val => ({val, uri: URI, src: 'did:plc:mod'}))},
+})
+
+function setup() {
+ const client = new QueryClient({
+ defaultOptions: {queries: {retry: false}},
+ })
+ const invalidate = jest.spyOn(client, 'invalidateQueries')
+ const wrapper = ({children}: React.PropsWithChildren) => (
+ {children}
+ )
+ return {client, invalidate, wrapper}
+}
+
+const invalidatedKeys = (invalidate: jest.SpyInstance) =>
+ invalidate.mock.calls.map(
+ ([filters]: [{queryKey?: unknown}]) => filters.queryKey,
+ )
+
+const expectRenderCachesInvalidated = (
+ invalidate: jest.SpyInstance,
+ times: number,
+) => {
+ for (const key of RENDER_KEYS) {
+ expect(
+ invalidatedKeys(invalidate).filter(
+ k => JSON.stringify(k) === JSON.stringify(key),
+ ),
+ ).toHaveLength(times)
+ }
+}
+
+async function applyLabel(
+ wrapper: React.ComponentType,
+) {
+ const {result} = renderHook(() => useApplyLabelMutation(), {wrapper})
+ let pollsWhenResolved = -1
+ await act(async () => {
+ await result.current.mutateAsync({
+ subjectUri: URI,
+ subjectCid: CID,
+ val: 'porn',
+ })
+ pollsWhenResolved = mockQueryLabels.mock.calls.length
+ })
+ return {result, pollsWhenResolved}
+}
+
+describe('peer-mod label reconciliation', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ jest.clearAllMocks()
+ mockCommunityXrpc.mockResolvedValue({ok: true})
+ BLUESKY_PROXY_HEADER.set(BLUESKY_FALLBACK_PROXY_HEADER)
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('refreshes the render caches once the appview reports the label', async () => {
+ const {invalidate, wrapper} = setup()
+ mockQueryLabels
+ .mockResolvedValueOnce(labelsResponse([]))
+ .mockResolvedValueOnce(labelsResponse(['porn']))
+
+ const {pollsWhenResolved} = await applyLabel(wrapper)
+
+ expect(pollsWhenResolved).toBeLessThanOrEqual(1)
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(0)
+ })
+ expect(mockQueryLabels).toHaveBeenCalledTimes(1)
+ expectRenderCachesInvalidated(invalidate, 0)
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(INTERVAL)
+ })
+
+ expect(mockQueryLabels).toHaveBeenCalledTimes(2)
+ expectRenderCachesInvalidated(invalidate, 1)
+ expect(mockWarn).not.toHaveBeenCalled()
+ })
+
+ it('pins every label lookup to the home appview while fallback is active', async () => {
+ const {wrapper} = setup()
+ mockQueryLabels.mockResolvedValue(labelsResponse(['porn']))
+
+ const {result} = renderHook(() => usePostBlackskyLabelsQuery(URI), {
+ wrapper,
+ })
+ await waitFor(() => expect(result.current.data).toEqual(['porn']))
+ await applyLabel(wrapper)
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(0)
+ })
+
+ expect(BLUESKY_PROXY_HEADER.get()).toBe(BLUESKY_FALLBACK_PROXY_HEADER)
+ expect(mockQueryLabels.mock.calls.length).toBeGreaterThanOrEqual(2)
+ for (const [, opts] of mockQueryLabels.mock.calls as Array<
+ [unknown, {headers?: unknown}]
+ >) {
+ expect(opts.headers).toEqual(HOME_APPVIEW_PINNED_OPTS.headers)
+ }
+ })
+
+ it('gives up after the last attempt and still refreshes', async () => {
+ const {invalidate, wrapper} = setup()
+ mockQueryLabels.mockResolvedValue(labelsResponse([]))
+
+ await applyLabel(wrapper)
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(INTERVAL * ATTEMPTS)
+ })
+
+ expect(mockQueryLabels).toHaveBeenCalledTimes(ATTEMPTS)
+ expectRenderCachesInvalidated(invalidate, 1)
+ expect(mockWarn).toHaveBeenCalledWith(
+ 'peer-mod label reconcile did not converge',
+ expect.objectContaining({subjectUri: URI, val: 'porn'}),
+ )
+ })
+
+ it('survives a rejected lookup and keeps polling', async () => {
+ const {invalidate, wrapper} = setup()
+ mockQueryLabels
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValueOnce(labelsResponse(['porn']))
+
+ await applyLabel(wrapper)
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(INTERVAL)
+ })
+
+ expect(mockQueryLabels).toHaveBeenCalledTimes(2)
+ expectRenderCachesInvalidated(invalidate, 1)
+ expect(mockWarn).toHaveBeenCalledWith(
+ 'peer-mod label reconcile attempt failed',
+ expect.objectContaining({attempt: 1, message: 'boom'}),
+ )
+ })
+
+ it('times out a lookup that never settles, even one ignoring its signal', async () => {
+ const {invalidate, wrapper} = setup()
+ let stalledSignal: AbortSignal | undefined
+ mockQueryLabels
+ .mockImplementationOnce(
+ (_params: unknown, opts: {signal: AbortSignal}) => {
+ stalledSignal = opts.signal
+ return new Promise(() => {})
+ },
+ )
+ .mockResolvedValueOnce(labelsResponse(['porn']))
+
+ await applyLabel(wrapper)
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(REQUEST_TIMEOUT - 1)
+ })
+ expect(mockQueryLabels).toHaveBeenCalledTimes(1)
+ expect(stalledSignal?.aborted).toBe(false)
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(1 + INTERVAL)
+ })
+
+ expect(stalledSignal?.aborted).toBe(true)
+ expect(mockQueryLabels).toHaveBeenCalledTimes(2)
+ expectRenderCachesInvalidated(invalidate, 1)
+ expect(mockWarn).toHaveBeenCalledWith(
+ 'peer-mod label reconcile attempt failed',
+ expect.objectContaining({attempt: 1, message: 'Timed out after 3000ms'}),
+ )
+ })
+
+ it('converges on absence after a removal', async () => {
+ const {invalidate, wrapper} = setup()
+ mockQueryLabels
+ .mockResolvedValueOnce(labelsResponse(['porn']))
+ .mockResolvedValueOnce(labelsResponse([]))
+ const {result} = renderHook(() => useRemoveLabelMutation(), {wrapper})
+
+ await act(async () => {
+ await result.current.mutateAsync({subjectUri: URI, val: 'porn'})
+ })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(INTERVAL)
+ })
+
+ expect(mockQueryLabels).toHaveBeenCalledTimes(2)
+ expectRenderCachesInvalidated(invalidate, 1)
+ })
+})
diff --git a/src/state/queries/peer-mod-label.ts b/src/state/queries/peer-mod-label.ts
index a9255cc07..ad62bdd53 100644
--- a/src/state/queries/peer-mod-label.ts
+++ b/src/state/queries/peer-mod-label.ts
@@ -1,12 +1,23 @@
-import {useCallback} from 'react'
-import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
+import {type BskyAgent} from '@atproto/api'
+import {
+ type QueryClient,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query'
import {communityXrpc} from '#/lib/api/community'
+import {timeout} from '#/lib/async/timeout'
+import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants'
+import {logger} from '#/logger'
import {
COMMUNITY_POST_RQKEY,
RQKEY_ROOT as COMMUNITY_FEED_RQKEY_ROOT,
TIMELINE_RQKEY,
} from '#/state/queries/community-feed'
+import {RQKEY as postRQKey} from '#/state/queries/post'
+import {RQKEY_ROOT as POST_FEED_RQKEY_ROOT} from '#/state/queries/post-feed'
+import {postThreadQueryKeyRoot} from '#/state/queries/usePostThread/types'
import {useAgent} from '#/state/session'
import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities'
@@ -14,6 +25,10 @@ const APPLY_METHOD = 'community.blacksky.moderation.applyLabel'
const REMOVE_METHOD = 'community.blacksky.moderation.removeLabel'
const GET_MY_LABELS_METHOD = 'community.blacksky.moderation.getMyLabels'
+const RECONCILE_ATTEMPTS = 8
+const RECONCILE_INTERVAL_MS = 750
+const RECONCILE_REQUEST_TIMEOUT_MS = 3000
+
export type ApplyLabelInput = {
subjectUri: string
subjectCid: string
@@ -81,18 +96,97 @@ export function usePostBlackskyLabelsQuery(subjectUri: string | undefined) {
enabled: !!subjectUri,
queryFn: async () => {
if (!subjectUri) return []
- const res = await agent.com.atproto.label.queryLabels({
- uriPatterns: [subjectUri],
- sources: [BLACKSKY_LABELER],
- })
- return res.data.labels.filter(l => !l.neg).map(l => l.val)
+ return fetchBlackskyLabelVals(agent, subjectUri)
},
})
}
+async function fetchBlackskyLabelVals(
+ agent: BskyAgent,
+ subjectUri: string,
+ signal?: AbortSignal,
+): Promise {
+ const res = await agent.com.atproto.label.queryLabels(
+ {uriPatterns: [subjectUri], sources: [BLACKSKY_LABELER]},
+ {...HOME_APPVIEW_PINNED_OPTS, signal},
+ )
+ return res.data.labels.filter(l => !l.neg).map(l => l.val)
+}
+
+function withDeadline(
+ run: (signal: AbortSignal) => Promise,
+ ms: number,
+): Promise {
+ const controller = new AbortController()
+ let timer: ReturnType | undefined
+ const deadline = new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ controller.abort()
+ reject(new Error(`Timed out after ${ms}ms`))
+ }, ms)
+ })
+ return Promise.race([run(controller.signal), deadline]).finally(() =>
+ clearTimeout(timer),
+ )
+}
+
+/**
+ * Ozone accepting a label event does not mean the appview has ingested it
+ * yet, so the caches that render this post are refreshed once the appview
+ * reports the expected state, or after a bounded wait.
+ */
+export async function reconcileLabelState({
+ agent,
+ queryClient,
+ subjectUri,
+ val,
+ expectPresent,
+}: {
+ agent: BskyAgent
+ queryClient: QueryClient
+ subjectUri: string
+ val: string
+ expectPresent: boolean
+}): Promise {
+ let converged = false
+ try {
+ for (let attempt = 1; attempt <= RECONCILE_ATTEMPTS; attempt++) {
+ try {
+ const vals = await withDeadline(
+ signal => fetchBlackskyLabelVals(agent, subjectUri, signal),
+ RECONCILE_REQUEST_TIMEOUT_MS,
+ )
+ if (vals.includes(val) === expectPresent) {
+ converged = true
+ break
+ }
+ } catch (e) {
+ logger.warn('peer-mod label reconcile attempt failed', {
+ attempt,
+ subjectUri,
+ val,
+ message: e instanceof Error ? e.message : String(e),
+ })
+ }
+ if (attempt < RECONCILE_ATTEMPTS) {
+ await timeout(RECONCILE_INTERVAL_MS)
+ }
+ }
+ } finally {
+ if (!converged) {
+ logger.warn('peer-mod label reconcile did not converge', {
+ subjectUri,
+ val,
+ expectPresent,
+ })
+ }
+ invalidateLabelState(queryClient, subjectUri)
+ }
+}
+
export function useApplyLabelMutation() {
const agent = useAgent()
- const invalidate = useInvalidateLabelState()
+ const queryClient = useQueryClient()
return useMutation({
mutationFn: async input => {
const res = await communityXrpc(agent, APPLY_METHOD, {body: input})
@@ -101,14 +195,20 @@ export function useApplyLabelMutation() {
}
},
onSuccess: (_data, input) => {
- invalidate(input.subjectUri)
+ void reconcileLabelState({
+ agent,
+ queryClient,
+ subjectUri: input.subjectUri,
+ val: input.val,
+ expectPresent: true,
+ })
},
})
}
export function useRemoveLabelMutation() {
const agent = useAgent()
- const invalidate = useInvalidateLabelState()
+ const queryClient = useQueryClient()
return useMutation({
mutationFn: async input => {
const res = await communityXrpc(agent, REMOVE_METHOD, {body: input})
@@ -117,27 +217,28 @@ export function useRemoveLabelMutation() {
}
},
onSuccess: (_data, input) => {
- invalidate(input.subjectUri)
+ void reconcileLabelState({
+ agent,
+ queryClient,
+ subjectUri: input.subjectUri,
+ val: input.val,
+ expectPresent: false,
+ })
},
})
}
-function useInvalidateLabelState() {
- const queryClient = useQueryClient()
- return useCallback(
- (subjectUri: string) => {
- void queryClient.invalidateQueries({queryKey: myLabelsRQKey(subjectUri)})
- void queryClient.invalidateQueries({
- queryKey: postLabelsRQKey(subjectUri),
- })
- void queryClient.invalidateQueries({
- queryKey: COMMUNITY_POST_RQKEY(subjectUri),
- })
- void queryClient.invalidateQueries({queryKey: TIMELINE_RQKEY()})
- void queryClient.invalidateQueries({
- queryKey: [COMMUNITY_FEED_RQKEY_ROOT],
- })
- },
- [queryClient],
- )
+function invalidateLabelState(queryClient: QueryClient, subjectUri: string) {
+ for (const queryKey of [
+ myLabelsRQKey(subjectUri),
+ postLabelsRQKey(subjectUri),
+ COMMUNITY_POST_RQKEY(subjectUri),
+ postRQKey(subjectUri),
+ TIMELINE_RQKEY(),
+ [COMMUNITY_FEED_RQKEY_ROOT],
+ [POST_FEED_RQKEY_ROOT],
+ [postThreadQueryKeyRoot],
+ ]) {
+ void queryClient.invalidateQueries({queryKey})
+ }
}