From e4dcfedea25ab94b7420a26ee7dd48e9c0d0c002 Mon Sep 17 00:00:00 2001 From: William K Santiago Date: Sun, 22 Nov 2026 19:28:00 -0400 Subject: [PATCH 1/2] Apply synced read status to feeds subscribed after the pull --- .../migration.sql | 8 + prisma/schema.prisma | 11 +- src/components/feed-reader.tsx | 122 +++++++- src/lib/read-sync.test.ts | 268 ++++++++++++++++++ src/lib/read-sync.ts | 164 ++++++++++- src/server/api/routers/feed.ts | 75 ++++- src/server/read-sync.test.ts | 167 ++++++++++- src/server/read-sync.ts | 15 + 8 files changed, 791 insertions(+), 39 deletions(-) create mode 100644 prisma/migrations/20261122000000_add_subscription_read_list_applied_at/migration.sql diff --git a/prisma/migrations/20261122000000_add_subscription_read_list_applied_at/migration.sql b/prisma/migrations/20261122000000_add_subscription_read_list_applied_at/migration.sql new file mode 100644 index 0000000..4ba911e --- /dev/null +++ b/prisma/migrations/20261122000000_add_subscription_read_list_applied_at/migration.sql @@ -0,0 +1,8 @@ +-- AlterTable +ALTER TABLE "Subscription" ADD COLUMN "readListAppliedAt" TIMESTAMP(3); + +-- Existing subscriptions count as covered: the pulled read list was already +-- applied to them, and applying it again could mark read items the user has +-- since marked unread on purpose. Only subscriptions created from now on start +-- out NULL and get the list applied once. +UPDATE "Subscription" SET "readListAppliedAt" = NOW(); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 970b149..c68b94d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -65,8 +65,15 @@ model Subscription { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? // Soft delete for sync tracking - - // Relations + // When the pulled read-status list (kind 30405) was first applied to this + // feed, or null while it has not been. It is kept per account, not per + // browser, so no browser applies the list again to a feed where the user + // may have marked items unread on purpose. Resubscribing a soft-deleted + // subscription is a no-op today (readstr-3ze); the fix for that should + // clear this field too, so the resubscribed feed gets the list again. + readListAppliedAt DateTime? + + // Relations feed Feed @relation(fields: [feedId], references: [id], onDelete: Cascade) category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) diff --git a/src/components/feed-reader.tsx b/src/components/feed-reader.tsx index 540a807..63d24d8 100644 --- a/src/components/feed-reader.tsx +++ b/src/components/feed-reader.tsx @@ -43,6 +43,7 @@ import { getSyncRelays, } from '@/lib/nostr-sync' import { + coverNewFeedsWithReadList, newReadSyncSession, nextReadSyncRetryDelay, publishReadStatusIfChanged, @@ -50,6 +51,7 @@ import { readSyncAllowed, READ_SYNC_PUBLISH_DELAY_MS, READ_SYNC_RETRY_MIN_MS, + type ReadListServer, withdrawReadStatus, } from '@/lib/read-sync' import type { UnsignedEvent } from 'nostr-tools' @@ -68,6 +70,15 @@ const AUTO_MARK_RETRY_FALLBACK_MS = 60_000 // Quiet period after the last mark read/unread before refetching feed data. const FEED_DATA_REFRESH_DELAY_MS = 400 +// Quiet spell before checking for feeds the pulled read list was never +// applied to. Feeds refetch in bursts (an import, a run of reads), and one +// check per burst is enough. +const READ_SYNC_COVER_DELAY_MS = 3_000 +// Every read refetches the feeds, so a refetch asks for a check at most this +// often; a subscribe, an import or a pull asks directly. This keeps an active +// reader well inside the server's budget for the check. +const READ_SYNC_COVER_REFETCH_MIN_MS = 60_000 + // The tRPC route's 429 is plain JSON, so the TRPCClientError carries no code, // but its meta keeps the raw Response and with it the Retry-After header. function autoMarkRetryDelayMs(err: unknown): number { @@ -156,6 +167,13 @@ export function FeedReader() { const readSyncRetryTimerRef = useRef | null>(null) const readSyncRetryDelayRef = useRef(READ_SYNC_RETRY_MIN_MS) const readSyncDepsRef = useRef({ canSign, npub: user?.npub, signEventOrThrow }) + // One timer serves the debounced cover check and its retry. While it is a + // retry (backoff), feeds refetches do not move it earlier. + const readSyncCoverTimerRef = useRef | null>(null) + const readSyncCoverBackoffRef = useRef(false) + // Imports in progress: each feed they subscribe refetches the feeds, and one + // cover check after the import is cheaper than one per feed. + const readSyncImportingRef = useRef(0) const [readSyncTick, setReadSyncTick] = useState(0) // Mobile responsive state @@ -267,7 +285,7 @@ export function FeedReader() { return undefined }, [organizationMode, selectedCategoryId, selectedTags]) - const { data: feedsData = [], isLoading: isFeedsLoading, isFetched: isFeedsFetched, error: feedsQueryError } = api.feed.getFeeds.useQuery( + const { data: feedsData = [], dataUpdatedAt: feedsUpdatedAt, isLoading: isFeedsLoading, isFetched: isFeedsFetched, error: feedsQueryError } = api.feed.getFeeds.useQuery( getFeedsInput, { enabled: !!user && !!user.npub, @@ -448,6 +466,7 @@ export function FeedReader() { const subscribeFeedMutation = api.feed.subscribeFeed.useMutation({ onSuccess: () => { invalidateFeedData() + scheduleReadSyncCover() setShowAddFeed(false) setFeedError('') // Auto-export after adding a feed @@ -563,6 +582,12 @@ export function FeedReader() { readSyncRetryTimerRef.current = null } + const clearReadSyncCover = () => { + if (readSyncCoverTimerRef.current) clearTimeout(readSyncCoverTimerRef.current) + readSyncCoverTimerRef.current = null + readSyncCoverBackoffRef.current = false + } + // Sync state belongs to one account. On a switch, start over so the new // account pulls before it publishes and never publishes the old one's list; // work still queued for the old account sees the session's npub and stops. @@ -578,6 +603,7 @@ export function FeedReader() { if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) readSyncTimerRef.current = null clearReadSyncRetry() + clearReadSyncCover() readSyncRetryDelayRef.current = READ_SYNC_RETRY_MIN_MS }, [user?.npub]) @@ -640,6 +666,9 @@ export function FeedReader() { if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) if (readSyncRetryTimerRef.current) clearTimeout(readSyncRetryTimerRef.current) readSyncRetryTimerRef.current = null + if (readSyncCoverTimerRef.current) clearTimeout(readSyncCoverTimerRef.current) + readSyncCoverTimerRef.current = null + readSyncCoverBackoffRef.current = false } }, []) @@ -785,6 +814,7 @@ export function FeedReader() { }) const markReadByGuidsMutation = api.feed.markReadByGuids.useMutation() + const markReadListAppliedMutation = api.feed.markReadListApplied.useMutation() const addFavoriteMutation = api.feed.addFavorite.useMutation({ onSuccess: invalidateFeedData, @@ -1239,6 +1269,70 @@ export function FeedReader() { } }, []) + // What the pull and the cover run share: the signed-in account, read + // through the ref so a run sees the current signer, and the server calls. + const readSyncAuth = () => ({ + canSign: () => readSyncDepsRef.current.canSign, + npub: () => readSyncDepsRef.current.npub, + }) + const readSyncServer = (): ReadListServer => ({ + markRead: (guids, feedIds) => markReadByGuidsMutation.mutateAsync(feedIds ? { guids, feedIds } : { guids }), + // Never from the cache: the answer changes as feeds are covered. + getUncovered: () => utils.feed.getReadSyncUncoveredFeeds.fetch(undefined, { staleTime: 0, cacheTime: 0 }), + markApplied: (feedIds) => markReadListAppliedMutation.mutateAsync({ feedIds }), + onApplied: () => { + invalidateFeedData() + void utils.feed.getCategoriesWithUnread.invalidate() + }, + }) + + // A pulled key whose feed was not subscribed yet matched nothing, so the + // list is applied to feeds subscribed since, wherever they were added (add + // feed, OPML or Nostr import, the subscription sync inside getFeeds, another + // browser). The server says which feeds are uncovered, so this needs neither + // the filtered feed list nor any state in this browser. It waits for the + // session's pull, and a pull starting cancels it, since the pull applies the + // list to every feed and checks again when it is done. + const runReadSyncCover = () => { + readSyncCoverTimerRef.current = null + readSyncCoverBackoffRef.current = false + if (!readSyncReadyRef.current) return + const session = readSyncSessionRef.current + void coverNewFeedsWithReadList({ + ...readSyncAuth(), + ...readSyncServer(), + isCancelled: () => + readSyncUnmountedRef.current || readSyncSessionRef.current !== session || readSyncPullingRef.current, + session, + }).then((retryIn) => { + if (retryIn == null || readSyncUnmountedRef.current || readSyncSessionRef.current !== session) return + const { canSign: signer, npub } = readSyncDepsRef.current + if (!readSyncAllowed(signer, npub)) return + if (readSyncCoverTimerRef.current) clearTimeout(readSyncCoverTimerRef.current) + readSyncCoverBackoffRef.current = true + readSyncCoverTimerRef.current = setTimeout(runReadSyncCover, retryIn) + }) + } + + // Before the session's pull there is nothing to check: the pull applies the + // list to every feed and schedules a check when it is done. + const scheduleReadSyncCover = (delay = READ_SYNC_COVER_DELAY_MS) => { + if (!readSyncReadyRef.current || readSyncCoverBackoffRef.current || readSyncImportingRef.current > 0) return + if (readSyncCoverTimerRef.current) clearTimeout(readSyncCoverTimerRef.current) + readSyncCoverTimerRef.current = setTimeout(runReadSyncCover, delay) + } + + // Every feeds fetch may bring a new subscription (getFeeds also syncs the + // subscription list), so it asks for a check; only its timing is used, not + // the filtered feeds it returned. + const readSyncCoverRefetchAtRef = useRef(0) + useEffect(() => { + if (!feedsUpdatedAt || feedsUpdatedAt - readSyncCoverRefetchAtRef.current < READ_SYNC_COVER_REFETCH_MIN_MS) return + readSyncCoverRefetchAtRef.current = feedsUpdatedAt + scheduleReadSyncCover() + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [feedsUpdatedAt]) + // Pull read status once per session after feeds load, and again when the // setting is turned on (readSyncTick), which then publishes once. useEffect(() => { @@ -1253,15 +1347,10 @@ export function FeedReader() { readSyncPublishAfterPullRef.current = false void pullReadStatus({ - canSign: () => readSyncDepsRef.current.canSign, - npub: () => readSyncDepsRef.current.npub, + ...readSyncAuth(), + ...readSyncServer(), isCancelled: () => readSyncUnmountedRef.current || readSyncSessionRef.current !== session, session, - markRead: (guids) => markReadByGuidsMutation.mutateAsync({ guids }), - onApplied: () => { - invalidateFeedData() - void utils.feed.getCategoriesWithUnread.invalidate() - }, }).then((pulled) => { if (readSyncSessionRef.current === session) readSyncPullingRef.current = false // A pull for an account that is no longer signed in leaves the new @@ -1292,6 +1381,7 @@ export function FeedReader() { } readSyncRetryDelayRef.current = READ_SYNC_RETRY_MIN_MS readSyncReadyRef.current = true + scheduleReadSyncCover(0) if (publishAfter || readSyncPendingRef.current) { readSyncPendingRef.current = false void publishReadSyncNow() @@ -1319,6 +1409,8 @@ export function FeedReader() { if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) readSyncTimerRef.current = null clearReadSyncRetry() + clearReadSyncCover() + readSyncSessionRef.current.coverRetryDelay = READ_SYNC_RETRY_MIN_MS readSyncPendingRef.current = false // Turning it off replaces the published list with an empty one. void withdrawReadStatus({ @@ -1330,7 +1422,19 @@ export function FeedReader() { } // Handle importing feeds from Nostr sync - const handleImportFeeds = async (feedsToImport: Array<{ type: 'RSS' | 'NOSTR'; url: string; tags?: string[]; category?: { name: string; color?: string; icon?: string } }>) => { + type ImportedFeed = { type: 'RSS' | 'NOSTR'; url: string; tags?: string[]; category?: { name: string; color?: string; icon?: string } } + const handleImportFeeds = async (feedsToImport: ImportedFeed[]) => { + readSyncImportingRef.current++ + try { + await importFeeds(feedsToImport) + } finally { + readSyncImportingRef.current-- + // Feeds imported before a failure are subscribed too, so check either way. + scheduleReadSyncCover() + } + } + + const importFeeds = async (feedsToImport: ImportedFeed[]) => { // First, create a map of category names to IDs for existing categories const categoryMap = new Map() for (const cat of categories) { diff --git a/src/lib/read-sync.test.ts b/src/lib/read-sync.test.ts index 3b85e2c..1bb4243 100644 --- a/src/lib/read-sync.test.ts +++ b/src/lib/read-sync.test.ts @@ -16,6 +16,7 @@ import { buildPublishedReadList, chunkGuidsForRequest, cleanPulledGuids, + coverNewFeedsWithReadList, MARK_READ_REQUEST_BYTES, MAX_PUBLISHED_READ_CONTENT, newReadSyncSession, @@ -23,6 +24,7 @@ import { publishReadStatusIfChanged, pullReadStatus, READ_STATUS_D_TAG, + READ_SYNC_FEED_IDS_MAX, READ_SYNC_RETRY_MAX_MS, READ_SYNC_RETRY_MIN_MS, readSyncAllowed, @@ -144,6 +146,21 @@ describe('chunkGuidsForRequest', () => { } } }) + + it('keeps a call scoped to the most and longest feed ids under the route cap too', async () => { + setReadSyncEnabled(true) + const worst = Array.from({ length: 2000 }, (_, i) => `${i}`.padEnd(MAX_GUID_LEN, '\u0001')) + const feedIds = Array.from({ length: READ_SYNC_FEED_IDS_MAX }, (_, i) => `${i}`.padEnd(64, 'x')) + const server = fakeServer(feedIds) + const session = { ...newReadSyncSession(NPUB), pulled: true, remote: worst } + await expect(coverNewFeedsWithReadList({ canSign: () => true, npub: () => NPUB, session, ...server })).resolves.toBeNull() + expect(server.markRead.mock.calls.flatMap(([part]) => part)).toEqual(worst) + for (const [part, scope] of server.markRead.mock.calls) { + expect(scope).toEqual(feedIds) + const body = JSON.stringify({ 0: superjson.serialize({ guids: part, feedIds: scope }) }) + expect(new TextEncoder().encode(body).length + 200 * 45).toBeLessThan(MAX_TRPC_BODY_BYTES) + } + }) }) describe('readStatusListSchema caps', () => { @@ -199,6 +216,8 @@ describe('pullReadStatus', () => { npub: () => NPUB, session, onApplied: vi.fn(), + getUncovered: vi.fn(async () => ({ feedIds: [] as string[], more: false })), + markApplied: vi.fn(async () => {}), }) it('does nothing when the setting is off or the user cannot sign', async () => { @@ -564,6 +583,255 @@ describe('publishReadStatusIfChanged', () => { }) }) +describe('pullReadStatus and covered feeds', () => { + const fresh = (itemGuids: string[], isFresh = true) => + vi.fn(async (): Promise => ({ success: true, found: true, data: { itemGuids }, createdAt: 100, fresh: isFresh, complete: true })) + const auth = { canSign: () => true, npub: () => NPUB } + + it('marks applied the feeds uncovered when a fresh pull starts, not ones subscribed during it', async () => { + setReadSyncEnabled(true) + const guids = Array.from({ length: 3000 }, (_, i) => `https://example.com/${'p'.repeat(40)}/${i}`) + const server = fakeServer(['old', 'new-before'], ['old']) + server.markRead.mockImplementation(async () => { + // A feed subscribed while the chunks go out misses the earlier ones. + if (!server.subscribed.includes('mid-pull')) server.subscribed.push('mid-pull') + return { marked: 0 } + }) + const session = newReadSyncSession(NPUB) + await expect(pullReadStatus({ ...auth, ...server, session, fetchRemote: fresh(guids) })).resolves.toBe(true) + // The pull applies to every feed, unscoped. + expect(server.markRead.mock.calls.map((call) => call.length)).toEqual(chunkGuidsForRequest(guids).map(() => 1)) + expect(server.markApplied).toHaveBeenCalledOnce() + expect(server.markApplied).toHaveBeenCalledWith(['new-before']) + expect([...server.applied].sort()).toEqual(['new-before', 'old']) + + // The cover run then gives the list to the feed subscribed mid-pull. + server.markRead.mockClear() + await expect(coverNewFeedsWithReadList({ ...auth, ...server, session })).resolves.toBeNull() + expect(server.markRead).toHaveBeenCalledTimes(chunkGuidsForRequest(guids, MARK_READ_REQUEST_BYTES - JSON.stringify(['mid-pull']).length).length) + expect(new Set(server.markRead.mock.calls.map(([, scope]) => JSON.stringify(scope)))).toEqual(new Set(['["mid-pull"]'])) + expect(server.applied.has('mid-pull')).toBe(true) + }) + + it('marks nothing applied for a stale event, and still applies when the snapshot fails', async () => { + setReadSyncEnabled(true) + const server = fakeServer(['f1']) + await pullReadStatus({ ...auth, ...server, session: newReadSyncSession(NPUB), fetchRemote: fresh(['a'], false) }) + expect(server.getUncovered).not.toHaveBeenCalled() + expect(server.markApplied).not.toHaveBeenCalled() + + vi.spyOn(console, 'warn').mockImplementation(() => {}) + server.getUncovered.mockRejectedValueOnce(new Error('429')) + const session = newReadSyncSession(NPUB) + await expect(pullReadStatus({ ...auth, ...server, session, fetchRemote: fresh(['a']) })).resolves.toBe(true) + expect(server.markRead).toHaveBeenCalledWith(['a']) + expect(server.markApplied).not.toHaveBeenCalled() + expect(storage.data.get(WATERMARK)).toBe('100') + }) + + it('never throws when an opts callback does', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const boom = () => { + throw new Error('boom') + } + const server = fakeServer(['f1']) + const session = newReadSyncSession(NPUB) + for (const broken of [{ isCancelled: boom }, { canSign: boom }, { npub: boom }]) { + await expect(pullReadStatus({ ...auth, ...server, session, fetchRemote: fresh(['a']), ...broken })).resolves.toBe(false) + } + }) +}) + +// The account's subscriptions as the server keeps them: which feeds are +// subscribed and which ones the read list was applied to. +function fakeServer(subscribed: string[], appliedAlready: string[] = []) { + const applied = new Set(appliedAlready) + const server = { + subscribed, + applied, + markRead: vi.fn(async (_guids: string[], _feedIds?: string[]): Promise => ({ marked: 0 })), + getUncovered: vi.fn(async () => { + const feedIds = server.subscribed.filter((feedId) => !applied.has(feedId)) + return { feedIds: feedIds.slice(0, READ_SYNC_FEED_IDS_MAX), more: feedIds.length > READ_SYNC_FEED_IDS_MAX } + }), + markApplied: vi.fn(async (feedIds: string[]) => { + for (const feedId of feedIds) if (server.subscribed.includes(feedId)) applied.add(feedId) + }), + onApplied: vi.fn(), + } + return server +} + +describe('coverNewFeedsWithReadList', () => { + const pulled = (remote: string[] | null = ['a', 'b'], npub = NPUB) => ({ ...newReadSyncSession(npub), pulled: true, remote }) + const run = (server: ReturnType, session = pulled(), extra: Record = {}) => + coverNewFeedsWithReadList({ canSign: () => true, npub: () => session.npub, session, ...server, ...extra }) + const bigList = () => Array.from({ length: 3000 }, (_, i) => `https://example.com/${'p'.repeat(40)}/${i}`) + + it('applies the list only to uncovered feeds, then marks them applied', async () => { + setReadSyncEnabled(true) + const server = fakeServer(['covered', 'f2', 'f3'], ['covered']) + await expect(run(server)).resolves.toBeNull() + expect(server.markRead).toHaveBeenCalledOnce() + expect(server.markRead).toHaveBeenCalledWith(['a', 'b'], ['f2', 'f3']) + expect(server.markApplied).toHaveBeenCalledWith(['f2', 'f3']) + expect(server.onApplied).toHaveBeenCalledOnce() + expect([...server.applied].sort()).toEqual(['covered', 'f2', 'f3']) + + // Covered now: the next check sends nothing but the one lookup. + await run(server) + expect(server.getUncovered).toHaveBeenCalledTimes(2) + expect(server.markRead).toHaveBeenCalledOnce() + expect(server.markApplied).toHaveBeenCalledOnce() + }) + + it('leaves a feed another browser covered alone, so its unreads stay unread', async () => { + setReadSyncEnabled(true) + const server = fakeServer(['old'], ['old']) + const browserX = pulled(['k']) + const browserY = pulled(['k']) + // The user subscribes F, browser Y covers it, then marks F:k unread. + server.subscribed.push('F') + await run(server, browserY) + expect(server.markRead).toHaveBeenCalledWith(['k'], ['F']) + server.markRead.mockClear() + // Browser X, which never saw F before, checks later and sends nothing. + await expect(run(server, browserX)).resolves.toBeNull() + expect(server.markRead).not.toHaveBeenCalled() + expect(server.markApplied).toHaveBeenCalledOnce() + }) + + it('marks uncovered feeds applied without sending anything when there is no list', async () => { + setReadSyncEnabled(true) + for (const remote of [null, []]) { + const server = fakeServer(['f1']) + await expect(run(server, pulled(remote))).resolves.toBeNull() + expect(server.markRead).not.toHaveBeenCalled() + expect(server.markApplied).toHaveBeenCalledWith(['f1']) + expect(server.onApplied).not.toHaveBeenCalled() + } + }) + + it('does not even look before the pull, or when sync is not allowed', async () => { + const notPulled = pulled() + notPulled.pulled = false + const cases: Array<[ReturnType, Record]> = [ + [pulled(), {}], // the setting is off + [pulled(), { canSign: () => false }], + [pulled(), { npub: () => 'npub1other' }], + [pulled(), { isCancelled: () => true }], + [notPulled, {}], + ] + for (const [i, [session, extra]] of cases.entries()) { + if (i === 1) setReadSyncEnabled(true) + const server = fakeServer(['f1']) + await expect(run(server, session, extra)).resolves.toBeNull() + expect(server.getUncovered).not.toHaveBeenCalled() + } + }) + + it('stops between steps when cancelled or the account changes, leaving the feeds uncovered', async () => { + setReadSyncEnabled(true) + const steps = ['getUncovered', 'markRead', 'markApplied'] as const + for (const step of steps) { + for (const stop of ['cancel', 'account'] as const) { + const server = fakeServer(['f1']) + const state = { cancelled: false, npub: NPUB } + const original = server[step].getMockImplementation()! + server[step].mockImplementation((async (...args: never[]) => { + const result = await (original as (...a: never[]) => Promise)(...args) + if (stop === 'cancel') state.cancelled = true + else state.npub = 'npub1other' + return result + }) as never) + const session = pulled(bigList()) + const result = await run(server, session, { isCancelled: () => state.cancelled, npub: () => state.npub }) + expect(result).toBeNull() + expect(server.onApplied).not.toHaveBeenCalled() + if (step === 'getUncovered') expect(server.markRead).not.toHaveBeenCalled() + if (step === 'markRead') { + expect(server.markRead).toHaveBeenCalledOnce() + expect(server.markApplied).not.toHaveBeenCalled() + expect(server.applied.has('f1')).toBe(false) + } + } + } + }) + + it('keeps the feeds uncovered on failure and backs off exponentially, then resets', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const server = fakeServer(['f1']) + const session = pulled() + server.markRead.mockRejectedValue(new Error('429')) + await expect(run(server, session)).resolves.toBe(READ_SYNC_RETRY_MIN_MS) + await expect(run(server, session)).resolves.toBe(READ_SYNC_RETRY_MIN_MS * 2) + await expect(run(server, session)).resolves.toBe(READ_SYNC_RETRY_MIN_MS * 4) + expect(server.applied.has('f1')).toBe(false) + expect(server.markApplied).not.toHaveBeenCalled() + + server.getUncovered.mockRejectedValueOnce(new Error('429')) + await expect(run(server, session)).resolves.toBe(READ_SYNC_RETRY_MIN_MS * 8) + server.markApplied.mockRejectedValueOnce(new Error('429')) + server.markRead.mockResolvedValue({ marked: 1 }) + await expect(run(server, session)).resolves.toBe(READ_SYNC_RETRY_MIN_MS * 16) + expect(server.applied.has('f1')).toBe(false) + + await expect(run(server, session)).resolves.toBeNull() + expect(server.applied.has('f1')).toBe(true) + expect(session.coverRetryDelay).toBe(READ_SYNC_RETRY_MIN_MS) + for (let i = 0; i < 20; i++) session.coverRetryDelay = nextReadSyncRetryDelay(session.coverRetryDelay) + expect(session.coverRetryDelay).toBe(READ_SYNC_RETRY_MAX_MS) + }) + + it('never throws when an opts callback does, and reports it as a failure', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const boom = () => { + throw new Error('boom') + } + for (const broken of [{ isCancelled: boom }, { canSign: boom }, { npub: boom }, { onApplied: boom }]) { + const session = pulled() + await expect(run(fakeServer(['f1']), session, broken)).resolves.toBe(READ_SYNC_RETRY_MIN_MS) + expect(session.covering).toBe(false) + } + }) + + it('never runs twice at once, and runs again for a feed subscribed meanwhile', async () => { + setReadSyncEnabled(true) + const server = fakeServer(['f1']) + const session = pulled() + let inFlight = 0 + let release!: () => void + server.markRead.mockImplementation(async () => { + inFlight++ + expect(inFlight).toBe(1) + if (server.markRead.mock.calls.length === 1) await new Promise((resolve) => (release = resolve)) + inFlight-- + return { marked: 1 } + }) + const first = run(server, session) + await vi.waitFor(() => expect(server.markRead).toHaveBeenCalledOnce()) + server.subscribed.push('f2') + await expect(run(server, session)).resolves.toBeNull() + expect(server.getUncovered).toHaveBeenCalledOnce() + release() + await first + expect(server.markRead.mock.calls.map(([, scope]) => scope)).toEqual([['f1'], ['f2']]) + expect([...server.applied]).toEqual(['f1', 'f2']) + }) + + it('pages through more uncovered feeds than one call carries', async () => { + setReadSyncEnabled(true) + const feeds = Array.from({ length: READ_SYNC_FEED_IDS_MAX + 3 }, (_, i) => `f${i}`) + const server = fakeServer(feeds) + await expect(run(server)).resolves.toBeNull() + expect(server.markApplied.mock.calls.map(([ids]) => ids.length)).toEqual([READ_SYNC_FEED_IDS_MAX, 3]) + expect(server.applied.size).toBe(feeds.length) + }) +}) + describe('withdrawReadStatus', () => { const opts = (session = pulledSession(['a'])) => ({ canSign: () => true, npub: () => NPUB, session, signEvent }) diff --git a/src/lib/read-sync.ts b/src/lib/read-sync.ts index b8dad30..45eab2e 100644 --- a/src/lib/read-sync.ts +++ b/src/lib/read-sync.ts @@ -20,6 +20,12 @@ export const READ_SYNC_PUBLISH_DELAY_MS = 30_000 // leaves room for the tRPC envelope and small mutations batched alongside. export const MARK_READ_REQUEST_BYTES = 48_000 +// Most feed ids one getReadSyncUncoveredFeeds answer, scoped markReadByGuids +// call or markReadListApplied call carries. At the schema's 64 characters per +// id that is about 33 KB, so a scoped call still fits MARK_READ_REQUEST_BYTES +// once its guids are chunked to the bytes left (see applyReadListChunks). +export const READ_SYNC_FEED_IDS_MAX = 500 + // Common strfry relays (damus, nos.lol) refuse events over 64 KiB of JSON, so a // bigger list would fail to publish without any error. The web publishes only // the newest reads that fit this budget. Pulls still accept lists up to @@ -146,10 +152,27 @@ export interface ReadSyncSession { // runs behind another device's. latestSeenAt: number | null queue: Promise + // Whether coverNewFeedsWithReadList is running, and whether it was asked to + // run again meanwhile, so two runs never overlap. + covering: boolean + coverAgain: boolean + // How long to wait before retrying the next failed cover run. Doubled on + // each failure and reset by a run that finishes, so a 429 is not hammered. + coverRetryDelay: number } export function newReadSyncSession(npub: string | null = null): ReadSyncSession { - return { npub, pulled: false, remote: null, remoteVersion: 0, latestSeenAt: null, queue: Promise.resolve() } + return { + npub, + pulled: false, + remote: null, + remoteVersion: 0, + latestSeenAt: null, + queue: Promise.resolve(), + covering: false, + coverAgain: false, + coverRetryDelay: READ_SYNC_RETRY_MIN_MS, + } } // Retry delays for a pull that failed or that not every relay answered. @@ -163,6 +186,42 @@ export function nextReadSyncRetryDelay(delay: number): number { type SignEvent = (event: UnsignedEvent) => Promise +/** What getReadSyncUncoveredFeeds answers. */ +export interface ReadSyncUncoveredFeeds { + feedIds: string[] + more: boolean +} + +/** + * The server calls the pull and the cover run share. markRead without feedIds + * applies guids to every active subscription, with them only to those feeds. + */ +export interface ReadListServer { + markRead: (guids: string[], feedIds?: string[]) => Promise + getUncovered: () => Promise + markApplied: (feedIds: string[]) => Promise + onApplied: () => void +} + +/** + * Send `guids` in request-sized chunks, re-checking `live` before each one. + * `reservedBytes` is what the rest of each call's input (a feedIds scope) + * takes from the request budget. Returns false when it stopped early, true + * when every chunk was sent and the run is still live. + */ +async function applyReadListChunks( + guids: string[], + send: (part: string[]) => Promise, + live: () => boolean, + reservedBytes = 0 +): Promise { + for (const part of chunkGuidsForRequest(guids, MARK_READ_REQUEST_BYTES - reservedBytes)) { + if (!live()) return false + await send(part) + } + return live() +} + // Sync is allowed and the signed-in account is still the session's, so work // queued for an earlier account stops. function sessionAllowed(opts: { @@ -179,23 +238,22 @@ function sessionAllowed(opts: { * Additive only. The pull stops between chunks once it is cancelled, the * setting is turned off or the account changes. The watermark advances only * once every chunk is applied, so a failed or stopped apply is retried on the - * next pull. A pull that not every connected relay answered still applies - * what it found, but leaves publishing locked. Returns whether publishing is - * now safe (see ReadSyncSession.pulled), so false means "retry the pull". - * Never throws. + * next pull. A fresh event is applied to every feed, and the feeds it had + * never been applied to when the pull started are then marked applied, so the + * cover run does not send it to them again. A pull that not every connected + * relay answered still applies what it found, but leaves publishing locked. + * Returns whether publishing is now safe (see ReadSyncSession.pulled), so + * false means "retry the pull". Never throws. */ -export async function pullReadStatus(opts: { +export async function pullReadStatus(opts: ReadListServer & { canSign: () => boolean npub: () => string | null | undefined isCancelled?: () => boolean session: ReadSyncSession - markRead: (guids: string[]) => Promise - onApplied: () => void fetchRemote?: typeof fetchReadStatus }): Promise { const { session } = opts const live = () => !opts.isCancelled?.() && sessionAllowed(opts) - if (!live()) return false const remoteVersion = session.remoteVersion // A publish or withdrawal that finished during the pull already set what the // relays hold, after the pulled event, so the pulled list must not replace @@ -210,6 +268,7 @@ export async function pullReadStatus(opts: { return complete } try { + if (!live()) return false const result = await (opts.fetchRemote ?? fetchReadStatus)(session.npub!) // Raised even when the pull then stops, so a withdrawal made right after // still goes after the event the relays hold. @@ -229,11 +288,29 @@ export async function pullReadStatus(opts: { // is what the relays hold, so publishes build on it. return settle(guids, result.complete) } - for (const part of chunkGuidsForRequest(guids)) { + // The feeds the list was never applied to, taken before the first chunk: + // they get every chunk, so they can be marked applied once it is done. A + // feed subscribed during the pull missed the earlier chunks and is not in + // this snapshot, so it stays uncovered and the cover run applies the list + // to it. Best effort: without the snapshot they stay uncovered too, and the + // cover run applies the list to them once more. The snapshot is one page, + // so past READ_SYNC_FEED_IDS_MAX uncovered feeds the rest get the list a + // second time from the cover run, which only marks read again. + let uncovered: string[] = [] + try { + uncovered = (await opts.getUncovered()).feedIds + } catch (error) { + console.warn('Read status sync could not list the feeds still to cover:', error) + } + if (!(await applyReadListChunks(guids, (part) => opts.markRead(part), live))) return false + if (uncovered.length > 0) { + try { + await opts.markApplied(uncovered) + } catch (error) { + console.warn('Read status sync could not record the covered feeds:', error) + } if (!live()) return false - await opts.markRead(part) } - if (!live()) return false opts.onApplied() advanceSyncWatermarkIfFresh(READ_STATUS_D_TAG, result.createdAt) return settle(guids, result.complete) @@ -243,6 +320,69 @@ export async function pullReadStatus(opts: { } } +/** + * Apply the known remote list to the account's feeds it was never applied to, + * which the server tracks per subscription (readListAppliedAt), so a key whose + * feed was not subscribed at pull time still gets marked read once it is. The + * server picks the feeds, since the client's feed list may be filtered by + * category or tag, and since another browser may already have covered them: + * a covered feed never gets the list again, so items the user marked unread + * there stay unread. Each round snapshots the uncovered feeds, applies the + * list scoped to them, then marks them applied. A feed subscribed during the + * round is not in the snapshot and is picked up by the next run. With no + * remote list (none published, or an empty one) the feeds are still marked + * applied: there is nothing to give them, and a key this browser publishes + * later must not be applied to a feed where the user since marked it unread. + * + * Runs only after the session's pull. A run asked for while one is going runs + * again after it. Stops when cancelled, turned off or the account changes. + * Returns null when no retry is needed, else the delay before retrying, which + * doubles on each failure. A failure leaves the snapshot uncovered, so a retry + * applies again the chunks sent before it failed; within that retry window an + * item the user marked unread in a feed subscribed moments ago can be marked + * read again, which is accepted. Never throws. + */ +export async function coverNewFeedsWithReadList(opts: ReadListServer & { + canSign: () => boolean + npub: () => string | null | undefined + isCancelled?: () => boolean + session: ReadSyncSession +}): Promise { + const { session } = opts + if (session.covering) { + session.coverAgain = true + return null + } + session.covering = true + try { + const live = () => !opts.isCancelled?.() && sessionAllowed(opts) && session.pulled + do { + session.coverAgain = false + if (!live()) return null + const { feedIds, more } = await opts.getUncovered() + if (feedIds.length === 0) continue + const scope = feedIds.slice(0, READ_SYNC_FEED_IDS_MAX) + const remote = session.remote ?? [] + const send = (part: string[]) => opts.markRead(part, scope) + const scopeBytes = utf8.encode(JSON.stringify(scope)).length + if (!(await applyReadListChunks(remote, send, live, scopeBytes))) return null + await opts.markApplied(scope) + if (!live()) return null + if (remote.length > 0) opts.onApplied() + if (more || feedIds.length > scope.length) session.coverAgain = true + } while (session.coverAgain) + session.coverRetryDelay = READ_SYNC_RETRY_MIN_MS + return null + } catch (error) { + console.error('Read status sync for new feeds failed:', error) + const delay = session.coverRetryDelay + session.coverRetryDelay = nextReadSyncRetryDelay(delay) + return delay + } finally { + session.covering = false + } +} + const turnedOff = () => new Error('Read status sync was turned off') function raiseLatestSeenAt(session: ReadSyncSession, createdAt: number): void { diff --git a/src/server/api/routers/feed.ts b/src/server/api/routers/feed.ts index 7ed93dc..7963fb2 100644 --- a/src/server/api/routers/feed.ts +++ b/src/server/api/routers/feed.ts @@ -7,10 +7,12 @@ import { withRequestFetcher } from '@/lib/safe-relays' import { rateLimit } from '@/server/rate-limit' import { MAX_RELAY_URL_LENGTH, MAX_CLIENT_RELAYS } from '@/lib/relays' import { discoverFeed } from '@/lib/feed-discovery' +import { READ_SYNC_FEED_IDS_MAX } from '@/lib/read-sync' import { chunk, GUID_QUERY_CHUNK, - readGuidsInputSchema, + markReadByGuidsInputSchema, + markReadListAppliedInputSchema, readSyncKey, ReadSyncGuidCollector, } from '@/server/read-sync' @@ -42,9 +44,20 @@ function limitProfileDiscovery(name: string, pubkey: string) { // Read-status sync budgets. A publish fetches the list at most once per // 30-second debounce, plus a page close or a settings toggle, so a few a // minute is plenty. Applying an 8 MiB pulled list takes about 175 calls of -// 48 KB each, so 250 per 10 minutes lets one full pull through. +// 48 KB each, so 250 per 10 minutes lets one full pull through. Applying the +// list to newly subscribed feeds (calls scoped with feedIds) sends the whole +// list again, so those calls get a budget of their own: a pull and a cover +// run in the same window then both fit, and neither starves the other. For +// the largest lists that is about one cover run per window: a second feed +// added within it waits for the retry after the window. The cover check runs +// at most once a minute from feeds refetches plus once per subscribe, import +// or pull, and marking feeds applied once per cover run, so those two budgets +// only stop a runaway client. const READ_GUIDS_FOR_SYNC_PER_MINUTE = 6 const MARK_READ_BY_GUIDS_PER_10_MIN = 250 +const MARK_READ_BY_GUIDS_COVER_PER_10_MIN = 250 +const READ_SYNC_UNCOVERED_PER_10_MIN = 120 +const MARK_READ_LIST_APPLIED_PER_10_MIN = 60 // Type for subscription with feed include type SubscriptionWithFeed = Prisma.SubscriptionGetPayload<{ include: { feed: true } }> @@ -2072,16 +2085,27 @@ export const feedRouter = createTRPCRouter({ // Apply a pulled kind 30405 event: mark read the user's subscribed items whose // key matches. Additive only, as on the desktop: a key missing from the list - // never marks anything unread. + // never marks anything unread. With feedIds, only the caller's active + // subscriptions among them are touched, so the list can be applied to newly + // subscribed feeds without being applied again to feeds that already had it; + // ids of feeds the caller does not subscribe to are ignored. markReadByGuids: subscribedProcedure - .input(readGuidsInputSchema) + .input(markReadByGuidsInputSchema) .mutation(async ({ ctx, input }) => { - limitPerUser('feed.markReadByGuids', ctx.nostrPubkey, MARK_READ_BY_GUIDS_PER_10_MIN, 10 * 60 * 1000) + if (input.feedIds) { + limitPerUser('feed.markReadByGuids.cover', ctx.nostrPubkey, MARK_READ_BY_GUIDS_COVER_PER_10_MIN, 10 * 60 * 1000) + } else { + limitPerUser('feed.markReadByGuids', ctx.nostrPubkey, MARK_READ_BY_GUIDS_PER_10_MIN, 10 * 60 * 1000) + } const guids = [...new Set(input.guids)].filter(g => g.length > 0) if (guids.length === 0) return { marked: 0 } const subscriptions = await ctx.db.subscription.findMany({ - where: { userPubkey: ctx.nostrPubkey, deletedAt: null }, + where: { + userPubkey: ctx.nostrPubkey, + deletedAt: null, + ...(input.feedIds ? { feedId: { in: [...new Set(input.feedIds)] } } : {}), + }, select: { feedId: true }, }) const feedIds = subscriptions.map((sub: { feedId: string }) => sub.feedId) @@ -2106,4 +2130,43 @@ export const feedRouter = createTRPCRouter({ } return { marked } }), + + // The caller's active subscriptions the pulled read list has not been applied + // to yet (see Subscription.readListAppliedAt), at most READ_SYNC_FEED_IDS_MAX + // of them; `more` says whether others remain. The server decides, not the + // client's feed list, which may be filtered by category or tag. + getReadSyncUncoveredFeeds: subscribedProcedure + .query(async ({ ctx }) => { + limitPerUser('feed.getReadSyncUncoveredFeeds', ctx.nostrPubkey, READ_SYNC_UNCOVERED_PER_10_MIN, 10 * 60 * 1000) + const rows = await ctx.db.subscription.findMany({ + // A feed whose first fetch stored no items has nothing to match yet. + // Marking it applied now would leave the items its next refresh + // brings without the list, so it stays uncovered until it has some. + where: { userPubkey: ctx.nostrPubkey, deletedAt: null, readListAppliedAt: null, feed: { items: { some: {} } } }, + select: { feedId: true }, + orderBy: { createdAt: 'asc' }, + take: READ_SYNC_FEED_IDS_MAX + 1, + }) + const feedIds = rows.slice(0, READ_SYNC_FEED_IDS_MAX).map((row: { feedId: string }) => row.feedId) + return { feedIds, more: rows.length > READ_SYNC_FEED_IDS_MAX } + }), + + // Record that the pulled read list has been applied to these feeds, so no + // browser applies it to them again. Only the caller's active subscriptions + // not yet marked are touched, which keeps the first time it was applied. + markReadListApplied: subscribedProcedure + .input(markReadListAppliedInputSchema) + .mutation(async ({ ctx, input }) => { + limitPerUser('feed.markReadListApplied', ctx.nostrPubkey, MARK_READ_LIST_APPLIED_PER_10_MIN, 10 * 60 * 1000) + const result = await ctx.db.subscription.updateMany({ + where: { + userPubkey: ctx.nostrPubkey, + deletedAt: null, + readListAppliedAt: null, + feedId: { in: [...new Set(input.feedIds)] }, + }, + data: { readListAppliedAt: new Date() }, + }) + return { updated: result.count } + }), }) \ No newline at end of file diff --git a/src/server/read-sync.test.ts b/src/server/read-sync.test.ts index 9340ba9..964bc66 100644 --- a/src/server/read-sync.test.ts +++ b/src/server/read-sync.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MAX_GUID_LEN, MAX_READ_ITEMS, readStatusListSchema } from '@/lib/nostr-sync' -import { MAX_PUBLISHED_READ_CONTENT } from '@/lib/read-sync' +import { MAX_PUBLISHED_READ_CONTENT, READ_SYNC_FEED_IDS_MAX } from '@/lib/read-sync' import { feedRouter } from '@/server/api/routers/feed' import { __resetRateLimitForTests } from '@/server/rate-limit' import type { SubscriptionLookups } from '@/server/paywall' @@ -169,13 +169,58 @@ describe('feed.getReadGuidsForSync', () => { }) }) +// Subscriptions as rows, so the where clauses the procedures build are +// evaluated rather than only inspected: a row matches every filter the clause +// gives, and a filter the clause leaves out matches anything. +type SubRow = { userPubkey: string; feedId: string; deletedAt: Date | null; readListAppliedAt: Date | null; createdAt: Date; hasItems: boolean } +type SubWhere = { + userPubkey?: string + deletedAt?: null + readListAppliedAt?: null + feedId?: { in: string[] } + feed?: { items: { some: Record } } +} +const OTHER = 'f'.repeat(64) + +function sub(feedId: string, extra: Partial = {}): SubRow { + return { userPubkey: PUBKEY, feedId, deletedAt: null, readListAppliedAt: null, createdAt: new Date(0), hasItems: true, ...extra } +} + +function matches(row: SubRow, where: SubWhere): boolean { + return ( + (where.userPubkey === undefined || row.userPubkey === where.userPubkey) && + (where.deletedAt === undefined || row.deletedAt === null) && + (where.readListAppliedAt === undefined || row.readListAppliedAt === null) && + (where.feedId === undefined || where.feedId.in.includes(row.feedId)) && + (where.feed === undefined || row.hasItems) + ) +} + +function fakeSubscriptions(rows: SubRow[]) { + return { + rows, + findMany: vi.fn(async (args: { where: SubWhere; take?: number }) => + rows + .filter((row) => matches(row, args.where)) + .sort((x, y) => x.createdAt.getTime() - y.createdAt.getTime()) + .slice(0, args.take ?? Infinity) + .map((row) => ({ feedId: row.feedId })) + ), + updateMany: vi.fn(async (args: { where: SubWhere; data: { readListAppliedAt: Date } }) => { + const hit = rows.filter((row) => matches(row, args.where)) + for (const row of hit) row.readListAppliedAt = args.data.readListAppliedAt + return { count: hit.length } + }), + } +} + describe('feed.markReadByGuids', () => { type ItemArgs = { where: { feedId: { in: string[] }; OR: [{ guid: { in: string[] } }, unknown] } } - // Every guid exists in feed-1 and feed-2; the lookup honours the feedId filter. - function fakeDb(feedIds: string[], itemFeeds = ['feed-1', 'feed-2']) { + // Every guid exists in feed-1, feed-2 and feed-3; the lookup honours the feedId filter. + function fakeDb(subscriptions: Array, itemFeeds = ['feed-1', 'feed-2', 'feed-3']) { return { - subscription: { findMany: vi.fn(async () => feedIds.map((feedId) => ({ feedId }))) }, + subscription: fakeSubscriptions(subscriptions.map((row) => (typeof row === 'string' ? sub(row) : row))), feedItem: { findMany: vi.fn(async (args: ItemArgs) => itemFeeds @@ -210,8 +255,8 @@ describe('feed.markReadByGuids', () => { expect(db.readItem.deleteMany).not.toHaveBeenCalled() }) - it('marks only items in the user\'s subscribed feeds', async () => { - const db = fakeDb(['feed-2']) + it('marks only items in the user\'s active subscribed feeds', async () => { + const db = fakeDb(['feed-2', sub('feed-1', { deletedAt: new Date(1) }), sub('feed-3', { userPubkey: OTHER })]) await expect(feedRouter.createCaller(ctx(db)).markReadByGuids({ guids: ['a', 'b'] })).resolves.toEqual({ marked: 2 }) expect(db.readItem.createMany).toHaveBeenCalledWith({ data: [ @@ -222,13 +267,36 @@ describe('feed.markReadByGuids', () => { }) }) - it('is rate limited per user, with room for a full pull', async () => { + it('with feedIds, touches only those of the caller\'s active subscriptions, so covered feeds keep their unreads', async () => { + const db = fakeDb([ + 'feed-1', + 'feed-2', + sub('feed-3', { deletedAt: new Date(1) }), + sub('feed-4', { userPubkey: OTHER }), + ], ['feed-1', 'feed-2', 'feed-3', 'feed-4']) + const caller = feedRouter.createCaller(ctx(db)) + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: ['feed-2', 'feed-3', 'feed-4', 'feed-9', 'feed-2'] })).resolves.toEqual({ + marked: 1, + }) + expect(db.readItem.createMany).toHaveBeenCalledOnce() + expect(db.readItem.createMany).toHaveBeenCalledWith({ data: [{ userPubkey: PUBKEY, itemId: 'feed-2-a' }], skipDuplicates: true }) + + // Only foreign, unsubscribed or unknown feeds: nothing is looked up. + db.feedItem.findMany.mockClear() + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: ['feed-3', 'feed-4', 'feed-9'] })).resolves.toEqual({ marked: 0 }) + expect(db.feedItem.findMany).not.toHaveBeenCalled() + }) + + it('is rate limited per user, with room for a full pull and a separate budget for covering new feeds', async () => { const caller = feedRouter.createCaller(ctx(fakeDb(['feed-1']))) for (let i = 0; i < 250; i++) await caller.markReadByGuids({ guids: ['a'] }) await expect(caller.markReadByGuids({ guids: ['a'] })).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' }) + // The pull's budget is spent, yet the cover run still has all of its own. + for (let i = 0; i < 250; i++) await caller.markReadByGuids({ guids: ['a'], feedIds: ['feed-1'] }) + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: ['feed-1'] })).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' }) }) - it('skips the item lookup without subscriptions or guids', async () => { + it('skips the lookups without subscriptions or guids', async () => { for (const [feeds, guids] of [[[], ['a']], [['feed-1'], []]] as [string[], string[]][]) { const db = fakeDb(feeds) await expect(feedRouter.createCaller(ctx(db)).markReadByGuids({ guids })).resolves.toEqual({ marked: 0 }) @@ -239,8 +307,87 @@ describe('feed.markReadByGuids', () => { it('rejects input past the caps', async () => { const db = fakeDb(['feed-1']) const caller = feedRouter.createCaller(ctx(db)) - await expect(caller.markReadByGuids({ guids: ['g'.repeat(MAX_GUID_LEN + 1)] })).rejects.toMatchObject({ code: 'BAD_REQUEST' }) - await expect(caller.markReadByGuids({ guids: Array(MAX_READ_ITEMS + 1).fill('g') })).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + const bad = { code: 'BAD_REQUEST' } + await expect(caller.markReadByGuids({ guids: ['g'.repeat(MAX_GUID_LEN + 1)] })).rejects.toMatchObject(bad) + await expect(caller.markReadByGuids({ guids: Array(MAX_READ_ITEMS + 1).fill('g') })).rejects.toMatchObject(bad) + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: Array(READ_SYNC_FEED_IDS_MAX + 1).fill('feed-1') })).rejects.toMatchObject(bad) + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: [] })).rejects.toMatchObject(bad) + for (const feedId of ['', 'x'.repeat(65), 'feed 1', "feed'1", 'feed/1']) { + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: [feedId] })).rejects.toMatchObject(bad) + } + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: 'feed-1' as never })).rejects.toMatchObject(bad) expect(db.subscription.findMany).not.toHaveBeenCalled() + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: Array(READ_SYNC_FEED_IDS_MAX).fill('x'.repeat(64)) })).resolves.toEqual({ marked: 0 }) + }) +}) + +describe('feed.getReadSyncUncoveredFeeds', () => { + it('lists the caller\'s active subscriptions the read list was never applied to, oldest first', async () => { + const subscription = fakeSubscriptions([ + sub('feed-new', { createdAt: new Date(3) }), + sub('feed-covered', { readListAppliedAt: new Date(1) }), + sub('feed-gone', { deletedAt: new Date(1) }), + sub('feed-old', { createdAt: new Date(1) }), + sub('feed-foreign', { userPubkey: OTHER }), + sub('feed-empty', { createdAt: new Date(2), hasItems: false }), + ]) + const caller = feedRouter.createCaller(ctx({ subscription })) + await expect(caller.getReadSyncUncoveredFeeds()).resolves.toEqual({ feedIds: ['feed-old', 'feed-new'], more: false }) + }) + + it('returns at most READ_SYNC_FEED_IDS_MAX and says when more remain', async () => { + const rows = Array.from({ length: READ_SYNC_FEED_IDS_MAX + 1 }, (_, i) => sub(`feed-${i}`, { createdAt: new Date(i) })) + const caller = feedRouter.createCaller(ctx({ subscription: fakeSubscriptions(rows) })) + const first = await caller.getReadSyncUncoveredFeeds() + expect(first.feedIds).toEqual(rows.slice(0, READ_SYNC_FEED_IDS_MAX).map((row) => row.feedId)) + expect(first.more).toBe(true) + rows.pop() + await expect(caller.getReadSyncUncoveredFeeds()).resolves.toMatchObject({ more: false }) + }) + + it('is rate limited per user', async () => { + const caller = feedRouter.createCaller(ctx({ subscription: fakeSubscriptions([]) })) + for (let i = 0; i < 120; i++) await caller.getReadSyncUncoveredFeeds() + await expect(caller.getReadSyncUncoveredFeeds()).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' }) + }) +}) + +describe('feed.markReadListApplied', () => { + it('marks only the given feeds among the caller\'s active, uncovered subscriptions', async () => { + const earlier = new Date(5) + const subscription = fakeSubscriptions([ + sub('feed-1'), + sub('feed-2'), + sub('feed-covered', { readListAppliedAt: earlier }), + sub('feed-gone', { deletedAt: new Date(1) }), + sub('feed-foreign', { userPubkey: OTHER }), + ]) + const caller = feedRouter.createCaller(ctx({ subscription })) + await expect( + caller.markReadListApplied({ feedIds: ['feed-1', 'feed-covered', 'feed-gone', 'feed-foreign', 'feed-9', 'feed-1'] }) + ).resolves.toEqual({ updated: 1 }) + const applied = Object.fromEntries(subscription.rows.map((row) => [`${row.userPubkey === PUBKEY ? '' : 'other:'}${row.feedId}`, row.readListAppliedAt])) + expect(applied['feed-1']).toBeInstanceOf(Date) + expect(applied['feed-2']).toBeNull() + expect(applied['feed-covered']).toBe(earlier) + expect(applied['feed-gone']).toBeNull() + expect(applied['other:feed-foreign']).toBeNull() + }) + + it('needs feedIds within the caps', async () => { + const subscription = fakeSubscriptions([sub('feed-1')]) + const caller = feedRouter.createCaller(ctx({ subscription })) + const bad = { code: 'BAD_REQUEST' } + await expect(caller.markReadListApplied({} as never)).rejects.toMatchObject(bad) + await expect(caller.markReadListApplied({ feedIds: [] })).rejects.toMatchObject(bad) + await expect(caller.markReadListApplied({ feedIds: Array(READ_SYNC_FEED_IDS_MAX + 1).fill('feed-1') })).rejects.toMatchObject(bad) + await expect(caller.markReadListApplied({ feedIds: ['feed;1'] })).rejects.toMatchObject(bad) + expect(subscription.updateMany).not.toHaveBeenCalled() + }) + + it('is rate limited per user', async () => { + const caller = feedRouter.createCaller(ctx({ subscription: fakeSubscriptions([]) })) + for (let i = 0; i < 60; i++) await caller.markReadListApplied({ feedIds: ['feed-1'] }) + await expect(caller.markReadListApplied({ feedIds: ['feed-1'] })).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' }) }) }) diff --git a/src/server/read-sync.ts b/src/server/read-sync.ts index ad80043..48b2f63 100644 --- a/src/server/read-sync.ts +++ b/src/server/read-sync.ts @@ -1,5 +1,6 @@ import { z } from 'zod' import { MAX_READ_ITEMS, readGuidSchema } from '@/lib/nostr-sync' +import { READ_SYNC_FEED_IDS_MAX } from '@/lib/read-sync' export { ReadSyncGuidCollector } from '@/lib/read-sync' @@ -10,6 +11,20 @@ export const readGuidsInputSchema = z.object({ guids: z.array(readGuidSchema).max(MAX_READ_ITEMS), }) +// Feed ids are cuids. The charset and length bound keep a hostile list from +// building a huge `in` query, and the count bound keeps a scoped +// markReadByGuids call under the request body cap (see READ_SYNC_FEED_IDS_MAX). +const feedIdSchema = z.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/) +export const readSyncFeedIdsSchema = z.array(feedIdSchema).min(1).max(READ_SYNC_FEED_IDS_MAX) + +export const markReadByGuidsInputSchema = readGuidsInputSchema.extend({ + feedIds: readSyncFeedIdsSchema.optional(), +}) + +export const markReadListAppliedInputSchema = z.object({ + feedIds: readSyncFeedIdsSchema, +}) + /** * The key an item has in a kind 30405 event: its guid, or its link when it has * none. The desktop keys items the same way (feedparser.cpp finishItem, with the From 0181ba63260ad3f3b7035268cdaf82918d03e5cf Mon Sep 17 00:00:00 2001 From: William K Santiago Date: Sun, 22 Nov 2026 19:56:35 -0400 Subject: [PATCH 2/2] Skip feeds another browser already covered when applying the read list --- src/server/api/routers/feed.ts | 5 ++++- src/server/read-sync.test.ts | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/server/api/routers/feed.ts b/src/server/api/routers/feed.ts index 7963fb2..edabb3c 100644 --- a/src/server/api/routers/feed.ts +++ b/src/server/api/routers/feed.ts @@ -2100,11 +2100,14 @@ export const feedRouter = createTRPCRouter({ const guids = [...new Set(input.guids)].filter(g => g.length > 0) if (guids.length === 0) return { marked: 0 } + // A cover call may come from a browser holding an older list of uncovered + // feeds, so it skips feeds another browser has covered since: applying the + // list there again would re-read items the user has marked unread. const subscriptions = await ctx.db.subscription.findMany({ where: { userPubkey: ctx.nostrPubkey, deletedAt: null, - ...(input.feedIds ? { feedId: { in: [...new Set(input.feedIds)] } } : {}), + ...(input.feedIds ? { feedId: { in: [...new Set(input.feedIds)] }, readListAppliedAt: null } : {}), }, select: { feedId: true }, }) diff --git a/src/server/read-sync.test.ts b/src/server/read-sync.test.ts index 964bc66..8e706c5 100644 --- a/src/server/read-sync.test.ts +++ b/src/server/read-sync.test.ts @@ -287,6 +287,24 @@ describe('feed.markReadByGuids', () => { expect(db.feedItem.findMany).not.toHaveBeenCalled() }) + it('with feedIds, skips feeds already covered, since a stale browser may still list them; a full pull covers both', async () => { + const db = fakeDb(['feed-1', sub('feed-2', { readListAppliedAt: new Date(1) })]) + const caller = feedRouter.createCaller(ctx(db)) + await expect(caller.markReadByGuids({ guids: ['a'], feedIds: ['feed-1', 'feed-2'] })).resolves.toEqual({ marked: 1 }) + expect(db.readItem.createMany).toHaveBeenCalledOnce() + expect(db.readItem.createMany).toHaveBeenCalledWith({ data: [{ userPubkey: PUBKEY, itemId: 'feed-1-a' }], skipDuplicates: true }) + + db.readItem.createMany.mockClear() + await expect(caller.markReadByGuids({ guids: ['a'] })).resolves.toEqual({ marked: 2 }) + expect(db.readItem.createMany).toHaveBeenCalledWith({ + data: [ + { userPubkey: PUBKEY, itemId: 'feed-1-a' }, + { userPubkey: PUBKEY, itemId: 'feed-2-a' }, + ], + skipDuplicates: true, + }) + }) + it('is rate limited per user, with room for a full pull and a separate budget for covering new feeds', async () => { const caller = feedRouter.createCaller(ctx(fakeDb(['feed-1']))) for (let i = 0; i < 250; i++) await caller.markReadByGuids({ guids: ['a'] })