import { queueReadStateMutation } from "./readStateMutationQueue"; import { loadPDSReadStateSync, usesPDSReadState } from "@/lib/pdsReadStateRuntime"; import type { OAuthSession } from "@atproto/oauth-client-browser"; import { articleContentLabelFields } from "@/lib/articleContentLabels"; import { normalizeAppViewPublishedAt } from "@/lib/appViewPublishedAt"; import type { EntryListItem, EntryDetail } from "@/lib/atprotoClient"; import type { ArticleListFilter } from "@/lib/entryArticleFilter"; import type { PublicationAppViewScope, UnreadCountsAccuracy, } from "@/lib/publicationProjectionClient"; import { normalizeHttpUrlToHttps } from "@/lib/publicResourceUrl"; import { gatewayFetch } from "@/lib/socialWireGatewayClient"; import { socialWireXrpc } from "@/lib/socialWireXrpc"; import { sourceRefreshErrorFromResponse } from "@/lib/publicationSourceRefreshError"; import { requestUnreadCountChunk } from "@/lib/appViewUnreadCountRequests"; export type AppViewEntriesPage = { entries: EntryListItem[]; cursor?: string; }; export type AggregateAppViewFeed = { kind: "subscribed" | "following" | "folder" | "publication" | "list"; id?: string; }; export type AppViewUnreadCountsResponse = { counts: Record; generation?: number; accuracy?: UnreadCountsAccuracy; countedAt?: string; }; export class AppViewRequestError extends Error { readonly status: number; readonly requestId?: string; readonly retryable: boolean; constructor(args: { message: string; status: number; requestId?: string; retryable?: boolean; }) { super(args.message); this.name = "AppViewRequestError"; this.status = args.status; this.requestId = args.requestId; this.retryable = args.retryable === true; } } export function shouldRetryAppViewRequest( failureCount: number, error: unknown ): boolean { return ( failureCount < 1 && error instanceof AppViewRequestError && error.retryable ); } async function appViewResponseError( res: Response, fallback: string ): Promise { const requestId = res.headers.get("X-Request-ID") ?? undefined; let message = `${fallback} (${res.status})`; let retryable = false; try { const envelope = (await res.json()) as { message?: string; requestId?: string; retryable?: boolean; }; message = envelope.message?.trim() || message; retryable = envelope.retryable === true; return new AppViewRequestError({ message, status: res.status, requestId: envelope.requestId ?? requestId, retryable, }); } catch { return new AppViewRequestError({ message, status: res.status, requestId }); } } export async function listEntriesFromAppView(args: { publicationKey: string; appViewScope: PublicationAppViewScope; cursor?: string; limit?: number; maxEntries?: number; filter?: ArticleListFilter; oauthSession: OAuthSession; signal?: AbortSignal; }): Promise { const { appViewScope, cursor, limit = 50, maxEntries, filter = "all", oauthSession, signal, } = args; const { authorDid, publicationAtUri, publicationScopeAtUris, publicationSiteUrls } = appViewScope; const params = new URLSearchParams({ authorDid, filter, limit: String(limit), }); if (typeof maxEntries === "number") { params.set("maxEntries", String(maxEntries)); } else if (cursor) { params.set("cursor", cursor); } if (publicationAtUri) { params.set("publicationAtUri", publicationAtUri); } if (publicationSiteUrls.length > 0) { params.set("publicationSiteUrls", publicationSiteUrls.join(",")); } if (publicationScopeAtUris.length > 0) { params.set("publicationScopeAtUris", publicationScopeAtUris.join(",")); } const res = await gatewayFetch( oauthSession, `${socialWireXrpc.listEntries}?${params.toString()}`, { method: "GET", signal } ); if (!res.ok) { throw await appViewResponseError(res, "Thin AppView entries failed"); } const json = (await res.json()) as { entries?: Array<{ entryId: string; contentLabels?: unknown; title: string; summary?: string; publishedAt: unknown; thumbnailUrl?: string; thumbnailFallbackUrl?: string; originalUrl?: string; isRead: boolean; }>; cursor?: string; }; return { entries: (json.entries ?? []).map((row) => { const originalUrl = row.originalUrl?.trim(); const normalizedOriginal = originalUrl ? normalizeHttpUrlToHttps(originalUrl) : undefined; return { entryId: row.entryId, ...articleContentLabelFields(row.contentLabels), title: row.title, summary: row.summary, publishedAt: normalizeAppViewPublishedAt(row.publishedAt), thumbnailUrl: row.thumbnailUrl, thumbnailFallbackUrl: row.thumbnailFallbackUrl, isRead: row.isRead, ...(normalizedOriginal ? { originalUrl: normalizedOriginal } : {}), }; }), cursor: json.cursor, }; } export async function listAggregateFeedFromAppView(args: { feed: AggregateAppViewFeed; cursor?: string; limit?: number; filter?: ArticleListFilter; oauthSession: OAuthSession; signal?: AbortSignal; }): Promise { const { feed, cursor, limit = 50, filter = "all", oauthSession, signal, } = args; const params = new URLSearchParams({ kind: feed.kind, filter, limit: String(limit), }); if (feed.id) params.set("id", feed.id); if (cursor) params.set("cursor", cursor); const res = await gatewayFetch( oauthSession, `${socialWireXrpc.getFeed}?${params.toString()}`, { method: "GET", signal }, ); if (!res.ok) { throw await appViewResponseError(res, "Aggregate AppView feed failed"); } const json = (await res.json()) as { entries?: Array<{ entryId: string; contentLabels?: unknown; title: string; summary?: string; publishedAt: unknown; thumbnailUrl?: string; thumbnailFallbackUrl?: string; originalUrl?: string; publicationId?: string; isRead: boolean; }>; cursor?: string; }; return { entries: (json.entries ?? []).map((row) => { const normalizedOriginal = row.originalUrl?.trim() ? normalizeHttpUrlToHttps(row.originalUrl) : undefined; return { entryId: row.entryId, ...articleContentLabelFields(row.contentLabels), title: row.title, summary: row.summary, publishedAt: normalizeAppViewPublishedAt(row.publishedAt), thumbnailUrl: row.thumbnailUrl, thumbnailFallbackUrl: row.thumbnailFallbackUrl, publicationId: row.publicationId, isRead: row.isRead, ...(normalizedOriginal ? { originalUrl: normalizedOriginal } : {}), }; }), cursor: json.cursor, }; } export async function getEntryFromAppView( oauthSession: OAuthSession, entryId: string, signal?: AbortSignal ): Promise { const params = new URLSearchParams({ entryId }); const res = await gatewayFetch( oauthSession, `${socialWireXrpc.getEntry}?${params.toString()}`, { method: "GET", signal } ); if (res.status === 404) { return null; } if (!res.ok) { throw new Error(`Thin AppView entry detail failed (${res.status})`); } const json = (await res.json()) as { entryId: string; contentLabels?: unknown; title: string; summary?: string; publishedAt: unknown; thumbnailUrl?: string; thumbnailFallbackUrl?: string; contentHtml?: string; originalUrl?: string; }; const originalUrl = json.originalUrl?.trim(); const normalizedOriginal = originalUrl ? normalizeHttpUrlToHttps(originalUrl) : undefined; return { entryId: json.entryId, ...articleContentLabelFields(json.contentLabels), title: json.title, summary: json.summary, publishedAt: normalizeAppViewPublishedAt(json.publishedAt), contentHtml: json.contentHtml ?? json.summary ?? "", thumbnailUrl: json.thumbnailUrl, thumbnailFallbackUrl: json.thumbnailFallbackUrl, ...(normalizedOriginal ? { originalUrl: normalizedOriginal, embedUrl: normalizedOriginal } : {}), }; } /** Encoded query budget per request; Safari rejects very long URLs as "bad URL". */ const UNREAD_COUNTS_MAX_QUERY_LENGTH = 6_000; /** Bound queued work per refresh; the session lane also caps all callers at two. */ const UNREAD_COUNTS_MAX_CONCURRENCY = 2; /** Split publication IDs into requests whose encoded query stays under the URL budget. */ export function chunkUnreadCountPublicationIds( publicationIds: readonly string[], maxQueryLength = UNREAD_COUNTS_MAX_QUERY_LENGTH ): string[][] { const chunks: string[][] = []; let current: string[] = []; let length = 0; for (const publicationId of new Set(publicationIds)) { const paramLength = new URLSearchParams({ publicationIds: publicationId }).toString().length + 1; if (current.length > 0 && length + paramLength > maxQueryLength) { chunks.push(current); current = []; length = 0; } current.push(publicationId); length += paramLength; } if (current.length > 0) chunks.push(current); return chunks; } export async function fetchAppViewUnreadCounts( oauthSession: OAuthSession, publicationIds: string[], signal?: AbortSignal ): Promise { const chunks = chunkUnreadCountPublicationIds(publicationIds); if (chunks.length === 0) return { counts: {} }; const readChunk = (chunk: string[], signal?: AbortSignal) => requestUnreadCountChunk(oauthSession, chunk, requestSignal => fetchAppViewUnreadCountsChunk(oauthSession, chunk, requestSignal), signal); if (chunks.length === 1) { return readChunk(chunks[0], signal); } // Each chunk holds a pooled AppView database connection; an unbounded burst // starves every other request on the instance (mark-all, read ages, feeds). const snapshots: AppViewUnreadCountsResponse[] = new Array(chunks.length); const lifetime = new AbortController(); const requestSignal = signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal; let next = 0; try { await Promise.all( Array.from({ length: Math.min(UNREAD_COUNTS_MAX_CONCURRENCY, chunks.length) }, async () => { while (next < chunks.length) { requestSignal.throwIfAborted(); const index = next++; snapshots[index] = await readChunk(chunks[index], requestSignal); } }) ); } catch (error) { lifetime.abort(error); throw error; } const generations = snapshots.flatMap((s) => (s.generation == null ? [] : [s.generation])); const countedAts = snapshots.flatMap((s) => (s.countedAt ? [s.countedAt] : [])); return { counts: Object.assign({}, ...snapshots.map((s) => s.counts)), generation: generations.length ? Math.max(...generations) : undefined, // The combined snapshot is only exact when every chunk was. accuracy: snapshots.every((s) => s.accuracy === "exact") ? "exact" : snapshots.find((s) => s.accuracy && s.accuracy !== "exact")?.accuracy, // The oldest chunk bounds how fresh the whole snapshot is. countedAt: countedAts.sort()[0], }; } async function fetchAppViewUnreadCountsChunk( oauthSession: OAuthSession, publicationIds: string[], signal?: AbortSignal ): Promise { const params = new URLSearchParams(); for (const publicationId of publicationIds) { params.append("publicationIds", publicationId); } const res = await gatewayFetch( oauthSession, `${socialWireXrpc.getUnreadCounts}?${params.toString()}`, { method: "GET", signal } ); if (res.status === 404) { return { counts: {} }; } if (!res.ok) { throw new Error(`Thin AppView unread counts failed (${res.status})`); } const json = (await res.json()) as { counts?: Record; generation?: number; accuracy?: UnreadCountsAccuracy; countedAt?: string; }; return { counts: json.counts ?? {}, generation: json.generation, accuracy: json.accuracy, countedAt: json.countedAt, }; } export async function writeThroughReadMark( oauthSession: OAuthSession, subjectUri: string, readAt: string ): Promise { return queueReadStateMutation(oauthSession, assertCurrent => writeThroughReadMarkOrdered(oauthSession, subjectUri, readAt, assertCurrent)); } async function writeThroughReadMarkOrdered( oauthSession: OAuthSession, subjectUri: string, readAt: string, assertCurrent: () => void, canonicalAuthority = false ): Promise { const canonical = canonicalAuthority || await usesPDSReadState(oauthSession); assertCurrent(); if (canonical) { const runtime = await loadPDSReadStateSync(oauthSession); assertCurrent(); await runtime.exact([subjectUri], "read", readAt); assertCurrent(); return; } const res = await gatewayFetch(oauthSession, socialWireXrpc.putReadMark, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ subjectUri, readAt }), }); assertCurrent(); if (!res.ok) { if (res.status === 409) { const canonical = await usesPDSReadState(oauthSession, true); assertCurrent(); if (canonical) return writeThroughReadMarkOrdered(oauthSession, subjectUri, readAt, assertCurrent, true); } throw new Error(`Thin AppView read-mark upsert failed (${res.status})`); } } export async function writeThroughReadMarkDelete( oauthSession: OAuthSession, subjectUri: string ): Promise { return queueReadStateMutation(oauthSession, assertCurrent => writeThroughReadMarkDeleteOrdered(oauthSession, subjectUri, assertCurrent)); } async function writeThroughReadMarkDeleteOrdered( oauthSession: OAuthSession, subjectUri: string, assertCurrent: () => void, canonicalAuthority = false ): Promise { const canonical = canonicalAuthority || await usesPDSReadState(oauthSession); assertCurrent(); if (canonical) { const runtime = await loadPDSReadStateSync(oauthSession); assertCurrent(); await runtime.exact([subjectUri], "unread"); assertCurrent(); return; } const res = await gatewayFetch(oauthSession, socialWireXrpc.deleteReadMark, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ subjectUri }), }); assertCurrent(); if (!res.ok) { if (res.status === 409) { const canonical = await usesPDSReadState(oauthSession, true); assertCurrent(); if (canonical) return writeThroughReadMarkDeleteOrdered(oauthSession, subjectUri, assertCurrent, true); } throw new Error(`Thin AppView read-mark delete failed (${res.status}`); } } /** * Writes one read state for many entries as a single queued mutation. PDS read state takes the * whole batch in one outbox operation; the AppView fallback has no batch route, so it runs a * bounded number of per-entry writes. Resolves with the entries whose write failed. */ export async function writeThroughReadStates( oauthSession: OAuthSession, subjectUris: string[], read: boolean, readAt: string = new Date().toISOString() ): Promise> { return queueReadStateMutation(oauthSession, async assertCurrent => { const failures = new Map(); if (subjectUris.length === 0) return failures; const canonical = await usesPDSReadState(oauthSession); assertCurrent(); if (canonical) { const runtime = await loadPDSReadStateSync(oauthSession); assertCurrent(); await runtime.exact(subjectUris, read ? "read" : "unread", readAt); assertCurrent(); return failures; } let next = 0; const worker = async () => { while (next < subjectUris.length) { const subjectUri = subjectUris[next++]; try { if (read) await writeThroughReadMarkOrdered(oauthSession, subjectUri, readAt, assertCurrent); else await writeThroughReadMarkDeleteOrdered(oauthSession, subjectUri, assertCurrent); } catch (error) { failures.set(subjectUri, error); } } }; await Promise.all(Array.from({ length: Math.min(8, subjectUris.length) }, worker)); assertCurrent(); return failures; }); } export async function enrollAuthorsInAppView( oauthSession: OAuthSession, authorDids: string[], feedUrls: string[] = [], signal?: AbortSignal ): Promise { if (authorDids.length === 0 && feedUrls.length === 0) return; const res = await gatewayFetch(oauthSession, socialWireXrpc.enrollSources, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ authorDids, feedUrls }), signal, }); if (!res.ok) { const partial = sourceRefreshErrorFromResponse(res.status, await res.json().catch(() => undefined)); if (partial) throw partial; throw new Error(`Thin AppView enroll failed (${res.status})`); } } export async function purgeThinAppViewData( oauthSession: OAuthSession ): Promise { const res = await gatewayFetch(oauthSession, socialWireXrpc.purgeViewerData, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}", }); if (!res.ok) { throw new Error(`Thin AppView purge failed (${res.status})`); } }