diff --git a/CONTEXT.md b/CONTEXT.md index e620135..7fa9955 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -44,6 +44,10 @@ _Avoid_: export, backup, archive export Creating one new, disconnected Bluesky local account from a prepared Cyd Bluesky archive for an identity this installation does not already hold. It is the commit half of a Bluesky archive import for a new Bluesky identity; an identity Cyd already has a Bluesky local account for is merged instead. _Avoid_: restore, import, replace +**Bluesky archive merge**: +The commit half of a Bluesky archive import for an identity this installation already holds: a union of the Cyd Bluesky archive into that Bluesky local account's Bluesky saved data, previewed before it is written. It adds and enriches Bluesky saved records and never touches the account's identifier, Bluesky account settings, schedules or Bluesky connection. +_Avoid_: merge, sync, overwrite, import + **Bluesky account settings**: Local preferences governing how Cyd saves and manages a Bluesky identity. A Cyd Bluesky archive can supply defaults for a new Bluesky local account, but does not silently override an existing Bluesky local account's preferences or schedules. _Avoid_: account settings, account data, archive state diff --git a/app/account/[accountId].tsx b/app/account/[accountId].tsx index fb874ea..1d29684 100644 --- a/app/account/[accountId].tsx +++ b/app/account/[accountId].tsx @@ -36,6 +36,11 @@ import iconHome from "@/assets/images/icon-home.png"; import iconSave from "@/assets/images/icon-save.png"; import iconSchedule from "@/assets/images/icon-schedule.png"; +import { + AccountAvatar, + accountDisplayName, + accountUsername, +} from "@/components/account/identity"; import { getThemePalette } from "@/constants/theme"; import { ACCOUNT_AUTH_STATUS, @@ -51,7 +56,7 @@ import { useColorScheme } from "@/hooks/use-color-scheme"; import { onAuthStatusChange } from "@/services/auth-events"; import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; import { disconnectBlueskyAccount } from "@/services/bluesky-disconnect"; -import { authenticateBlueskyAccount } from "@/services/bluesky-oauth"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; import type { AccountTabKey, AccountTabProps } from "@/types/account-tabs"; import { BrowseTab } from "./tabs/browse-tab"; import { DashboardTab } from "./tabs/dashboard-tab"; @@ -147,13 +152,10 @@ export default function AccountScreen() { try { console.log("[AccountScreen] handleReauthenticate -> start", account.id); - await authenticateBlueskyAccount(account.handle); - console.log( - "[AccountScreen] authenticateBlueskyAccount -> success", - account.id, - ); - const nextStatus = await runWithAccountController(account, (controller) => - verifyBlueskyAccountAuthStatus(controller, account, { force: true }), + // Signing in is more than authorizing: it also refreshes what this + // account knows about itself, which is why it is not done by hand here. + const { status: nextStatus } = await connectBlueskyAccount( + account.handle, ); console.log( "[AccountScreen] handleReauthenticate -> verified", @@ -311,14 +313,8 @@ export default function AccountScreen() { }, [account]), ); - const avatarUri = account?.avatarUrl ?? null; - const username = account?.handle - ? account.handle.startsWith("@") - ? account.handle - : `@${account.handle}` - : null; - const displayName = account?.displayName ?? username ?? "Unknown"; - const initial = displayName.replace(/^@/, "").charAt(0).toUpperCase() || "?"; + const username = account?.handle ? accountUsername(account.handle) : null; + const displayName = account ? accountDisplayName(account) : "Unknown"; const accountStatus = error ? "Unable to load account" : loading @@ -374,35 +370,11 @@ export default function AccountScreen() { headerBackTitle: "Back", headerTitle: () => ( - {avatarUri ? ( - - ) : ( - - - {initial} - - - )} + { - await verifyBlueskyAccountAuthStatus(controller, savedAccount, { - force: true, - }); - }, - ); - } catch (verifyError) { - console.warn( - "[AddAccount] Failed to persist auth status after OAuth", - verifyError, - ); - } + const { account: savedAccount } = await connectBlueskyAccount(handle); router.replace({ pathname: "/account/[accountId]", params: { accountId: savedAccount.uuid }, diff --git a/app/index.tsx b/app/index.tsx index 2d4a57b..3b73113 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -3,7 +3,6 @@ import { useCallback, useMemo, useState } from "react"; import { ActivityIndicator, FlatList, - Image, Linking, Pressable, RefreshControl, @@ -16,6 +15,11 @@ import { SafeAreaView } from "react-native-safe-area-context"; import WordmarkDark from "@/assets/images/cyd-wordmark-dark.svg"; import WordmarkLight from "@/assets/images/cyd-wordmark.svg"; +import { + AccountAvatar, + accountDisplayName, + accountUsername, +} from "@/components/account/identity"; import { Colors, getThemePalette } from "@/constants/theme"; import type { AccountListItem } from "@/database/accounts"; import { useAccounts } from "@/hooks/use-accounts"; @@ -235,12 +239,8 @@ function AccountCard({ disabled, busy, }: AccountCardProps) { - const avatarUri = account.avatarUrl || null; - const username = account.handle.startsWith("@") - ? account.handle - : `@${account.handle}`; - const displayName = account.displayName ?? username; - const initial = displayName.replace(/^@/, "").charAt(0).toUpperCase() || "?"; + const username = accountUsername(account.handle); + const displayName = accountDisplayName(account); return ( - {avatarUri ? ( - - ) : ( - - - {initial} - - - )} + void; + onConfirmMerge: () => void; + /** Connect the account an import just restored, from where it was restored. */ + onSignIn: (handle: string) => void; + onCancel: () => void; + onDismiss: () => void; +}; + +export function BlueskyArchiveImportModal({ + state, + onConfirmLargeArchive, + onConfirmMerge, + onSignIn, + onCancel, + onDismiss, +}: BlueskyArchiveImportModalProps) { + const palette = getThemePalette(useColorScheme()); + + if (state.status === "idle") { + return null; + } + + const action = ( + label: string, + onPress: () => void, + emphasis: "primary" | "quiet" = "quiet", + ) => ( + [ + styles.action, + { + borderColor: palette.icon + "22", + backgroundColor: + emphasis === "primary" ? palette.tint + "22" : palette.background, + opacity: pressed ? 0.9 : 1, + }, + ]} + > + {label} + + ); + + /** + * What the Android back button does, which is what the nearest button does. + * + * Backing out of a question is cancelling it, and backing out of a report is + * dismissing it. The one state with no button is a merge being written, and + * back does nothing there for the same reason there is nothing to press: a + * commit cannot be called back, and half a merge is not a state to leave + * somebody in. + */ + const handleRequestClose = () => { + if (state.status === "done" || state.status === "failed") { + onDismiss(); + return; + } + if (state.status === "working" && !state.cancellable) { + return; + } + onCancel(); + }; + + return ( + + + + {state.status === "working" ? ( + <> + + + {state.message} + + {state.fraction !== null ? ( + + {Math.round(state.fraction * 100)}% + + ) : null} + {state.cancellable ? action("Cancel", onCancel) : null} + + ) : null} + + {state.status === "needs-confirmation" ? ( + <> + + This is a big archive + + + {state.message} + + {action("Import it", onConfirmLargeArchive, "primary")} + {action("Cancel", onCancel)} + + ) : null} + + {state.status === "reviewing" ? ( + <> + + Merge into + + + {breakableHandle(state.handle)} + + {describeMerge(state.preview).map((line) => ( + + {line} + + ))} + {action("Import", onConfirmMerge, "primary")} + {action("Cancel", onCancel)} + + ) : null} + + {state.status === "done" ? ( + <> + + {state.title} + + + {breakableHandle(state.handle)} + + {state.lines.map((line) => ( + + {line} + + ))} + {state.offerSignIn ? ( + <> + {action( + "Sign in to Bluesky", + () => onSignIn(state.handle), + "primary", + )} + {action("Not now", onDismiss)} + + ) : ( + action("Done", onDismiss, "primary") + )} + + ) : null} + + {state.status === "failed" ? ( + <> + + Import failed + + + {state.message} + + {action("Close", onDismiss, "primary")} + + ) : null} + + + + ); +} + + +/** + * A handle written so a line box breaks it where a reader would. + * + * A handle is a single token with no spaces in it, so a heading wide enough + * for most of one splits it wherever it happens to run out of room — + * "@glittertop-cyd.bsky" above ".social". A zero-width space before each dot + * offers the layout the same break points a person would choose, and leaves + * nothing on screen. Nothing is truncated: a handle is how somebody knows + * which account this is. + */ +function breakableHandle(handle: string): string { + return `@${handle.replace(/^@/, "")}`.replace(/\./g, "\u200B."); +} + +/** `2 posts`, and `1 post` rather than `1 posts`. */ +function count(total: number, noun: string): string { + return `${total.toLocaleString()} ${noun}${total === 1 ? "" : "s"}`; +} + +/** + * What this archive has that the account does not, a line per kind. + * + * Named the way Browse names them, so somebody who reads "2 likes will be + * added" can go to the Likes tab afterwards and find two more than before. + * A kind with nothing to add says nothing at all: a list of zeroes is a list + * of things that are not happening. + * + * What a merge leaves alone is not mentioned either. A merge cannot reach an + * account's settings, schedule or Bluesky connection — the ports have no way + * to — so saying so every time is a sentence that is never news. + */ +function describeMerge(preview: BlueskyArchiveMergePreview): string[] { + const totals = totalMergeChanges(preview.summary); + + if (totals.total === 0) { + return [ + "This archive holds nothing this account does not already have. Importing it will change nothing.", + ]; + } + + const added = preview.summary.addedRecords; + const kinds: [number, string][] = [ + [added.posts, "post"], + [added.reposts, "repost"], + [added.likes, "like"], + [added.bookmarks, "bookmark"], + [added.follows, "follow"], + [added.chats, "chat"], + [added.messages, "message"], + [totals.files.added, "media file"], + ]; + + const lines = kinds + .filter(([total]) => total > 0) + .map(([total, noun]) => `${count(total, noun)} will be added.`); + + if (totals.files.updated > 0) { + // A file this account has a record of but never managed to download. + lines.push(`${count(totals.files.updated, "media file")} will be restored.`); + } + if (totals.records.updated > 0) { + lines.push(`${count(totals.records.updated, "record")} will be filled in.`); + } + if (lines.length === 0) { + // Only supporting rows changed: an author, an attachment, a link preview. + lines.push("Some records will gain details this account is missing."); + } + if (preview.archive.completeness === "incomplete") { + lines.push( + "This archive is missing some files, so a few records will arrive without their media.", + ); + } + return lines; +} + +const styles = StyleSheet.create({ + overlay: { + flex: 1, + backgroundColor: "rgba(0, 0, 0, 0.5)", + justifyContent: "center", + alignItems: "center", + padding: 24, + }, + sheet: { + width: "100%", + maxHeight: "85%", + borderRadius: 16, + padding: 24, + gap: 12, + }, + title: { + fontSize: 18, + fontWeight: "600", + textAlign: "center", + }, + handle: { + fontSize: 16, + fontWeight: "600", + textAlign: "center", + marginTop: -4, + }, + body: { + fontSize: 14, + lineHeight: 20, + }, + scroll: { + maxHeight: 280, + }, + choice: { + gap: 6, + marginBottom: 12, + }, + choiceButton: { + borderWidth: StyleSheet.hairlineWidth, + borderRadius: 12, + padding: 12, + gap: 4, + }, + choiceTitle: { + fontSize: 15, + fontWeight: "600", + }, + settingsPick: { + fontSize: 13, + paddingHorizontal: 4, + }, + action: { + borderRadius: 16, + borderWidth: StyleSheet.hairlineWidth, + paddingVertical: 14, + paddingHorizontal: 16, + }, + actionText: { + fontSize: 16, + fontWeight: "600", + textAlign: "center", + }, +}); diff --git a/components/CydAccountBar.tsx b/components/CydAccountBar.tsx index 55e7433..6f8e324 100644 --- a/components/CydAccountBar.tsx +++ b/components/CydAccountBar.tsx @@ -1,5 +1,6 @@ import { useCallback, useState } from "react"; import { + Alert, Linking, Modal, Platform, @@ -12,8 +13,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { getThemePalette } from "@/constants/theme"; import { useCydAccount } from "@/contexts/CydAccountProvider"; +import { useBlueskyArchiveImport } from "@/hooks/use-bluesky-archive-import"; import { useColorScheme } from "@/hooks/use-color-scheme"; +import { emitLocalAccountsChanged } from "@/services/account-events"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; +import { BlueskyArchiveImportModal } from "./BlueskyArchiveImportModal"; import { CydSignInModal } from "./CydSignInModal"; type CydAccountBarProps = { @@ -35,6 +40,7 @@ export function CydAccountBar({ const [menuVisible, setMenuVisible] = useState(false); const [signInModalVisible, setSignInModalVisible] = useState(false); + const archiveImport = useBlueskyArchiveImport(); const handleMenuPress = useCallback(() => { setMenuVisible(true); @@ -71,8 +77,73 @@ export function CydAccountBar({ onShowOnboarding?.(); }, [onShowOnboarding]); + /** + * Import a Cyd Bluesky archive. + * + * Importing needs no Cyd account and no premium subscription — it is how + * somebody gets their own data back — so the menu item is here whether or + * not they are signed in. Where the archive lands is decided by the Bluesky + * identity inside it, not by anything about the file (#97). + */ + const handleImportArchive = useCallback(() => { + setMenuVisible(false); + void archiveImport.start(); + }, [archiveImport]); + + /** + * Connect the Bluesky account an import just restored. + * + * A restored Bluesky local account holds somebody's data and no authorization + * to act on it, because a Cyd Bluesky archive never carries a Bluesky + * connection. Offering the sign-in here is offering it at the one moment the + * person is already thinking about that account — and signing in is also what + * fills in the display name and avatar an archive cannot carry. + * + * The import is dismissed first: the OAuth session is a full-screen browser, + * and it should not open over a modal reporting an import that has finished. + */ + const handleSignIn = useCallback( + (handle: string) => { + archiveImport.dismiss(); + void (async () => { + try { + await connectBlueskyAccount(handle); + emitLocalAccountsChanged(); + } catch (err) { + Alert.alert( + "Sign in failed", + err instanceof Error + ? err.message + : "Cyd could not connect to Bluesky right now.", + ); + } + })(); + }, + [archiveImport], + ); + + /** + * The import, which outlives the bar that starts it. + * + * The bar hides itself on the account screen, and an import started from the + * accounts list is still running when somebody opens the account it just + * restored. Rendering this outside the bar's own visibility is what keeps + * the progress and the questions on screen rather than leaving the import + * running invisibly. + */ + const importModal = ( + void archiveImport.confirmLargeArchive()} + onConfirmMerge={() => void archiveImport.confirmMerge()} + onSignIn={handleSignIn} + onCancel={archiveImport.cancel} + onDismiss={archiveImport.dismiss} + /> + ); + if (state.isLoading || hidden) { - return null; + return importModal; } return ( @@ -213,6 +284,22 @@ export function CydAccountBar({ { borderColor: palette.icon + "22" }, ]} /> + [ + styles.sheetActionButton, + { + borderColor: palette.icon + "22", + backgroundColor: palette.background, + opacity: pressed ? 0.9 : 1, + }, + ]} + accessibilityRole="button" + > + + Import Bluesky archive + + [ @@ -239,6 +326,7 @@ export function CydAccountBar({ onClose={handleCloseSignInModal} /> + {importModal} ); } diff --git a/components/PostPreview.tsx b/components/PostPreview.tsx index 5afd0be..3b74b1e 100644 --- a/components/PostPreview.tsx +++ b/components/PostPreview.tsx @@ -1,3 +1,4 @@ +import { MaterialIcons } from "@expo/vector-icons"; import * as Clipboard from "expo-clipboard"; import { useVideoPlayer, VideoView } from "expo-video"; import React, { @@ -50,7 +51,14 @@ type ImageItem = { function Avatar({ uri }: { uri?: string | null }) { if (!uri) { - return ; + // Avatars are URLs Cyd never preserves, so an author it knows only from a + // Cyd Bluesky archive has none at all. A person is a better stand-in for + // somebody than an empty circle. + return ( + + + + ); } return ; } @@ -842,6 +850,8 @@ const styles = StyleSheet.create({ avatarPlaceholder: { borderWidth: StyleSheet.hairlineWidth, borderColor: "#0001", + alignItems: "center", + justifyContent: "center", }, bodyText: { fontSize: 17, diff --git a/components/account/identity.tsx b/components/account/identity.tsx new file mode 100644 index 0000000..b74143b --- /dev/null +++ b/components/account/identity.tsx @@ -0,0 +1,84 @@ +import { MaterialIcons } from "@expo/vector-icons"; +import { Image, StyleSheet, View } from "react-native"; + +/** + * What to call a Bluesky local account, and what to show where its avatar goes. + * + * A Bluesky local account restored from a Cyd Bluesky archive usually has + * neither. Avatars are URLs Cyd never preserves (they are not part of a Cyd + * Bluesky archive at all), and a display name nobody ever set arrives as an + * empty string rather than as nothing — the same absence-as-empty-string the + * merge's `populated` rule already refuses to treat as an observation. + * + * Both screens that show an account fell through that gap into a blank name + * and a "?", so the fallbacks live here once: an account is named by its + * handle when it has nothing better, and an account with no avatar gets a + * person rather than a punctuation mark. + */ + +export type AccountIdentity = { + handle: string; + displayName: string | null; +}; + +/** The handle as somebody would write it, whichever form it is stored in. */ +export function accountUsername(handle: string): string { + return handle.startsWith("@") ? handle : `@${handle}`; +} + +/** + * The name to show for an account. + * + * A blank display name is not a name, so it does not get to be one: the handle + * is what is left, and it always names somebody. + */ +export function accountDisplayName(account: AccountIdentity): string { + const displayName = account.displayName?.trim(); + return displayName ? displayName : accountUsername(account.handle); +} + +export type AccountAvatarProps = { + uri: string | null; + size: number; + palette: { icon: string }; +}; + +export function AccountAvatar({ uri, size, palette }: AccountAvatarProps) { + const shape = { + width: size, + height: size, + borderRadius: size / 2, + borderColor: palette.icon + "33", + backgroundColor: palette.icon + "20", + }; + + if (uri) { + return ( + + ); + } + + return ( + + + + ); +} + +const styles = StyleSheet.create({ + avatar: { + borderWidth: StyleSheet.hairlineWidth, + }, + fallback: { + alignItems: "center", + justifyContent: "center", + }, +}); diff --git a/controllers/BaseAccountController.ts b/controllers/BaseAccountController.ts index 3aa2955..67200f6 100644 --- a/controllers/BaseAccountController.ts +++ b/controllers/BaseAccountController.ts @@ -1,12 +1,13 @@ import * as Crypto from "expo-crypto"; import { Directory, File, Paths } from "expo-file-system"; -import { - defaultDatabaseDirectory, - openDatabaseAsync, - type SQLiteDatabase, -} from "expo-sqlite"; +import { defaultDatabaseDirectory, type SQLiteDatabase } from "expo-sqlite"; import { getDatabase } from "@/database"; +import { + accountDatabaseRefCount, + acquireAccountDatabase, + releaseAccountDatabase, +} from "@/database/account-db/shared-handles"; import { getBackupEligibleDataRoot } from "@/services/device-storage"; /** @@ -63,15 +64,10 @@ export class CancelledError extends Error { * configuration storage, and progress tracking. */ export abstract class BaseAccountController { - private static sharedAccountDbs = new Map< - string, - { db: SQLiteDatabase; refCount: number } - >(); - protected accountId: number; protected accountUUID: string; protected db: SQLiteDatabase | null = null; - private sharedDbKey: string | null = null; + private sharedDbKey: { dbDir: string; dbName: string } | null = null; private _disposed = false; protected _progress: TProgress; private paused = false; @@ -265,47 +261,15 @@ export abstract class BaseAccountController { await this.ensureAccountDirectory(); const { dbDir, dbName } = this.getAccountDatabaseSQLiteInfo(); - const dbKey = `${dbDir}::${dbName}`; - - const existing = BaseAccountController.sharedAccountDbs.get(dbKey); - if (existing) { - existing.refCount += 1; - this.sharedDbKey = dbKey; - console.log( - "[BaseAccountController] openAccountDatabase -> reuse shared db", - { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - refCount: existing.refCount, - }, - ); - return existing.db; - } - - console.log( - "[BaseAccountController] openAccountDatabase -> opening new db", - { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - dbDir, - dbName, - }, - ); - const db = await openDatabaseAsync(dbName, {}, dbDir); - await db.execAsync("PRAGMA foreign_keys = ON;"); - - BaseAccountController.sharedAccountDbs.set(dbKey, { db, refCount: 1 }); - this.sharedDbKey = dbKey; - console.log("[BaseAccountController] openAccountDatabase -> opened", { + const db = await acquireAccountDatabase(dbDir, dbName); + this.sharedDbKey = { dbDir, dbName }; + console.log("[BaseAccountController] openAccountDatabase -> acquired", { accountId: this.accountId, accountType: this.getAccountType(), accountUUID: this.accountUUID, - dbKey, - refCount: 1, + dbDir, + dbName, + refCount: accountDatabaseRefCount(dbDir, dbName), }); return db; @@ -401,7 +365,7 @@ export abstract class BaseAccountController { } const dbToRelease = this.db; - const dbKey = this.sharedDbKey; + const shared = this.sharedDbKey; this.db = null; this.sharedDbKey = null; @@ -410,44 +374,27 @@ export abstract class BaseAccountController { accountId: this.accountId, accountType: this.getAccountType(), accountUUID: this.accountUUID, - dbKey, + ...shared, }); - if (dbKey) { - const entry = BaseAccountController.sharedAccountDbs.get(dbKey); - if (entry) { - const beforeRefCount = entry.refCount; - entry.refCount -= 1; - console.log( - "[BaseAccountController] cleanup -> shared refCount decremented", - { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - beforeRefCount, - afterRefCount: entry.refCount, - }, - ); - if (entry.refCount <= 0) { - BaseAccountController.sharedAccountDbs.delete(dbKey); - console.log("[BaseAccountController] cleanup -> closing shared db", { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - }); - await entry.db.closeAsync(); - } - return; - } + if (shared) { + await releaseAccountDatabase(shared.dbDir, shared.dbName); + console.log("[BaseAccountController] cleanup -> released", { + accountId: this.accountId, + accountType: this.getAccountType(), + accountUUID: this.accountUUID, + ...shared, + refCount: accountDatabaseRefCount(shared.dbDir, shared.dbName), + }); + return; } + // A handle that did not come from the shared map is this controller's + // alone, so closing it is closing it for nobody else. console.log("[BaseAccountController] cleanup -> closing direct db", { accountId: this.accountId, accountType: this.getAccountType(), accountUUID: this.accountUUID, - dbKey, }); await dbToRelease.closeAsync(); } diff --git a/controllers/BlueskyAccountController.ts b/controllers/BlueskyAccountController.ts index ef51808..b361c0d 100644 --- a/controllers/BlueskyAccountController.ts +++ b/controllers/BlueskyAccountController.ts @@ -55,6 +55,7 @@ import { type SaveAndDeleteJobOptions, type SaveJobOptions, } from "./bluesky/job-types"; +import { upsertProfileRow } from "./bluesky/post-persistence"; import { BlueskyRateLimiter, type ApiRequestFn } from "./bluesky/rate-limiter"; import type { BlueskyDatabaseStats, @@ -404,6 +405,28 @@ export class BlueskyAccountController extends BaseAccountController { + if (!this.db) { + return; + } + const profile = await this.getProfile(); + if (!profile) { + return; + } + await upsertProfileRow(this.db, profile); + } + /** * Get database statistics */ diff --git a/controllers/bluesky/post-persistence.ts b/controllers/bluesky/post-persistence.ts index fba1946..b50d2ef 100644 --- a/controllers/bluesky/post-persistence.ts +++ b/controllers/bluesky/post-persistence.ts @@ -15,6 +15,50 @@ type FeedRecordInfo = | { kind: "post"; record: AppBskyFeedPost.Record } | { kind: "repost"; record: AppBskyFeedRepost.Record }; +/** + * Write down what Bluesky currently says about somebody. + * + * Browse renders a record's author out of this table, so it is also what Cyd + * knows about an identity when it is offline. Saving posts refreshes it as a + * side effect of saving their author; anything else that learns a fresher + * profile — signing in, most of all, for an account restored from a Cyd + * Bluesky archive that could not carry an avatar — writes it here too. + * + * It takes the four fields it stores rather than a particular profile view, so + * the detailed profile an account fetches about itself fits as well as the + * basic one that arrives attached to a post. + */ +export type ProfileRowSource = Pick< + AppBskyActorDefs.ProfileViewBasic, + "did" | "handle" | "displayName" | "avatar" +>; + +export async function upsertProfileRow( + db: SQLiteDatabase, + profile: ProfileRowSource +): Promise { + const now = Date.now(); + + await db.runAsync( + `INSERT INTO profile ( + did, handle, displayName, avatarUrl, savedAt, updatedAt + ) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(did) DO UPDATE SET + handle = excluded.handle, + displayName = excluded.displayName, + avatarUrl = excluded.avatarUrl, + updatedAt = excluded.updatedAt;`, + [ + profile.did, + profile.handle, + profile.displayName ?? null, + profile.avatar ?? null, + now, + now, + ] + ); +} + export interface PostPersistenceOptions { viewerLiked?: number; viewerReposted?: number; @@ -251,26 +295,7 @@ export class PostPersistence { db: SQLiteDatabase, profile: AppBskyActorDefs.ProfileViewBasic ): Promise { - const now = Date.now(); - - await db.runAsync( - `INSERT INTO profile ( - did, handle, displayName, avatarUrl, savedAt, updatedAt - ) VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT(did) DO UPDATE SET - handle = excluded.handle, - displayName = excluded.displayName, - avatarUrl = excluded.avatarUrl, - updatedAt = excluded.updatedAt;`, - [ - profile.did, - profile.handle, - profile.displayName ?? null, - profile.avatar ?? null, - now, - now, - ] - ); + await upsertProfileRow(db, profile); } private async downloadAndSaveMedia( diff --git a/database/account-db/__tests__/shared-handles.test.ts b/database/account-db/__tests__/shared-handles.test.ts new file mode 100644 index 0000000..b140362 --- /dev/null +++ b/database/account-db/__tests__/shared-handles.test.ts @@ -0,0 +1,109 @@ +const opened: { path: string; closeAsync: jest.Mock; execAsync: jest.Mock }[] = + []; + +jest.mock("expo-sqlite", () => ({ + openDatabaseAsync: jest.fn(async (dbName: string, _options, dbDir: string) => { + const db = { + path: `${dbDir}::${dbName}`, + closeAsync: jest.fn(async () => {}), + execAsync: jest.fn(async () => {}), + }; + opened.push(db); + return db; + }), +})); + +import { openDatabaseAsync } from "expo-sqlite"; + +import { + accountDatabaseRefCount, + acquireAccountDatabase, + releaseAccountDatabase, +} from "../shared-handles"; + +const DIR = "/files/accounts/bluesky-account"; +const NAME = "data.db"; + +/** + * One handle per account database file. + * + * expo-sqlite hands every caller the same native connection, and every JS + * handle over it can close that connection when it is garbage collected. So + * "open it again and close it when done" is not a local decision: it breaks + * whoever else is holding the database, at whatever later moment the + * collector runs. + */ +describe("sharing one handle per account database", () => { + afterEach(async () => { + // Give everything back, so one test's holders are not another's. + while (accountDatabaseRefCount(DIR, NAME) > 0) { + await releaseAccountDatabase(DIR, NAME); + } + opened.length = 0; + jest.clearAllMocks(); + }); + + it("opens the database once, however many holders it has", async () => { + const first = await acquireAccountDatabase(DIR, NAME); + const second = await acquireAccountDatabase(DIR, NAME); + + expect(second).toBe(first); + expect(openDatabaseAsync).toHaveBeenCalledTimes(1); + expect(accountDatabaseRefCount(DIR, NAME)).toBe(2); + }); + + it("does not close a database somebody else is still holding", async () => { + const db = await acquireAccountDatabase(DIR, NAME); + await acquireAccountDatabase(DIR, NAME); + + await releaseAccountDatabase(DIR, NAME); + + expect(db.closeAsync).not.toHaveBeenCalled(); + }); + + it("closes it when the last holder gives it back", async () => { + const db = await acquireAccountDatabase(DIR, NAME); + await acquireAccountDatabase(DIR, NAME); + + await releaseAccountDatabase(DIR, NAME); + await releaseAccountDatabase(DIR, NAME); + + expect(db.closeAsync).toHaveBeenCalledTimes(1); + expect(accountDatabaseRefCount(DIR, NAME)).toBe(0); + }); + + it("opens a fresh one after the last holder let go", async () => { + await acquireAccountDatabase(DIR, NAME); + await releaseAccountDatabase(DIR, NAME); + + await acquireAccountDatabase(DIR, NAME); + + expect(openDatabaseAsync).toHaveBeenCalledTimes(2); + }); + + it("gives two callers arriving at once the same handle", async () => { + const [first, second] = await Promise.all([ + acquireAccountDatabase(DIR, NAME), + acquireAccountDatabase(DIR, NAME), + ]); + + expect(second).toBe(first); + expect(openDatabaseAsync).toHaveBeenCalledTimes(1); + }); + + it("keeps databases for different accounts apart", async () => { + const mine = await acquireAccountDatabase(DIR, NAME); + const theirs = await acquireAccountDatabase("/files/accounts/other", NAME); + + expect(theirs).not.toBe(mine); + + await releaseAccountDatabase("/files/accounts/other", NAME); + expect(mine.closeAsync).not.toHaveBeenCalled(); + }); + + it("ignores a release from somebody who never acquired", async () => { + await expect( + releaseAccountDatabase("/files/accounts/never-opened", NAME), + ).resolves.toBeUndefined(); + }); +}); diff --git a/database/account-db/shared-handles.ts b/database/account-db/shared-handles.ts new file mode 100644 index 0000000..2fe3921 --- /dev/null +++ b/database/account-db/shared-handles.ts @@ -0,0 +1,117 @@ +import { openDatabaseAsync, type SQLiteDatabase } from "expo-sqlite"; + +/** + * One open handle per account database file, shared for as long as anybody + * wants it. + * + * expo-sqlite keeps one native connection per path and hands the same one to + * every caller that opens it with the same options — but each JS handle also + * *owns* that connection. Its native object is a `SharedRef` whose + * `sharedObjectDidRelease` closes the connection, and that runs when the JS + * handle is garbage collected, no matter who else is still holding one. So a + * second `openDatabaseAsync` for a database the app already has open is not a + * second connection. It is a promise that somebody's queries will start + * failing with + * + * Call to function 'NativeDatabase.prepareAsync' has been rejected. + * → Caused by: java.lang.NullPointerException + * + * at whatever later moment the collector happens to run — which is why it + * looks like an unrelated screen breaking minutes after the work that caused + * it. + * + * Everything that opens an account database goes through here: one handle per + * file, lent out as often as it is asked for, and closed once — when the last + * holder gives it back. + */ + +type SharedHandle = { + db: SQLiteDatabase; + refCount: number; + /** Serializes opens, so two callers at once cannot make two connections. */ + opening: Promise; +}; + +const handles = new Map(); + +function keyFor(dbDir: string, dbName: string): string { + return `${dbDir}::${dbName}`; +} + +/** + * Borrow the handle for an account database, opening it if nobody has it. + * + * Every caller must hand it back with `releaseAccountDatabase`, and none may + * close it themselves: closing a borrowed handle closes it for its other + * holders too. + */ +export async function acquireAccountDatabase( + dbDir: string, + dbName: string, +): Promise { + const key = keyFor(dbDir, dbName); + const existing = handles.get(key); + if (existing) { + existing.refCount += 1; + return existing.opening; + } + + const opening = (async () => { + const db = await openDatabaseAsync(dbName, {}, dbDir); + await db.execAsync("PRAGMA foreign_keys = ON;"); + return db; + })(); + + // Registered before it finishes opening, so a second caller arriving while + // the first is still awaiting waits for that one rather than starting its + // own. + const handle: SharedHandle = { + db: undefined as unknown as SQLiteDatabase, + refCount: 1, + opening, + }; + handles.set(key, handle); + + try { + handle.db = await opening; + } catch (err) { + handles.delete(key); + throw err; + } + return handle.db; +} + +/** + * Give a handle back, closing it when the last holder does. + * + * Releasing one nobody is holding is a no-op rather than an error: a caller + * cleaning up after a failure should not have to know whether it got as far + * as acquiring. + */ +export async function releaseAccountDatabase( + dbDir: string, + dbName: string, +): Promise { + const key = keyFor(dbDir, dbName); + const handle = handles.get(key); + if (!handle) { + return; + } + + handle.refCount -= 1; + if (handle.refCount > 0) { + return; + } + + handles.delete(key); + const db = await handle.opening.catch(() => null); + await db?.closeAsync(); +} + +/** How many holders a database has, for tests and for logging. */ +export function accountDatabaseRefCount( + dbDir: string, + dbName: string, +): number { + return handles.get(keyFor(dbDir, dbName))?.refCount ?? 0; +} diff --git a/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md b/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md index ce09abc..20c495e 100644 --- a/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md +++ b/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md @@ -1,3 +1,11 @@ # Reconcile duplicate DIDs before enforcing uniqueness -Cyd Mobile migration detects existing local accounts that share a Bluesky DID and flags them for explicit reconciliation rather than selecting one silently. The user previews an idempotent union of saved data and chooses the surviving local-account UUID and settings; after duplicates are resolved, mobile enforces one local account per DID so archive imports have an unambiguous destination. +**Superseded on Mobile: the state this describes is unreachable here.** + +The original decision was that Cyd Mobile migration would detect existing Bluesky local accounts sharing a Bluesky DID and flag them for explicit reconciliation — the person previews an idempotent union of Bluesky saved data and chooses the surviving local-account UUID and Bluesky account settings — rather than selecting one silently, after which one local account per DID is enforced so a Bluesky archive import has an unambiguous destination. + +No Mobile migration ever performed that detection, and none could have needed to. `bsky_account.did` has carried a unique index since the same migration that added the column, in the same statement list and so in the same transaction, which means no Mobile database has ever held one Bluesky identity in two Bluesky local accounts. Every path that writes an account reuses the row the DID or handle already names, and Bluesky archive restore refuses an identity this installation holds and merges instead. Restoring an OS backup restores the index with it, so it does not produce the state either. The unique index permits several rows with no DID, but an account whose Bluesky identity is unknown is not a duplicate of anything. + +So Mobile does not carry reconciliation. `chooseBlueskyArchiveImportDestination` refuses an archive it cannot place rather than choosing between two accounts, because a database holding one identity twice is a database Cyd did not build and has no way to reason about. What remains reachable, and is deliberately not handled, is an old Bluesky local account with no DID sitting beside a newer one that has it: nothing proves those are one identity, and guessing from a handle is what the DID exists to avoid. + +This ADR stands for clients whose schema does permit the state. diff --git a/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md new file mode 100644 index 0000000..b9042fa --- /dev/null +++ b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md @@ -0,0 +1,3 @@ +# Preview a recovery merge before committing it + +Cyd Mobile splits a Bluesky archive merge into a preview that reads the prepared Cyd Bluesky archive and works out every row it would write, and a commit that carries that preview out, so nobody imports an archive without being told what it would do. The preview counts what it would add, a line for each kind of Bluesky saved record in the words Bluesky browse uses for them, rather than naming each record: Mobile has no Bluesky local deletion, so a Bluesky saved record missing from a Bluesky local account is one the account never had rather than one somebody chose to be rid of, and there is nothing for them to recognise in a list. Naming each record becomes worth its screen again if Mobile ever lets somebody remove Bluesky saved data without removing it from Bluesky; the plan already separates the records it would add from the ones it would enrich, so that would be a presentation change over rows it has in hand. The commit re-reads the Bluesky local account instead of trusting the preview's copy, so work that ran in between is merged rather than overwritten, and committing the same Cyd Bluesky archive again writes nothing. diff --git a/hooks/__tests__/use-bluesky-archive-import.test.ts b/hooks/__tests__/use-bluesky-archive-import.test.ts new file mode 100644 index 0000000..d5b0d5b --- /dev/null +++ b/hooks/__tests__/use-bluesky-archive-import.test.ts @@ -0,0 +1,166 @@ +import { act, renderHook, waitFor } from "@testing-library/react-native"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { + createDiskBlueskyArchiveIntakeEnvironment, + createNodeBlueskyArchiveRestoreEnvironment, +} from "@/testUtils/archiveEnvironments"; +import { + useBlueskyArchiveImport, + type BlueskyArchiveImportRuntime, +} from "../use-bluesky-archive-import"; + +/** + * The import as somebody drives it: pick a file, watch it work, decide. + * + * The runtime is the seam — the picker, intake, restore and merge all come in + * from outside — so this runs the real archive services over the committed + * fixture and only stands in for the phone. What it is here to hold down is + * the ordering: an archive for an identity this device does not have is + * restored without asking, one it does have waits for a decision, and walking + * away in the middle leaves nothing behind and nothing on screen. + */ + +const FIXTURE = path.join( + __dirname, + "../../testUtils/fixtures/bluesky-archive/complete.cyd", +); + +jest.setTimeout(120_000); + +type Harness = { + root: string; + runtime: BlueskyArchiveImportRuntime; + stagingParent: string; +}; + +function harnessFor(): Harness { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-import-hook-")); + const stagingParent = path.join(root, "intake"); + const environment = createNodeBlueskyArchiveRestoreEnvironment({ + root: path.join(root, "app"), + }); + let intakes = 0; + + return { + root, + stagingParent, + runtime: { + pickArchive: async () => ({ uri: `file://${FIXTURE}` }), + intake: createDiskBlueskyArchiveIntakeEnvironment(stagingParent), + restore: environment, + merge: environment, + newIntakeId: () => `intake-${(intakes += 1)}`, + }, + }; +} + +/** + * The hook opens the picked file itself, through the device reader. Under Node + * there is no such reader, so the fixture is served from memory instead. + */ +jest.mock("@/services/archive-import", () => { + const actual = jest.requireActual< + typeof import("@/services/archive-import") + >("@/services/archive-import"); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodeFs = require("node:fs") as typeof import("node:fs"); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const fixtures = require("@/testUtils/archiveFixtures") as typeof import("@/testUtils/archiveFixtures"); + return { + ...actual, + openBlueskyArchiveByteReader: (uri: string) => + fixtures.createMemoryByteReader( + new Uint8Array(nodeFs.readFileSync(uri.replace("file://", ""))), + ), + }; +}); + +describe("importing a Cyd Bluesky archive from the menu", () => { + let harness: Harness; + + beforeEach(() => { + harness = harnessFor(); + }); + + afterEach(() => { + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + it("restores an identity this device does not have, without asking", async () => { + const { result } = renderHook(() => + useBlueskyArchiveImport({ + runtime: harness.runtime, + }), + ); + + await act(async () => { + await result.current.start(); + }); + + await waitFor(() => { + expect(result.current.state.status).toBe("done"); + }); + expect(result.current.state).toMatchObject({ + title: "Restored", + handle: "glittertop-cyd.bsky.social", + // A restored account has no Bluesky connection, so this is where one is + // offered. + offerSignIn: true, + }); + // Staging is the import's working state, and the import is over. + expect(fs.readdirSync(harness.stagingParent)).toEqual([]); + }); + + it("waits for a decision before merging into an account it already has", async () => { + const { result } = renderHook(() => + useBlueskyArchiveImport({ + runtime: harness.runtime, + }), + ); + + await act(async () => { + await result.current.start(); + }); + await act(async () => { + await result.current.start(); + }); + + expect(result.current.state.status).toBe("reviewing"); + + await act(async () => { + await result.current.confirmMerge(); + }); + + expect(result.current.state).toMatchObject({ + status: "done", + lines: ["This archive held nothing that account did not already have."], + }); + }); + + it("leaves nothing on screen or in staging when somebody walks away", async () => { + const { result } = renderHook(() => + useBlueskyArchiveImport({ + runtime: harness.runtime, + }), + ); + + await act(async () => { + await result.current.start(); + }); + // A second import of the same identity stops to be reviewed, which is the + // moment somebody is most likely to change their mind. + const merging = act(async () => { + await result.current.start(); + }); + act(() => { + result.current.cancel(); + }); + await merging; + + expect(result.current.state.status).toBe("idle"); + expect(fs.readdirSync(harness.stagingParent)).toEqual([]); + }); +}); diff --git a/hooks/use-accounts.ts b/hooks/use-accounts.ts index ba30215..f3e1d30 100644 --- a/hooks/use-accounts.ts +++ b/hooks/use-accounts.ts @@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useFocusEffect } from "expo-router/react-navigation"; import { type AccountListItem, listAccounts } from "@/database/accounts"; +import { onLocalAccountsChanged } from "@/services/account-events"; export type UseAccountsResult = { accounts: AccountListItem[]; @@ -54,5 +55,9 @@ export function useAccounts(): UseAccountsResult { }, [refresh]), ); + // An import can add or remove an account while this screen keeps focus, so + // focus alone is not enough to keep the list honest (#97). + useEffect(() => onLocalAccountsChanged(() => void refresh()), [refresh]); + return { accounts, loading, error, refresh }; } diff --git a/hooks/use-bluesky-archive-import.ts b/hooks/use-bluesky-archive-import.ts new file mode 100644 index 0000000..8d3894b --- /dev/null +++ b/hooks/use-bluesky-archive-import.ts @@ -0,0 +1,520 @@ +import * as Crypto from "expo-crypto"; +import * as DocumentPicker from "expo-document-picker"; +import { useCallback, useRef, useState } from "react"; + +import { + cancelBlueskyArchiveIntake, + createBlueskyArchiveIntakeEnvironment, + openBlueskyArchiveByteReader, + runBlueskyArchiveIntake, + type BlueskyArchiveIntakeEnvironment, + type PreparedBlueskyArchive, +} from "@/services/archive-import"; +import { + chooseBlueskyArchiveImportDestination, + commitBlueskyArchiveMerge, + createBlueskyArchiveMergeEnvironment, + previewBlueskyArchiveMerge, + totalMergeChanges, + type BlueskyArchiveMergeEnvironment, + type BlueskyArchiveMergePreview, + type BlueskyArchiveMergeResult, +} from "@/services/archive-merge"; +import { + createBlueskyArchiveRestoreEnvironment, + restoreBlueskyArchiveAccount, + type BlueskyArchiveRestoreEnvironment, + type LocalAccountIdentity, +} from "@/services/archive-restore"; +import { emitLocalAccountsChanged } from "@/services/account-events"; + +/** + * Importing a Cyd Bluesky archive, from the menu to the account. + * + * This is the entry point #93 removed and #97 owns again, and it is one thing + * rather than two because routing a picked archive and merging one are the + * same decision: intake reports the Bluesky identity's DID, and whether the + * import creates a Bluesky local account or merges into one follows from + * whether this installation already holds it. + * + * What is deliberately *not* here is the behaviour #91 ruled out. Nothing + * reads the picked file's name, and nothing is unpacked before the archive has + * been inspected — both belong to intake now, which verifies every payload + * against the manifest before it lands in staging. + * + * The person is asked before anything irreversible: to confirm an unusually + * large archive, and to agree to what a merge would add. Cancelling at either + * point takes the staging with it. + */ + +export type BlueskyArchiveImportState = + | { status: "idle" } + | { + status: "working"; + message: string; + /** Fraction done, or null while there is nothing meaningful to show. */ + fraction: number | null; + cancellable: boolean; + } + | { status: "needs-confirmation"; message: string } + | { + status: "reviewing"; + preview: BlueskyArchiveMergePreview; + handle: string; + } + | { + status: "done"; + title: string; + /** + * The account the import ended in, kept apart from the title so it can + * be shown on its own line: a handle is one unbroken token, and a title + * that has to wrap around one breaks it wherever it runs out of room. + */ + handle: string; + lines: string[]; + /** + * Whether to offer a Bluesky connection from here. + * + * A restored Bluesky local account has none — a Cyd Bluesky archive + * never carries one — and this is the moment somebody is thinking about + * that account, so it is the moment worth asking. A merge leaves the + * account's existing connection alone and has nothing to offer. + */ + offerSignIn: boolean; + } + | { status: "failed"; message: string }; + +/** The device capabilities an import needs, gathered so tests can stand in. */ +export type BlueskyArchiveImportRuntime = { + pickArchive(): Promise<{ uri: string } | null>; + intake: BlueskyArchiveIntakeEnvironment; + restore: BlueskyArchiveRestoreEnvironment; + merge: BlueskyArchiveMergeEnvironment; + newIntakeId(): string; +}; + +function createDeviceRuntime(): BlueskyArchiveImportRuntime { + return { + pickArchive: async () => { + // No filename validation, and no type filter narrow enough to hide a + // real archive: what the file *is* is settled by reading it (#91). + const picked = await DocumentPicker.getDocumentAsync({ + copyToCacheDirectory: true, + multiple: false, + }); + if (picked.canceled || !picked.assets?.[0]) { + return null; + } + return { uri: picked.assets[0].uri }; + }, + intake: createBlueskyArchiveIntakeEnvironment(), + restore: createBlueskyArchiveRestoreEnvironment(), + merge: createBlueskyArchiveMergeEnvironment(), + newIntakeId: () => Crypto.randomUUID(), + }; +} + +type Session = { + intakeId: string; + sourceUri: string; + confirmedLargeArchive: boolean; + /** Set once intake ends *prepared*, so a later step can reach the staging. */ + prepared: PreparedBlueskyArchive | null; +}; + +function messageFor(error: unknown): string { + return error instanceof Error + ? error.message + : "Cyd could not import that archive."; +} + +function plural(count: number, noun: string): string { + return `${count.toLocaleString()} ${noun}${count === 1 ? "" : "s"}`; +} + +/** + * What a merge did, a line per kind of thing it did it to. + * + * The same headings the preview used, in the past tense: somebody who agreed + * to "3 posts will be added" should be told that 3 posts were. + */ +function describeMergeResult(result: BlueskyArchiveMergeResult): string[] { + if (result.written === 0) { + return ["This archive held nothing that account did not already have."]; + } + + const totals = totalMergeChanges(result.summary); + const added = result.summary.addedRecords; + const kinds: [number, string][] = [ + [added.posts, "post"], + [added.reposts, "repost"], + [added.likes, "like"], + [added.bookmarks, "bookmark"], + [added.follows, "follow"], + [added.chats, "chat"], + [added.messages, "message"], + [totals.files.added, "media file"], + ]; + + const lines = kinds + .filter(([total]) => total > 0) + .map(([total, noun]) => `${plural(total, noun)} added.`); + + if (totals.files.updated > 0) { + lines.push(`${plural(totals.files.updated, "media file")} restored.`); + } + if (totals.records.updated > 0) { + lines.push(`${plural(totals.records.updated, "record")} filled in.`); + } + if (lines.length === 0) { + lines.push("Some records gained details this account was missing."); + } + return lines; +} + +export function useBlueskyArchiveImport( + options: { + runtime?: BlueskyArchiveImportRuntime; + } = {}, +) { + const { runtime } = options; + const [state, setState] = useState({ + status: "idle", + }); + const runtimeRef = useRef( + runtime ?? null, + ); + const sessionRef = useRef(null); + /** + * Which import the person is actually in. + * + * Every step of an import is asynchronous and none of them can be called + * back: reading an archive off the device, or working out what a merge would + * do, runs to completion whatever happens on screen. Walking away moves the + * count on, and a step that finishes afterwards finds it has been left + * behind and says nothing — otherwise a cancelled import would reappear, + * pointing at staging it no longer has. + */ + const generationRef = useRef(0); + + const settle = useCallback( + (generation: number, next: BlueskyArchiveImportState): boolean => { + if (generationRef.current !== generation) { + return false; + } + setState(next); + return true; + }, + [], + ); + + const importRuntime = useCallback((): BlueskyArchiveImportRuntime => { + if (!runtimeRef.current) { + runtimeRef.current = createDeviceRuntime(); + } + return runtimeRef.current; + }, []); + + /** Abandon an import and take its staging with it (AC: nothing left behind). */ + const discardStaging = useCallback(() => { + const session = sessionRef.current; + if (!session) { + return; + } + try { + cancelBlueskyArchiveIntake(importRuntime().intake, session.intakeId); + } catch (error) { + console.warn("[archive-import] could not clear staging", error); + } + sessionRef.current = null; + }, [importRuntime]); + + const runRestore = useCallback( + async ( + prepared: PreparedBlueskyArchive, + environment: BlueskyArchiveRestoreEnvironment, + generation: number, + ): Promise => { + settle(generation, { + status: "working", + message: "Restoring the account…", + fraction: null, + cancellable: false, + }); + + const result = await restoreBlueskyArchiveAccount(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + onProgress: (progress) => + settle(generation, { + status: "working", + message: "Restoring the account…", + fraction: + progress.totalAssets > 0 + ? progress.restoredAssets / progress.totalAssets + : null, + cancellable: false, + }), + }); + + sessionRef.current = null; + emitLocalAccountsChanged(); + settle(generation, { + status: "done", + title: "Restored", + handle: result.handle, + offerSignIn: true, + lines: [ + `${plural(result.counts.posts, "post")}, ${plural(result.counts.likes, "like")}, ${plural(result.counts.chats, "chat")}.`, + `${plural(result.assets.restored, "file")} restored${result.assets.missing > 0 ? `, ${result.assets.missing} missing` : ""}.`, + "You can browse all of it now. Cyd needs a Bluesky connection before it can save or delete anything for this account.", + ...(result.uuidRemapping ? [result.uuidRemapping.reason] : []), + ], + }); + }, + [settle], + ); + + const openMergePreview = useCallback( + async ( + prepared: PreparedBlueskyArchive, + environment: BlueskyArchiveMergeEnvironment, + account: LocalAccountIdentity, + generation: number, + ): Promise => { + settle(generation, { + status: "working", + message: "Working out what this archive would add…", + fraction: null, + cancellable: true, + }); + + const preview = await previewBlueskyArchiveMerge(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account, + }); + + settle(generation, { + status: "reviewing", + preview, + handle: account.handle ?? preview.accountDid, + }); + }, + [settle], + ); + + /** Where this archive goes, decided by the DID intake reported. */ + const route = useCallback( + async ( + prepared: PreparedBlueskyArchive, + ports: Pick, + generation: number, + ): Promise => { + const identities = + await ports.merge.listLocalAccountIdentities(); + const destination = chooseBlueskyArchiveImportDestination( + prepared.metadata.accountDid, + identities, + ); + + if (destination.kind === "restore") { + await runRestore(prepared, ports.restore, generation); + return; + } + await openMergePreview( + prepared, + ports.merge, + destination.account, + generation, + ); + }, + [openMergePreview, runRestore], + ); + + const run = useCallback( + async (session: Session, generation: number): Promise => { + const { intake, restore, merge } = importRuntime(); + sessionRef.current = session; + + settle(generation, { + status: "working", + message: "Reading the archive…", + fraction: null, + cancellable: true, + }); + + const outcome = await runBlueskyArchiveIntake(intake, { + intakeId: session.intakeId, + sourceUri: session.sourceUri, + openReader: async () => + openBlueskyArchiveByteReader(session.sourceUri), + confirmLargeArchive: session.confirmedLargeArchive, + // Intake asks between payloads, so walking away stops the extraction + // itself rather than only what it reports. + shouldCancel: () => generationRef.current !== generation, + onProgress: (progress) => + settle(generation, { + status: "working", + message: "Reading the archive…", + fraction: + progress.totalBytes > 0 + ? progress.preparedBytes / progress.totalBytes + : null, + cancellable: true, + }), + }); + + if (outcome.status === "cancelled") { + sessionRef.current = null; + settle(generation, { status: "idle" }); + return; + } + if (outcome.status === "rejected") { + // Intake clears staging for an archive it blames, and keeps it for a + // failure it blames the device for, so that freeing space and trying + // again resumes. Nothing offers to resume from here, so a rejection + // ends the import and takes any staging with it either way. + discardStaging(); + settle(generation, { status: "failed", message: outcome.message }); + return; + } + if (outcome.status === "needs-confirmation") { + settle(generation, { + status: "needs-confirmation", + message: outcome.message, + }); + return; + } + + if (generationRef.current !== generation) { + // Somebody walked away while the last of the archive was being read. + // Intake finished anyway, so the staging it prepared is this import's + // to clear. + discardStaging(); + return; + } + + sessionRef.current = { ...session, prepared: outcome }; + await route(outcome, { restore, merge }, generation); + }, + [discardStaging, importRuntime, route, settle], + ); + + /** Pick the archive and take it as far as it can go without a decision. */ + const start = useCallback(async (): Promise => { + const generation = (generationRef.current += 1); + try { + const picked = await importRuntime().pickArchive(); + if (!picked) { + return; + } + await run( + { + intakeId: importRuntime().newIntakeId(), + sourceUri: picked.uri, + confirmedLargeArchive: false, + prepared: null, + }, + generation, + ); + } catch (error) { + discardStaging(); + settle(generation, { status: "failed", message: messageFor(error) }); + } + }, [discardStaging, importRuntime, run, settle]); + + const confirmLargeArchive = useCallback(async (): Promise => { + const session = sessionRef.current; + if (!session) { + return; + } + // The same import, carried on: the generation does not move, so cancelling + // still reaches everything this starts. + const generation = generationRef.current; + try { + await run({ ...session, confirmedLargeArchive: true }, generation); + } catch (error) { + discardStaging(); + settle(generation, { status: "failed", message: messageFor(error) }); + } + }, [discardStaging, run, settle]); + + /** Commit a merge the person has looked at. */ + const confirmMerge = useCallback(async (): Promise => { + if (state.status !== "reviewing") { + return; + } + const { preview, handle } = state; + const generation = generationRef.current; + try { + settle(generation, { + status: "working", + message: "Merging the archive…", + fraction: null, + cancellable: false, + }); + const result = await commitBlueskyArchiveMerge( + importRuntime().merge, + preview, + { + onProgress: (progress) => + settle(generation, { + status: "working", + message: "Merging the archive…", + fraction: + progress.totalAssets > 0 + ? progress.mergedAssets / progress.totalAssets + : null, + cancellable: false, + }), + }, + ); + + sessionRef.current = null; + emitLocalAccountsChanged(); + settle(generation, { + status: "done", + title: "Merged into", + handle, + offerSignIn: false, + lines: describeMergeResult(result), + }); + } catch (error) { + discardStaging(); + settle(generation, { status: "failed", message: messageFor(error) }); + } + }, [discardStaging, importRuntime, settle, state]); + + /** + * Walk away: nothing has been written, and nothing stays staged. + * + * Moving the generation on is what makes this final. A step already in + * flight — an archive being read, a merge being worked out — cannot be + * stopped mid-call, but it can be made to report to nobody. + */ + const cancel = useCallback((): void => { + generationRef.current += 1; + discardStaging(); + setState({ status: "idle" }); + }, [discardStaging]); + + const dismiss = useCallback((): void => { + generationRef.current += 1; + sessionRef.current = null; + setState({ status: "idle" }); + }, []); + + return { + state, + start, + confirmLargeArchive, + confirmMerge, + cancel, + dismiss, + }; +} diff --git a/jest-setup.ts b/jest-setup.ts index e25cf88..28591f1 100644 --- a/jest-setup.ts +++ b/jest-setup.ts @@ -188,6 +188,44 @@ jest.mock("expo-crypto", () => { }; }); +// Mock expo-device and expo-notifications: nothing under test is a phone, and +// no test may put a notifications prompt anywhere near itself. Tests about +// push notifications mock these again with the behaviour they need. +jest.mock("expo-device", () => ({ + __esModule: true, + isDevice: false, +})); + +jest.mock("expo-notifications", () => ({ + __esModule: true, + PermissionStatus: { + GRANTED: "granted", + DENIED: "denied", + UNDETERMINED: "undetermined", + }, + AndroidImportance: { HIGH: "high" }, + getPermissionsAsync: jest.fn(() => Promise.resolve({ status: "denied" })), + requestPermissionsAsync: jest.fn(() => Promise.resolve({ status: "denied" })), + setNotificationChannelAsync: jest.fn(), + getExpoPushTokenAsync: jest.fn(), + addNotificationReceivedListener: jest.fn(() => ({ remove: jest.fn() })), + addNotificationResponseReceivedListener: jest.fn(() => ({ + remove: jest.fn(), + })), + setNotificationHandler: jest.fn(), +})); + +// Mock expo-localization: only the calendar's time zone is ever read. +jest.mock("expo-localization", () => ({ + getCalendars: jest.fn(() => [{ timeZone: "UTC" }]), +})); + +// Mock expo-document-picker: tests never open a real file picker, and an +// import that is cancelled is the default because it touches nothing. +jest.mock("expo-document-picker", () => ({ + getDocumentAsync: jest.fn(() => Promise.resolve({ canceled: true })), +})); + // Mock expo-file-system jest.mock("expo-file-system", () => { const fileContents = new Map(); diff --git a/package-lock.json b/package-lock.json index 9c16a3c..d806f7f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "expo-crypto": "~57.0.0", "expo-dev-client": "~57.0.5", "expo-device": "~57.0.0", + "expo-document-picker": "^57.0.2", "expo-font": "~57.0.0", "expo-haptics": "~57.0.0", "expo-iap": "^4.3.6", @@ -10358,6 +10359,15 @@ "expo": "*" } }, + "node_modules/expo-document-picker": { + "version": "57.0.2", + "resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-57.0.2.tgz", + "integrity": "sha512-vVBbBNg0piMJUIxjB+DR6JaZZpcSl90ZUoywLA/EgNHTfRkZW+9axP97UxM2a0Zm0W6WfH3cLzzGAEfP9OKGwg==", + "license": "MIT", + "peerDependencies": { + "expo": "*" + } + }, "node_modules/expo-file-system": { "version": "57.0.0", "resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-57.0.0.tgz", diff --git a/package.json b/package.json index 0d5e16f..6e4c5f8 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "expo-crypto": "~57.0.0", "expo-dev-client": "~57.0.5", "expo-device": "~57.0.0", + "expo-document-picker": "^57.0.2", "expo-font": "~57.0.0", "expo-haptics": "~57.0.0", "expo-iap": "^4.3.6", diff --git a/services/__tests__/bluesky-sign-in.test.ts b/services/__tests__/bluesky-sign-in.test.ts new file mode 100644 index 0000000..b376df3 --- /dev/null +++ b/services/__tests__/bluesky-sign-in.test.ts @@ -0,0 +1,109 @@ +jest.mock("@/services/bluesky-oauth", () => ({ + authenticateBlueskyAccount: jest.fn(), +})); + +jest.mock("@/services/bluesky-account-auth-status", () => ({ + verifyBlueskyAccountAuthStatus: jest.fn(async () => "authenticated"), +})); + +const mockRefreshOwnProfile = jest.fn(async () => {}); + +jest.mock("@/controllers", () => ({ + ACCOUNT_AUTH_STATUS: { authenticated: "authenticated", signedOut: "signedOut" }, + withBlueskyController: jest.fn( + async ( + _accountId: number, + _accountUUID: string, + fn: (controller: unknown) => Promise, + ) => fn({ refreshOwnProfile: mockRefreshOwnProfile }), + ), +})); + +jest.mock("@/services/analytics", () => ({ trackEvent: jest.fn() })); + +import { withBlueskyController } from "@/controllers"; +import type { AccountListItem } from "@/database/accounts"; +import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; +import { authenticateBlueskyAccount } from "@/services/bluesky-oauth"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; + +const ACCOUNT = { + id: 7, + uuid: "account-uuid", + handle: "glittertop-cyd.bsky.social", + did: "did:plc:yn45xekh5kqrat27w6rmafcg", +} as AccountListItem; + +describe("signing in to a Bluesky local account", () => { + beforeEach(() => { + jest.clearAllMocks(); + (authenticateBlueskyAccount as jest.Mock).mockResolvedValue(ACCOUNT); + }); + + /** + * The trap this exists for: whether Cyd can act on an account is cached in + * that account's own database, and an unforced check returns the cached + * "signed out" without ever reading the connection. An account restored from + * a Cyd Bluesky archive has never held either, so authorizing it and + * stopping there leaves it asking to be authorized again. + */ + it("refreshes the account's cached auth status, not only its connection", async () => { + const signIn = await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(signIn).toEqual({ account: ACCOUNT, status: "authenticated" }); + expect(withBlueskyController).toHaveBeenCalledWith( + ACCOUNT.id, + ACCOUNT.uuid, + expect.any(Function), + ); + expect(verifyBlueskyAccountAuthStatus).toHaveBeenCalledWith( + expect.anything(), + ACCOUNT, + { force: true }, + ); + }); + + it("still reports a sign-in when the status could not be refreshed", async () => { + // The connection is stored by then, so failing to write down what it means + // is not a failed sign-in. + (withBlueskyController as jest.Mock).mockRejectedValueOnce( + new Error("no controller"), + ); + + const signIn = await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + // Authorized, but nothing wrote down what that means, so the account is + // reported as it will actually read until some forced check succeeds. + expect(signIn).toEqual({ account: ACCOUNT, status: "signedOut" }); + }); + + /** + * The account row learns the fresh handle, display name and avatar, but + * Browse renders authors out of the account's own database — which, for an + * account restored from an archive, still holds what the archive carried. + */ + it("writes down the profile it just fetched, for Browse to show", async () => { + await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(mockRefreshOwnProfile).toHaveBeenCalledTimes(1); + }); + + it("does not try to read a profile it could not authenticate for", async () => { + (verifyBlueskyAccountAuthStatus as jest.Mock).mockResolvedValueOnce( + "signedOut", + ); + + await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(mockRefreshOwnProfile).not.toHaveBeenCalled(); + }); + + it("does not authorize twice", async () => { + await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(authenticateBlueskyAccount).toHaveBeenCalledTimes(1); + expect(authenticateBlueskyAccount).toHaveBeenCalledWith( + "glittertop-cyd.bsky.social", + ); + }); +}); diff --git a/services/account-events.ts b/services/account-events.ts new file mode 100644 index 0000000..fd4a94d --- /dev/null +++ b/services/account-events.ts @@ -0,0 +1,30 @@ +type LocalAccountsListener = () => void; + +const listeners = new Set(); + +/** + * Notice when the set of Bluesky local accounts changes. + * + * A Bluesky archive import can create an account, or fold two of them into + * one, from a menu that lives outside the accounts list (#97). The list + * refreshes when it regains focus, which never happens for a modal opened over + * it, so it listens here instead. Modelled on `services/auth-events.ts`. + */ +export function onLocalAccountsChanged( + listener: LocalAccountsListener, +): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function emitLocalAccountsChanged(): void { + for (const listener of listeners) { + try { + listener(); + } catch (err) { + console.warn("[account-events] listener error", err); + } + } +} diff --git a/services/archive-merge/__tests__/destination.test.ts b/services/archive-merge/__tests__/destination.test.ts new file mode 100644 index 0000000..1d75ba3 --- /dev/null +++ b/services/archive-merge/__tests__/destination.test.ts @@ -0,0 +1,62 @@ +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +import { chooseBlueskyArchiveImportDestination } from "../destination"; + +/** + * Where a picked Cyd Bluesky archive is committed. + * + * Routing is the whole of the decision #97 owns: the same picked file becomes + * a restore, a merge, or a reconciliation depending only on what this + * installation already holds for the archive's DID. + */ + +const identity = ( + uuid: string, + did: string | null, + handle = "somebody.bsky.social", +): LocalAccountIdentity => ({ uuid, did, handle }); + +describe("choosing where a Cyd Bluesky archive is committed", () => { + it("restores an identity this installation does not hold", () => { + const destination = chooseBlueskyArchiveImportDestination( + "did:plc:archive", + [identity("uuid-a", "did:plc:someone-else")], + ); + + expect(destination).toEqual({ kind: "restore" }); + }); + + it("merges into the one Bluesky local account holding the DID", () => { + const existing = identity("uuid-a", "did:plc:archive", "glitter.bsky.social"); + + const destination = chooseBlueskyArchiveImportDestination( + "did:plc:archive", + [identity("uuid-b", "did:plc:someone-else"), existing], + ); + + expect(destination).toEqual({ kind: "merge", account: existing }); + }); + + it("matches on the DID rather than the handle a local account is listed under", () => { + const destination = chooseBlueskyArchiveImportDestination("did:plc:archive", [ + identity("uuid-a", null, "glitter.bsky.social"), + ]); + + expect(destination).toEqual({ kind: "restore" }); + }); + + /** + * `bsky_account.did` is unique and has been since the column existed, so no + * database Cyd Mobile built can reach this. If one ever does, an archive has + * no unambiguous destination and there is nothing sensible to pick. + */ + it("refuses rather than guess when two local accounts hold the DID", () => { + expect(() => + chooseBlueskyArchiveImportDestination("did:plc:archive", [ + identity("uuid-a", "did:plc:archive"), + identity("uuid-c", "did:plc:someone-else"), + identity("uuid-b", "did:plc:archive"), + ]), + ).toThrow(/more than one Bluesky account/); + }); +}); diff --git a/services/archive-merge/__tests__/merge-plan.test.ts b/services/archive-merge/__tests__/merge-plan.test.ts new file mode 100644 index 0000000..546da7e --- /dev/null +++ b/services/archive-merge/__tests__/merge-plan.test.ts @@ -0,0 +1,484 @@ +import type { MobilePostWrite } from "@/services/archive-restore"; + +import { planBlueskyArchiveMerge, totalMergeChanges } from "../merge-plan"; +import type { BlueskyArchiveMergeSummary } from "../merge-plan"; +import type { ExistingAccountRows, ExistingPostRow } from "../rows"; + +/** + * The recovery union, as a decision about rows. + * + * Everything the merge promises somebody — that importing twice changes + * nothing, that a Cyd Bluesky archive never blanks out what this device knows, + * that data the archive says nothing about survives — is decided here, with no + * database in sight. A row the plan does not carry is a row nothing writes. + */ + +const ARCHIVE_DID = "did:plc:archive"; + +function post(overrides: Partial = {}): MobilePostWrite { + return { + uri: "at://did:plc:archive/app.bsky.feed.post/one", + cid: "cid-one", + authorDid: ARCHIVE_DID, + text: "hello", + facetsJSON: null, + embedType: null, + embedJSON: null, + langs: null, + isReply: 0, + replyParentUri: null, + replyRootUri: null, + isQuote: 0, + quotedPostUri: null, + isRepost: 0, + repostUri: null, + repostCid: null, + originalPostUri: null, + likeCount: 0, + repostCount: 0, + replyCount: 0, + quoteCount: 0, + viewerLiked: 0, + likeUri: null, + viewerReposted: 0, + viewerBookmarked: 0, + createdAt: "2026-01-01T00:00:00.000Z", + savedAt: 1_000, + deletedPostAt: null, + deletedRepostAt: null, + deletedLikeAt: null, + deletedBookmarkAt: null, + ...overrides, + }; +} + +/** An archive's row, as it arrives at the plan: no local-only columns set. */ +function archived(row: MobilePostWrite): ExistingPostRow { + return { ...row, preserve: 0 }; +} + +function existing( + overrides: Partial = {}, +): ExistingAccountRows { + return { + profiles: [], + posts: [], + postMedia: [], + postExternals: [], + bookmarks: [], + follows: [], + conversations: [], + messages: [], + mediaAssets: [], + ...overrides, + }; +} + +function incoming( + overrides: Partial = {}, +): ExistingAccountRows { + return { + profiles: [], + posts: [], + postMedia: [], + postExternals: [], + bookmarks: [], + follows: [], + conversations: [], + messages: [], + mediaAssets: [], + ...overrides, + }; +} + +describe("planning a Cyd Bluesky archive merge", () => { + it("adds a record the account no longer holds, and counts it", () => { + const plan = planBlueskyArchiveMerge( + existing(), + incoming({ posts: [archived(post({ text: "a post deleted from Cyd" }))] }), + ARCHIVE_DID, + ); + + expect(plan.posts).toHaveLength(1); + expect(plan.posts[0]).toMatchObject({ + uri: "at://did:plc:archive/app.bsky.feed.post/one", + text: "a post deleted from Cyd", + preserve: 0, + }); + expect(plan.summary.posts).toEqual({ added: 1, updated: 0, unchanged: 0 }); + expect(plan.summary.addedRecords.posts).toBe(1); + }); + + it("writes nothing when the archive holds what the account already holds", () => { + const plan = planBlueskyArchiveMerge( + existing({ posts: [{ ...post(), preserve: 0 }] }), + incoming({ posts: [archived(post())] }), + ARCHIVE_DID, + ); + + expect(plan.posts).toEqual([]); + expect(plan.summary.posts).toEqual({ added: 0, updated: 0, unchanged: 1 }); + }); + it("does not let a quieter archive blank out what the account knows", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { + ...post({ text: "the full text", langs: "en", savedAt: 5_000 }), + preserve: 0, + }, + ], + }), + incoming({ posts: [archived(post({ text: "", langs: null, savedAt: 9_000 }))] }), + ARCHIVE_DID, + ); + + expect(plan.posts).toEqual([]); + expect(plan.summary.posts.unchanged).toBe(1); + }); + + it("takes the newer observation when both sides hold a value", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { + ...post({ text: "before an edit", likeCount: 1, savedAt: 5_000 }), + preserve: 0, + }, + ], + }), + incoming({ + posts: [ + archived(post({ text: "after an edit", likeCount: 4, savedAt: 9_000 })), + ], + }), + ARCHIVE_DID, + ); + + expect(plan.posts[0]).toMatchObject({ + text: "after an edit", + likeCount: 4, + // The union of when Cyd held it is when it first did. + savedAt: 5_000, + }); + expect(plan.summary.posts).toEqual({ added: 0, updated: 1, unchanged: 0 }); + }); + + it("does not let an archive that counted nothing zero out a count", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { + ...post({ likeCount: 5, replyCount: 2, savedAt: 5_000 }), + preserve: 0, + }, + ], + }), + incoming({ + posts: [ + archived( + post({ likeCount: 0, replyCount: 3, savedAt: 9_000 }), + ), + ], + }), + ARCHIVE_DID, + ); + + expect(plan.posts[0]).toMatchObject({ likeCount: 5, replyCount: 3 }); + }); + + it("keeps a like the archive was taken before, and takes one it was taken after", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { ...post({ viewerLiked: 1, savedAt: 9_000 }), preserve: 0 }, + { + ...post({ + uri: "at://did:plc:archive/app.bsky.feed.post/two", + viewerLiked: 0, + savedAt: 9_000, + }), + preserve: 0, + }, + ], + }), + incoming({ + posts: [ + archived(post({ viewerLiked: 0, savedAt: 1_000 })), + archived( + post({ + uri: "at://did:plc:archive/app.bsky.feed.post/two", + viewerLiked: 1, + savedAt: 1_000, + }), + ), + ], + }), + ARCHIVE_DID, + ); + + expect(plan.posts.map((row) => [row.uri, row.viewerLiked])).toEqual([ + ["at://did:plc:archive/app.bsky.feed.post/one", 1], + ["at://did:plc:archive/app.bsky.feed.post/two", 1], + ]); + }); + + it("keeps a source deletion either side observed, at the earlier time", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [{ ...post({ deletedPostAt: null }), preserve: 0 }], + }), + incoming({ posts: [archived(post({ deletedPostAt: 4_000 }))] }), + ARCHIVE_DID, + ); + + expect(plan.posts[0]).toMatchObject({ deletedPostAt: 4_000 }); + }); + + it("never clears a post the person chose to preserve", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [{ ...post({ text: "kept", savedAt: 1_000 }), preserve: 1 }], + }), + incoming({ posts: [archived(post({ text: "kept again", savedAt: 9_000 }))] }), + ARCHIVE_DID, + ); + + expect(plan.posts[0]).toMatchObject({ text: "kept again", preserve: 1 }); + }); + + it("leaves data the archive says nothing about out of the plan entirely", () => { + const untouched = { + ...post({ uri: "at://did:plc:archive/app.bsky.feed.post/local" }), + preserve: 0, + }; + + const plan = planBlueskyArchiveMerge( + existing({ posts: [untouched] }), + incoming({ posts: [] }), + ARCHIVE_DID, + ); + + expect(plan.posts).toEqual([]); + expect(plan.summary.posts).toEqual({ added: 0, updated: 0, unchanged: 0 }); + }); + + it("upgrades a failed download when the archive brought the file", () => { + const plan = planBlueskyArchiveMerge( + existing({ + mediaAssets: [ + { + contentCid: "bafy-one", + mediaType: "image", + mimeType: "image/jpeg", + byteLength: null, + localPath: null, + sourceUrl: "https://cdn.bsky.app/one.jpg", + sourceDid: ARCHIVE_DID, + sourceMetadataJSON: null, + downloadState: "failed", + lastError: "Network request failed", + attemptCount: 3, + downloadedAt: null, + }, + ], + }), + incoming({ + mediaAssets: [ + { + contentCid: "bafy-one", + mediaType: "image", + mimeType: "image/jpeg", + byteLength: 1_024, + localPath: "file:///accounts/media/sha256-abc", + sourceUrl: "https://cdn.bsky.app/one.jpg", + sourceDid: ARCHIVE_DID, + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + attemptCount: 0, + downloadedAt: 7_000, + }, + ], + }), + ARCHIVE_DID, + ); + + expect(plan.mediaAssets[0]).toMatchObject({ + downloadState: "complete", + localPath: "file:///accounts/media/sha256-abc", + lastError: null, + // What this device has already been through with the file is its own. + attemptCount: 3, + }); + }); + + it("does not trade a file this device holds for one it cannot open", () => { + const stored = { + contentCid: "bafy-one", + mediaType: "image" as const, + mimeType: "image/jpeg", + byteLength: 1_024, + localPath: "file:///accounts/media/sha256-abc", + sourceUrl: "https://cdn.bsky.app/one.jpg", + sourceDid: ARCHIVE_DID, + sourceMetadataJSON: null, + downloadState: "complete" as const, + lastError: null, + attemptCount: 0, + downloadedAt: 7_000, + }; + + const plan = planBlueskyArchiveMerge( + existing({ mediaAssets: [stored] }), + incoming({ + mediaAssets: [ + { + ...stored, + localPath: null, + byteLength: null, + downloadState: "failed", + lastError: "This file was not included in the archive.", + attemptCount: 0, + downloadedAt: null, + }, + ], + }), + ARCHIVE_DID, + ); + + expect(plan.mediaAssets).toEqual([]); + }); +}); + +/** + * Counting the added rows the way the Browse tabs count them, so a preview can + * say "2 likes" to somebody who will go and look at the Likes tab. + */ +describe("naming what a merge would add", () => { + const added = (rows: MobilePostWrite[]) => + planBlueskyArchiveMerge( + existing(), + incoming({ posts: rows.map(archived) }), + ARCHIVE_DID, + ).summary.addedRecords; + + it("counts the account's own posts as posts", () => { + expect(added([post()])).toMatchObject({ posts: 1, likes: 0, reposts: 0 }); + }); + + it("counts somebody else's post the account liked as a like, not a post", () => { + const liked = post({ + uri: "at://did:plc:someone/app.bsky.feed.post/two", + authorDid: "did:plc:someone", + viewerLiked: 1, + }); + + expect(added([liked])).toMatchObject({ posts: 0, likes: 1 }); + }); + + it("counts a repost as a repost", () => { + const reposted = post({ + uri: "at://did:plc:someone/app.bsky.feed.post/three", + authorDid: "did:plc:someone", + isRepost: 1, + viewerReposted: 1, + }); + + expect(added([reposted])).toMatchObject({ posts: 0, reposts: 1 }); + }); + + it("counts the account's own post that it also liked under both, as Browse does", () => { + // Browse shows this row in the Posts tab and in the Likes tab, so a + // preview that claimed one or the other would disagree with what somebody + // finds when they go and look. + expect(added([post({ viewerLiked: 1 })])).toMatchObject({ + posts: 1, + likes: 1, + }); + }); + + it("says nothing about a kind with nothing to add", () => { + expect(added([])).toEqual({ + posts: 0, + reposts: 0, + likes: 0, + bookmarks: 0, + follows: 0, + chats: 0, + messages: 0, + }); + }); +}); + +/** + * Whether a merge would change anything, asked of the summary rather than of + * whichever tables somebody remembered to look at. + */ +describe("adding a merge summary up", () => { + const none = { added: 0, updated: 0, unchanged: 0 }; + const summary = ( + overrides: Partial = {}, + ): BlueskyArchiveMergeSummary => ({ + profiles: none, + posts: none, + postMedia: none, + postExternals: none, + bookmarks: none, + follows: none, + conversations: none, + messages: none, + mediaAssets: none, + addedRecords: { + posts: 0, + reposts: 0, + likes: 0, + bookmarks: 0, + follows: 0, + chats: 0, + messages: 0, + }, + ...overrides, + }); + + it("is nothing only when every table is", () => { + expect(totalMergeChanges(summary()).total).toBe(0); + }); + + it("counts a recovered file, which no record table mentions", () => { + const totals = totalMergeChanges( + summary({ mediaAssets: { added: 0, updated: 1, unchanged: 4 } }), + ); + + expect(totals.files).toEqual({ added: 0, updated: 1 }); + expect(totals.records).toEqual({ added: 0, updated: 0 }); + expect(totals.total).toBe(1); + }); + + it("counts the rows a record needs to render, under their own heading", () => { + const totals = totalMergeChanges( + summary({ + profiles: { added: 1, updated: 0, unchanged: 2 }, + postExternals: { added: 0, updated: 1, unchanged: 0 }, + }), + ); + + expect(totals.context).toEqual({ added: 1, updated: 1 }); + expect(totals.total).toBe(2); + }); + + it("groups every kind of record together", () => { + const totals = totalMergeChanges( + summary({ + posts: { added: 2, updated: 1, unchanged: 0 }, + messages: { added: 3, updated: 0, unchanged: 0 }, + conversations: { added: 1, updated: 0, unchanged: 0 }, + bookmarks: { added: 1, updated: 0, unchanged: 0 }, + follows: { added: 1, updated: 0, unchanged: 0 }, + }), + ); + + expect(totals.records).toEqual({ added: 8, updated: 1 }); + expect(totals.total).toBe(9); + }); +}); diff --git a/services/archive-merge/__tests__/merge.test.ts b/services/archive-merge/__tests__/merge.test.ts new file mode 100644 index 0000000..0026a98 --- /dev/null +++ b/services/archive-merge/__tests__/merge.test.ts @@ -0,0 +1,392 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { DatabaseSync } from "node:sqlite"; + +import { + buildTotalCountQuery, + getTotalCountParams, + type BrowseType, +} from "@/components/account/browse-shared"; +import { + runBlueskyArchiveIntake, + type PreparedBlueskyArchive, +} from "@/services/archive-import"; +import { restoreBlueskyArchiveAccount } from "@/services/archive-restore"; +import { createMemoryByteReader } from "@/testUtils/archiveFixtures"; +import { + createDiskBlueskyArchiveIntakeEnvironment, + createNodeBlueskyArchiveRestoreEnvironment, + type NodeRestoreEnvironment, +} from "@/testUtils/archiveEnvironments"; + +import { + commitBlueskyArchiveMerge, + previewBlueskyArchiveMerge, +} from "../merge"; +import { totalMergeChanges } from "../merge-plan"; + +/** + * Importing a Cyd Bluesky archive into the Bluesky local account that already + * holds its identity. + * + * The archive is the committed real-data fixture, and the account it merges + * into is one this repo's own restore built out of that same fixture — so the + * interesting cases are the ones a recovery actually meets: importing twice, + * importing after somebody deleted things from Cyd, and importing over an + * account whose settings and schedule are none of the archive's business. + */ + +const FIXTURE_DIRECTORY = path.join( + __dirname, + "../../../testUtils/fixtures/bluesky-archive", +); +const ACCOUNT_DID = "did:plc:yn45xekh5kqrat27w6rmafcg"; + +jest.setTimeout(120_000); + +function fixtureBytes(name: string): Uint8Array { + return new Uint8Array(fs.readFileSync(path.join(FIXTURE_DIRECTORY, name))); +} + +type Harness = { + root: string; + environment: NodeRestoreEnvironment; + accountUuid: string; + accountId: number; + database: DatabaseSync; + /** Stage a fixture again, the way a second import would. */ + prepare: ( + intakeId: string, + name?: string, + ) => Promise; +}; + +async function stage( + root: string, + intakeId: string, + name = "complete.cyd", +): Promise { + const outcome = await runBlueskyArchiveIntake( + createDiskBlueskyArchiveIntakeEnvironment(path.join(root, "intake")), + { + intakeId, + sourceUri: `file:///fixtures/${name}`, + openReader: async () => createMemoryByteReader(fixtureBytes(name)), + }, + ); + if (outcome.status !== "prepared") { + throw new Error(`intake did not prepare ${name}: ${outcome.status}`); + } + return outcome; +} + +/** An account restored from the fixture, ready to have the fixture merged in. */ +async function restoredAccount(fixture = "complete.cyd"): Promise { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-merge-")); + const environment = createNodeBlueskyArchiveRestoreEnvironment({ + root: path.join(root, "app"), + }); + const prepared = await stage(root, "intake-restore", fixture); + const restored = await restoreBlueskyArchiveAccount(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + }); + + return { + root, + environment, + accountUuid: restored.accountUuid, + accountId: restored.accountId, + database: environment.openRestoredAccountDatabase(restored.accountUuid), + prepare: (intakeId, name) => stage(root, intakeId, name), + }; +} + +function browseCount(database: DatabaseSync, type: BrowseType): number { + const row = database + .prepare(buildTotalCountQuery(type)) + .get(...(getTotalCountParams(type, ACCOUNT_DID) as never[])) as { + count: number; + }; + return row.count; +} + +function countRows(database: DatabaseSync, table: string): number { + return ( + database.prepare(`SELECT COUNT(*) AS count FROM ${table};`).get() as { + count: number; + } + ).count; +} + +function identity(harness: Harness) { + return { + uuid: harness.accountUuid, + did: ACCOUNT_DID, + handle: "glittertop-cyd.bsky.social", + }; +} + +async function mergeFixture(harness: Harness, intakeId: string) { + const prepared = await harness.prepare(intakeId); + const preview = await previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: identity(harness), + }); + const result = await commitBlueskyArchiveMerge(harness.environment, preview); + return { prepared, preview, result }; +} + +describe("merging a Cyd Bluesky archive into an account that holds its identity", () => { + let harness: Harness; + + beforeAll(async () => { + harness = await restoredAccount(); + }); + + afterAll(() => { + harness.database.close(); + harness.environment.close(); + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + it("changes nothing when the same archive is imported a second time", async () => { + const before = { + posts: browseCount(harness.database, "posts"), + likes: browseCount(harness.database, "likes"), + rows: countRows(harness.database, "post"), + media: countRows(harness.database, "media_asset"), + }; + + const { preview, result } = await mergeFixture(harness, "intake-again"); + + expect(preview.summary.posts).toEqual({ + added: 0, + updated: 0, + unchanged: before.rows, + }); + expect(result.written).toBe(0); + expect({ + posts: browseCount(harness.database, "posts"), + likes: browseCount(harness.database, "likes"), + rows: countRows(harness.database, "post"), + media: countRows(harness.database, "media_asset"), + }).toEqual(before); + }); + + it("leaves no staging behind once the merge is committed", async () => { + const { prepared } = await mergeFixture(harness, "intake-staging"); + + expect(fs.existsSync(prepared.stagingRoot)).toBe(false); + }); + + it("brings back records the account no longer holds, counting them first", async () => { + const doomed = ( + harness.database + .prepare( + `SELECT uri FROM post WHERE authorDid = ? ORDER BY uri LIMIT 3;`, + ) + .all(ACCOUNT_DID) as { uri: string }[] + ).map((row) => row.uri); + const before = browseCount(harness.database, "posts"); + for (const uri of doomed) { + harness.database.prepare("DELETE FROM post_media WHERE postUri = ?;").run(uri); + harness.database.prepare("DELETE FROM post_external WHERE postUri = ?;").run(uri); + harness.database.prepare("DELETE FROM post WHERE uri = ?;").run(uri); + } + expect(browseCount(harness.database, "posts")).toBe(before - doomed.length); + + const prepared = await harness.prepare("intake-restoration"); + const preview = await previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: identity(harness), + }); + + // What the preview says out loud: three posts, and nothing else. + expect(preview.summary.addedRecords).toMatchObject({ + posts: doomed.length, + reposts: 0, + likes: 0, + messages: 0, + }); + // Nothing is written until somebody has agreed to the preview. + expect(browseCount(harness.database, "posts")).toBe(before - doomed.length); + + await commitBlueskyArchiveMerge(harness.environment, preview); + + expect(browseCount(harness.database, "posts")).toBe(before); + // The three that came back are the three that went, not three of + // something else that happens to add up. + expect( + ( + harness.database + .prepare( + `SELECT uri FROM post WHERE uri IN (${doomed.map(() => "?").join(", ")}) ORDER BY uri;`, + ) + .all(...doomed) as { uri: string }[] + ).map((row) => row.uri), + ).toEqual([...doomed].sort()); + }); + + it("keeps the account's own identifier, settings and schedule", async () => { + const main = harness.environment.mainDatabase; + main + .prepare( + `UPDATE bsky_account + SET settingSavePosts = 0, + settingDeleteLikes = 1, + settingScheduleDeletion = 1, + settingScheduleDeletionFrequency = 'monthly', + settingScheduleDeletionTime = '07:30' + WHERE id = (SELECT bskyAccountID FROM account WHERE uuid = ?);`, + ) + .run(harness.accountUuid); + const settingsBefore = main + .prepare( + `SELECT b.* FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + ) + .get(harness.accountUuid); + + const { result } = await mergeFixture(harness, "intake-settings"); + + expect(result.accountUuid).toBe(harness.accountUuid); + expect( + main + .prepare( + `SELECT b.* FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + ) + .get(harness.accountUuid), + ).toEqual(settingsBefore); + }); + + it("keeps a post the person chose to preserve", async () => { + const [{ uri }] = harness.database + .prepare(`SELECT uri FROM post ORDER BY uri LIMIT 1;`) + .all() as { uri: string }[]; + harness.database + .prepare("UPDATE post SET preserve = 1 WHERE uri = ?;") + .run(uri); + + await mergeFixture(harness, "intake-preserve"); + + expect( + ( + harness.database + .prepare("SELECT preserve FROM post WHERE uri = ?;") + .get(uri) as { preserve: number } + ).preserve, + ).toBe(1); + }); + + it("refuses an archive belonging to a different Bluesky identity", async () => { + const prepared = await harness.prepare("intake-mismatch"); + + await expect( + previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: { + uuid: harness.accountUuid, + did: "did:plc:somebody-else", + handle: "somebody.bsky.social", + }, + }), + ).rejects.toThrow(/identity/i); + }); +}); + +/** + * The recovery somebody actually performs: exporting again once a download + * that had failed has finished, and importing that over the account the first + * export built. + * + * The committed fixtures are exactly this pair — `incomplete.cyd` differs from + * `complete.cyd` by one asset and nothing else — so this is the merge whose + * only change is a file, and the one that used to describe itself as changing + * nothing at all. + */ +describe("merging an archive carrying a file an earlier one could not", () => { + let harness: Harness; + + beforeAll(async () => { + harness = await restoredAccount("incomplete.cyd"); + }); + + afterAll(() => { + harness.database.close(); + harness.environment.close(); + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + function unavailable(): { contentCid: string; localPath: string | null }[] { + return harness.database + .prepare( + `SELECT contentCid, localPath FROM media_asset + WHERE downloadState != 'complete';`, + ) + .all() as { contentCid: string; localPath: string | null }[]; + } + + it("recovers the file, and counts it as a change", async () => { + const missing = unavailable(); + expect(missing).toHaveLength(1); + + const prepared = await harness.prepare("intake-upgrade", "complete.cyd"); + const preview = await previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: identity(harness), + }); + + // Every record is identical across the pair, so a summary read one table + // at a time finds nothing: the file is the whole of the difference. + expect(preview.summary.posts).toMatchObject({ added: 0, updated: 0 }); + expect(preview.summary.messages).toMatchObject({ added: 0, updated: 0 }); + expect(preview.summary.mediaAssets).toMatchObject({ added: 0, updated: 1 }); + expect(totalMergeChanges(preview.summary)).toMatchObject({ + records: { added: 0, updated: 0 }, + files: { added: 0, updated: 1 }, + total: 1, + }); + // Nothing to say about any kind of record: the file is the whole of it. + expect(preview.summary.addedRecords).toEqual({ + posts: 0, + reposts: 0, + likes: 0, + bookmarks: 0, + follows: 0, + chats: 0, + messages: 0, + }); + + const result = await commitBlueskyArchiveMerge(harness.environment, preview); + + expect(result.written).toBe(1); + expect(unavailable()).toEqual([]); + + const restored = harness.database + .prepare("SELECT localPath FROM media_asset WHERE contentCid = ?;") + .get(missing[0].contentCid) as { localPath: string | null }; + expect(restored.localPath).not.toBeNull(); + expect( + fs.existsSync(restored.localPath!.replace(/^file:\/\//, "")), + ).toBe(true); + }); +}); diff --git a/services/archive-merge/account-rows.ts b/services/archive-merge/account-rows.ts new file mode 100644 index 0000000..7ed17f4 --- /dev/null +++ b/services/archive-merge/account-rows.ts @@ -0,0 +1,100 @@ +import type { MergeableAccountDatabase } from "./ports"; +import type { + ExistingAccountRows, + ExistingMediaAssetRow, + ExistingPostRow, + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobileProfileWrite, +} from "./rows"; + +/** + * Reading a Bluesky local account back out in the shape a restore writes it. + * + * This is the mirror of `services/archive-restore/account-writer.ts`, and it + * exists so the merge compares like with like: the archive's side arrives as + * Mobile rows through the translation, and this turns the account's own side + * into the same rows. Columns Mobile fills in for itself — a row id, the + * denormalized aspect ratio — are left out, because nothing in a union has an + * opinion about them. + * + * `viewer*` columns are nullable in Mobile's schema and are read as flags + * here. A null and a zero mean the same thing to browse, and normalizing them + * is what keeps a second import of the same archive from writing rows back + * unchanged. + */ + +const flag = (value: number | null): number => (value === 1 ? 1 : 0); + +export async function readExistingAccountRows( + database: MergeableAccountDatabase, +): Promise { + const posts = await database.all( + `SELECT uri, cid, authorDid, text, facetsJSON, embedType, embedJSON, langs, + isReply, replyParentUri, replyRootUri, isQuote, quotedPostUri, + isRepost, repostUri, repostCid, originalPostUri, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, likeUri, viewerReposted, viewerBookmarked, + createdAt, savedAt, + deletedPostAt, deletedRepostAt, deletedLikeAt, deletedBookmarkAt, + preserve + FROM post ORDER BY uri;`, + ); + + return { + profiles: await database.all( + `SELECT did, handle, displayName, avatarUrl, savedAt, updatedAt + FROM profile ORDER BY did;`, + ), + posts: posts.map((post) => ({ + ...post, + isReply: flag(post.isReply), + isQuote: flag(post.isQuote), + isRepost: flag(post.isRepost), + viewerLiked: flag(post.viewerLiked), + viewerReposted: flag(post.viewerReposted), + viewerBookmarked: flag(post.viewerBookmarked), + preserve: flag(post.preserve), + })), + postMedia: await database.all( + `SELECT postUri, position, mediaType, blobCid, mimeType, alt, + width, height, thumbUrl, fullsizeUrl, playlistUrl, + downloadedAt, assetCid + FROM post_media ORDER BY postUri, position;`, + ), + postExternals: await database.all( + `SELECT postUri, uri, title, description, thumbUrl, thumbLocalPath + FROM post_external ORDER BY postUri;`, + ), + bookmarks: await database.all( + `SELECT subjectUri, postAuthorDid, postAuthorHandle, postText, + postCreatedAt, savedAt, deletedAt + FROM bookmark ORDER BY subjectUri;`, + ), + follows: await database.all( + `SELECT uri, cid, subjectDid, handle, displayName, avatarUrl, + createdAt, savedAt, unfollowedAt + FROM follow ORDER BY uri;`, + ), + conversations: await database.all( + `SELECT convoId, rev, memberDids, muted, lastMessageId, lastMessageText, + lastMessageSentAt, lastMessageSenderDid, savedAt, updatedAt, leftAt + FROM conversation ORDER BY convoId;`, + ), + messages: await database.all( + `SELECT messageId, convoId, rev, senderDid, text, facetsJSON, embedJSON, + sentAt, savedAt, deletedAt + FROM message ORDER BY messageId;`, + ), + mediaAssets: await database.all( + `SELECT contentCid, mediaType, mimeType, byteLength, localPath, sourceUrl, + sourceDid, sourceMetadataJSON, downloadState, lastError, + attemptCount, downloadedAt + FROM media_asset ORDER BY contentCid;`, + ), + }; +} diff --git a/services/archive-merge/destination.ts b/services/archive-merge/destination.ts new file mode 100644 index 0000000..a86378d --- /dev/null +++ b/services/archive-merge/destination.ts @@ -0,0 +1,41 @@ +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +import { BlueskyArchiveMergeError } from "./errors"; + +/** + * Where a picked Cyd Bluesky archive is committed. + * + * Routing a Cyd Bluesky archive and merging one are the same decision, taken + * once: intake reports the Bluesky identity's DID (#95), and whether this + * installation already holds that identity decides everything that follows. + * Nothing here reads the archive's contents, and nothing matches on a handle + * or a local-account UUID — a handle moves between identities, and a UUID is + * this installation's own name for one. + */ +export type BlueskyArchiveImportDestination = + /** No Bluesky local account for this identity: restore a new one (#96). */ + | { kind: "restore" } + /** Exactly one holds it: the archive is a recovery union into that account. */ + | { kind: "merge"; account: LocalAccountIdentity }; + +export function chooseBlueskyArchiveImportDestination( + archiveDid: string, + existing: LocalAccountIdentity[], +): BlueskyArchiveImportDestination { + const holders = existing.filter((account) => account.did === archiveDid); + + if (holders.length === 0) { + return { kind: "restore" }; + } + if (holders.length > 1) { + // `bsky_account.did` is unique and has been since the column existed, so + // this cannot happen to a database Cyd Mobile built. If one ever turns up + // holding an identity twice, the archive has no unambiguous destination + // and saying so beats merging into whichever came back first. + throw new BlueskyArchiveMergeError( + "duplicate-identity", + "This device has more than one Bluesky account for the identity in this archive, so Cyd cannot tell where to import it.", + ); + } + return { kind: "merge", account: holders[0] }; +} diff --git a/services/archive-merge/environment.ts b/services/archive-merge/environment.ts new file mode 100644 index 0000000..faac165 --- /dev/null +++ b/services/archive-merge/environment.ts @@ -0,0 +1,122 @@ +import { Directory, File } from "expo-file-system"; +import type { SQLiteDatabase } from "expo-sqlite"; + +import { buildAccountPaths } from "@/controllers/BaseAccountController"; +import { + applyAccountMigrations, + blueskyAccountMigrations, +} from "@/database/account-db"; +import { + acquireAccountDatabase, + releaseAccountDatabase, +} from "@/database/account-db/shared-handles"; +import { listAccounts } from "@/database/accounts"; +import { openPreparedArchive } from "@/services/archive-restore/environment"; +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +import type { + BlueskyArchiveMergeEnvironment, + MergeableAccountDatabase, +} from "./ports"; + +/** + * The device-backed implementation of the merge ports. + * + * It is the restore adapter's neighbour and shares its staging reader: the + * difference between the two halves of an import is which account the rows go + * into, not how an archive is read. Everything else here is the same three + * things a phone does differently — SQLite, files, and Cyd's own account + * tables — so the merge logic never sees any of them. + */ + +async function openAccountDatabase(accountUuid: string): Promise { + const paths = buildAccountPaths("bluesky", accountUuid); + new Directory(paths.accountDir).create({ + intermediates: true, + idempotent: true, + }); + // Borrowed rather than opened: the app may already hold this database, and a + // second handle over the same connection closes it for the first one when it + // is collected. + const database = await acquireAccountDatabase( + paths.dbDirForSQLite, + paths.dbNameForSQLite, + ); + applyAccountMigrations(database, blueskyAccountMigrations); + return database; +} + +function asMergeableAccountDatabase( + database: SQLiteDatabase, + accountUuid: string, +): MergeableAccountDatabase { + const paths = buildAccountPaths("bluesky", accountUuid); + return { + all: async (sql: string) => database.getAllAsync(sql), + run: async (sql, params) => { + await database.runAsync(sql, params as never[]); + }, + transaction: (work) => database.withTransactionAsync(work), + // Handed back rather than closed. The account screen may be holding this + // very database, and closing a borrowed handle closes it for them too. + close: async () => + releaseAccountDatabase(paths.dbDirForSQLite, paths.dbNameForSQLite), + }; +} + +/** + * Where a media file lives, in the exact form storing it reports back. + * + * A merge previews the rows it would write before it copies any bytes, so the + * predicted path has to be the one `storeAccountMedia` ends up returning — + * otherwise every import would look like it had media to update. Going through + * `File` is what guarantees they agree: the same normalization on both sides. + */ +function mediaUri(accountUuid: string, fileName: string): string { + return new File( + `${buildAccountPaths("bluesky", accountUuid).mediaDir}${fileName}`, + ).uri; +} + +export function createBlueskyArchiveMergeEnvironment(): BlueskyArchiveMergeEnvironment { + return { + openPreparedArchive, + + listLocalAccountIdentities: async (): Promise => + (await listAccounts()).map((account) => ({ + uuid: account.uuid, + did: account.did, + handle: account.handle, + })), + + openAccountDatabase: async (accountUuid) => + asMergeableAccountDatabase( + await openAccountDatabase(accountUuid), + accountUuid, + ), + + storeAccountMedia: async (accountUuid, fileName, write) => { + const paths = buildAccountPaths("bluesky", accountUuid); + new Directory(paths.mediaDir).create({ + intermediates: true, + idempotent: true, + }); + + const file = new File(mediaUri(accountUuid, fileName)); + file.create({ intermediates: true, overwrite: true }); + const handle = file.open(); + let byteLength = 0; + try { + await write((bytes) => { + handle.writeBytes(bytes); + byteLength += bytes.length; + }); + } finally { + handle.close(); + } + return { uri: file.uri, byteLength }; + }, + + accountMediaUri: mediaUri, + }; +} diff --git a/services/archive-merge/errors.ts b/services/archive-merge/errors.ts new file mode 100644 index 0000000..1ed20f4 --- /dev/null +++ b/services/archive-merge/errors.ts @@ -0,0 +1,23 @@ +/** + * Why a prepared Cyd Bluesky archive could not be merged. + * + * Intake has proved the package intact (#95) and the shared version 2 adapter + * raises what it thinks of the interchange database, so what is left here is + * about destinations: an archive pointed at the wrong Bluesky local account, + * or a database holding one Bluesky identity twice, which Mobile's schema does + * not allow and which therefore has no destination at all. The messages are + * written for the person holding the phone. + */ +export type BlueskyArchiveMergeErrorCode = + | "identity-mismatch" + | "duplicate-identity"; + +export class BlueskyArchiveMergeError extends Error { + readonly code: BlueskyArchiveMergeErrorCode; + + constructor(code: BlueskyArchiveMergeErrorCode, message: string) { + super(message); + this.name = "BlueskyArchiveMergeError"; + this.code = code; + } +} diff --git a/services/archive-merge/index.ts b/services/archive-merge/index.ts new file mode 100644 index 0000000..ae546c2 --- /dev/null +++ b/services/archive-merge/index.ts @@ -0,0 +1,48 @@ +/** + * Merging a Cyd Bluesky archive into a Bluesky local account Cyd already has. + * + * A Bluesky archive import is one act with two possible endings: an identity + * this installation does not hold is restored as a new Bluesky local account + * (#96), and one it does hold is merged here. The merge is a recovery union — + * everything either side knows survives, records sharing a stable Bluesky + * identifier collapse into one, and the account's own settings, schedules, + * Bluesky connection and local choices are not the archive's business. + * + * Two things leave this module: where an archive should go, and what merging + * it would do. The union rules, the row reader and the writer are internal, + * and the tests reach for them directly. + */ + +export { chooseBlueskyArchiveImportDestination } from "./destination"; +export type { BlueskyArchiveImportDestination } from "./destination"; +export { createBlueskyArchiveMergeEnvironment } from "./environment"; +export { BlueskyArchiveMergeError } from "./errors"; +export type { BlueskyArchiveMergeErrorCode } from "./errors"; +export { + commitBlueskyArchiveMerge, + previewBlueskyArchiveMerge, +} from "./merge"; +export type { + BlueskyArchiveMergePhase, + BlueskyArchiveMergePreview, + BlueskyArchiveMergeProgress, + BlueskyArchiveMergeRequest, + BlueskyArchiveMergeResult, + MergedAssetSummary, +} from "./merge"; +export { planBlueskyArchiveMerge, totalMergeChanges } from "./merge-plan"; +export type { + BlueskyArchiveMergeCounts, + BlueskyArchiveMergePlan, + BlueskyArchiveMergeSummary, + BlueskyArchiveMergeTotals, +} from "./merge-plan"; +export type { + BlueskyArchiveMergeEnvironment, + MergeableAccountDatabase, +} from "./ports"; +export type { + ExistingAccountRows, + ExistingMediaAssetRow, + ExistingPostRow, +} from "./rows"; diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts new file mode 100644 index 0000000..ebedb63 --- /dev/null +++ b/services/archive-merge/merge-plan.ts @@ -0,0 +1,637 @@ +import { + earliest, + latest, + preferCounted, + preferPopulated, + unionFlag, +} from "./union"; +import type { + ExistingAccountRows, + ExistingMediaAssetRow, + ExistingPostRow, + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobileProfileWrite, +} from "./rows"; + +/** + * The recovery union, decided before anything is written. + * + * A Bluesky archive import into an account this installation already holds is + * a union, not a replacement: every record either side knows about survives, + * records that share a stable Bluesky identifier collapse into one, and an + * archive that is quieter than the account — an older export, a partial one — + * never turns what the account knows back into absence. + * + * The plan is the whole decision. It carries the rows that would change and + * the counts somebody is shown before agreeing to it, so committing is just + * writing what was previewed (AC: "previewed explicitly before commit"). + */ + +export type BlueskyArchiveMergeCounts = { + /** Rows the account does not hold, which the archive brings back. */ + added: number; + /** Rows both sides hold, which the archive has something to add to. */ + updated: number; + unchanged: number; +}; + +/** + * How many of each kind of record a merge would add, named the way Browse + * names them. + * + * Mobile keeps posts, reposts, likes and bookmarks in one table and tells them + * apart by column, so this classifies the rows the same way the Browse tabs + * count them. A row can land under two headings — the account's own post that + * it also liked is both — which is exactly what Browse shows, so agreeing with + * it beats adding up to a tidier total. + */ +export type AddedRecordCounts = { + posts: number; + reposts: number; + likes: number; + bookmarks: number; + follows: number; + chats: number; + messages: number; +}; + +export type BlueskyArchiveMergeSummary = { + profiles: BlueskyArchiveMergeCounts; + posts: BlueskyArchiveMergeCounts; + postMedia: BlueskyArchiveMergeCounts; + postExternals: BlueskyArchiveMergeCounts; + bookmarks: BlueskyArchiveMergeCounts; + follows: BlueskyArchiveMergeCounts; + conversations: BlueskyArchiveMergeCounts; + messages: BlueskyArchiveMergeCounts; + mediaAssets: BlueskyArchiveMergeCounts; + /** The added rows, by the name somebody would give them. */ + addedRecords: AddedRecordCounts; +}; + +/** + * What each table in a summary amounts to, for somebody deciding about it. + * + * A merge summary has one entry per table, and the tables are not equally + * interesting: somebody recognises a post, has no idea what a `post_external` + * is, and thinks of a recovered image as a file rather than a row. Grouping + * them is what lets a preview say something true in one sentence. + * + * The map is exhaustive on purpose. Reading a nine-table summary by hand is + * how a merge that recovers a missing image comes to announce itself as + * changing nothing: whoever adds the tenth table has to say what it is here, + * or this does not compile. + */ +const MERGE_CATEGORIES: Record< + Exclude, + "records" | "files" | "context" +> = { + posts: "records", + bookmarks: "records", + follows: "records", + conversations: "records", + messages: "records", + mediaAssets: "files", + profiles: "context", + postMedia: "context", + postExternals: "context", +}; + +export type BlueskyArchiveMergeTotals = { + /** Records somebody would recognise as theirs. */ + records: { added: number; updated: number }; + /** Media files: one this account never had, or one it failed to download. */ + files: { added: number; updated: number }; + /** What a record needs to render: authors, attachments, link previews. */ + context: { added: number; updated: number }; + /** Every write the plan would make. Zero is the only honest "nothing". */ + total: number; +}; + +/** + * Add a summary up, so that "would this change anything?" has one answer. + * + * Both the preview somebody agrees to and the report afterwards ask it, and a + * merge is only a no-op when every table is: an archive whose single + * difference is the image an earlier export could not carry changes something + * worth being told about. + */ +export function totalMergeChanges( + summary: BlueskyArchiveMergeSummary, +): BlueskyArchiveMergeTotals { + const totals: BlueskyArchiveMergeTotals = { + records: { added: 0, updated: 0 }, + files: { added: 0, updated: 0 }, + context: { added: 0, updated: 0 }, + total: 0, + }; + + for (const [table, group] of Object.entries(MERGE_CATEGORIES) as [ + keyof typeof MERGE_CATEGORIES, + "records" | "files" | "context", + ][]) { + const counts = summary[table]; + totals[group].added += counts.added; + totals[group].updated += counts.updated; + totals.total += counts.added + counts.updated; + } + + return totals; +} + +export type BlueskyArchiveMergePlan = { + profiles: MobileProfileWrite[]; + posts: ExistingPostRow[]; + postMedia: MobilePostMediaWrite[]; + postExternals: MobilePostExternalWrite[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; + mediaAssets: ExistingMediaAssetRow[]; + summary: BlueskyArchiveMergeSummary; +}; + +type TableRules = { + /** The stable Bluesky identifier two copies of a record share. */ + key: (row: Row) => string; + union: (local: Row, incoming: Row) => Row; +}; + +type TableResult = { + writes: Row[]; + counts: BlueskyArchiveMergeCounts; + added: Row[]; +}; + +/** + * Merge one table, writing only what would actually change. + * + * The comparison against the stored row is what makes a repeated import free: + * a union that comes back equal to what is already there produces no write at + * all, so importing the same Cyd Bluesky archive twice is indistinguishable + * from importing it once. + */ +function mergeTable( + local: Row[], + incoming: Row[], + rules: TableRules, +): TableResult { + const stored = new Map(local.map((row) => [rules.key(row), row])); + const writes: Row[] = []; + const added: Row[] = []; + let updated = 0; + let unchanged = 0; + + for (const row of incoming) { + const existing = stored.get(rules.key(row)); + if (!existing) { + writes.push(row); + added.push(row); + continue; + } + const merged = rules.union(existing, row); + if (sameRow(existing, merged)) { + unchanged += 1; + continue; + } + writes.push(merged); + updated += 1; + } + + return { + writes, + added, + counts: { added: added.length, updated, unchanged }, + }; +} + +function sameRow(left: object, right: object): boolean { + const keys = Object.keys(left); + return keys.every( + (key) => + (left as Record)[key] === + (right as Record)[key], + ); +} + +/** + * Union an account's Bluesky saved data with an archive's. + * + * Both sides are the same shape on purpose: what the account holds and what + * the archive carries are compared as the same rows by the same rules, so + * "the same record" cannot come to mean two things. + */ +export function planBlueskyArchiveMerge( + existing: ExistingAccountRows, + incoming: ExistingAccountRows, + /** Whose account this is, which is what makes a post theirs rather than + * somebody else's that they liked. */ + accountDid: string, +): BlueskyArchiveMergePlan { + const profiles = mergeTable(existing.profiles, incoming.profiles, { + key: (row) => row.did, + union: unionProfile, + }); + const posts = mergeTable(existing.posts, incoming.posts, { + key: (row) => row.uri, + union: unionPost, + }); + const postMedia = mergeTable(existing.postMedia, incoming.postMedia, { + key: (row) => `${row.postUri}#${row.position}`, + union: unionPostMedia, + }); + const postExternals = mergeTable( + existing.postExternals, + incoming.postExternals, + { key: (row) => row.postUri, union: unionPostExternal }, + ); + const bookmarks = mergeTable(existing.bookmarks, incoming.bookmarks, { + key: (row) => row.subjectUri, + union: unionBookmark, + }); + const follows = mergeTable(existing.follows, incoming.follows, { + key: (row) => row.uri, + union: unionFollow, + }); + const conversations = mergeTable( + existing.conversations, + incoming.conversations, + { key: (row) => row.convoId, union: unionConversation }, + ); + const messages = mergeTable(existing.messages, incoming.messages, { + key: (row) => row.messageId, + union: unionMessage, + }); + const mediaAssets = mergeTable(existing.mediaAssets, incoming.mediaAssets, { + key: (row) => row.contentCid, + union: unionMediaAsset, + }); + + return { + profiles: profiles.writes, + posts: posts.writes, + postMedia: postMedia.writes, + postExternals: postExternals.writes, + bookmarks: bookmarks.writes, + follows: follows.writes, + conversations: conversations.writes, + messages: messages.writes, + mediaAssets: mediaAssets.writes, + summary: { + profiles: profiles.counts, + posts: posts.counts, + postMedia: postMedia.counts, + postExternals: postExternals.counts, + bookmarks: bookmarks.counts, + follows: follows.counts, + conversations: conversations.counts, + messages: messages.counts, + mediaAssets: mediaAssets.counts, + addedRecords: countAddedRecords(accountDid, { + posts: posts.added, + bookmarks: bookmarks.added, + follows: follows.added, + conversations: conversations.added, + messages: messages.added, + }), + }, + }; +} + +/** + * Count the added rows under the headings Browse uses. + * + * The rules are Browse's own (`buildTotalCountQuery`): a post is one this + * account wrote and did not repost, while a repost, a like and a bookmark are + * any post row carrying that mark. Saying "3 posts and 2 likes" rather than + * "5 records" is only true if it is counted the way the tabs somebody will go + * and look at are counted. + */ +function countAddedRecords( + accountDid: string, + added: { + posts: ExistingPostRow[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; + }, +): AddedRecordCounts { + const posts = added.posts.filter( + (row) => row.authorDid === accountDid && row.isRepost === 0, + ).length; + + return { + posts, + reposts: added.posts.filter((row) => row.viewerReposted === 1).length, + likes: added.posts.filter((row) => row.viewerLiked === 1).length, + // Bookmarks live in their own table as well as on the post row; the table + // is the record, so it is what gets counted. + bookmarks: added.bookmarks.length, + follows: added.follows.length, + chats: added.conversations.length, + messages: added.messages.length, + }; +} + + +function unionProfile( + local: MobileProfileWrite, + incoming: MobileProfileWrite, +): MobileProfileWrite { + const newer = incoming.updatedAt > local.updatedAt; + return { + did: local.did, + handle: preferPopulated(local.handle, incoming.handle, newer), + displayName: preferPopulated(local.displayName, incoming.displayName, newer), + avatarUrl: preferPopulated(local.avatarUrl, incoming.avatarUrl, newer), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + updatedAt: Math.max(local.updatedAt, incoming.updatedAt), + }; +} + +/** + * One post, as both sides know it. + * + * Viewer state is a union rather than a choice: a like or a repost recorded on + * either side is something that happened, and an archive taken before somebody + * liked a post must not un-like it. Deletion timestamps take the earliest + * either side observed, because that is when Bluesky stopped holding it. + */ +function unionPost( + local: ExistingPostRow, + incoming: ExistingPostRow, +): ExistingPostRow { + const newer = incoming.savedAt > local.savedAt; + const metric = (left: number, right: number): number => + preferCounted(left, right, newer); + + return { + uri: local.uri, + cid: preferPopulated(local.cid, incoming.cid, newer), + authorDid: preferPopulated(local.authorDid, incoming.authorDid, newer), + text: preferPopulated(local.text, incoming.text, newer), + facetsJSON: preferPopulated(local.facetsJSON, incoming.facetsJSON, newer), + embedType: preferPopulated(local.embedType, incoming.embedType, newer), + embedJSON: preferPopulated(local.embedJSON, incoming.embedJSON, newer), + langs: preferPopulated(local.langs, incoming.langs, newer), + isReply: unionFlag(local.isReply, incoming.isReply), + replyParentUri: preferPopulated( + local.replyParentUri, + incoming.replyParentUri, + newer, + ), + replyRootUri: preferPopulated( + local.replyRootUri, + incoming.replyRootUri, + newer, + ), + isQuote: unionFlag(local.isQuote, incoming.isQuote), + quotedPostUri: preferPopulated( + local.quotedPostUri, + incoming.quotedPostUri, + newer, + ), + isRepost: unionFlag(local.isRepost, incoming.isRepost), + repostUri: preferPopulated(local.repostUri, incoming.repostUri, newer), + repostCid: preferPopulated(local.repostCid, incoming.repostCid, newer), + originalPostUri: preferPopulated( + local.originalPostUri, + incoming.originalPostUri, + newer, + ), + likeCount: metric(local.likeCount, incoming.likeCount), + repostCount: metric(local.repostCount, incoming.repostCount), + replyCount: metric(local.replyCount, incoming.replyCount), + quoteCount: metric(local.quoteCount, incoming.quoteCount), + viewerLiked: unionFlag(local.viewerLiked, incoming.viewerLiked), + likeUri: preferPopulated(local.likeUri, incoming.likeUri, newer), + viewerReposted: unionFlag(local.viewerReposted, incoming.viewerReposted), + viewerBookmarked: unionFlag( + local.viewerBookmarked, + incoming.viewerBookmarked, + ), + createdAt: preferPopulated(local.createdAt, incoming.createdAt, false), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + deletedPostAt: earliest(local.deletedPostAt, incoming.deletedPostAt), + deletedRepostAt: earliest(local.deletedRepostAt, incoming.deletedRepostAt), + deletedLikeAt: earliest(local.deletedLikeAt, incoming.deletedLikeAt), + deletedBookmarkAt: earliest( + local.deletedBookmarkAt, + incoming.deletedBookmarkAt, + ), + // A person's own "keep this" is a local choice no archive carries, so an + // import can only ever leave it alone. Two duplicate local accounts can + // both carry one, and then either saying "keep" is the answer. + preserve: unionFlag(local.preserve, incoming.preserve), + }; +} + +function unionPostMedia( + local: MobilePostMediaWrite, + incoming: MobilePostMediaWrite, +): MobilePostMediaWrite { + const newer = (incoming.downloadedAt ?? 0) > (local.downloadedAt ?? 0); + return { + postUri: local.postUri, + position: local.position, + mediaType: preferPopulated(local.mediaType, incoming.mediaType, newer), + blobCid: preferPopulated(local.blobCid, incoming.blobCid, newer), + mimeType: preferPopulated(local.mimeType, incoming.mimeType, newer), + alt: preferPopulated(local.alt, incoming.alt, newer), + width: preferPopulated(local.width, incoming.width, newer), + height: preferPopulated(local.height, incoming.height, newer), + thumbUrl: preferPopulated(local.thumbUrl, incoming.thumbUrl, newer), + fullsizeUrl: preferPopulated(local.fullsizeUrl, incoming.fullsizeUrl, newer), + playlistUrl: preferPopulated(local.playlistUrl, incoming.playlistUrl, newer), + downloadedAt: latest(local.downloadedAt, incoming.downloadedAt), + assetCid: preferPopulated(local.assetCid, incoming.assetCid, newer), + }; +} + +function unionPostExternal( + local: MobilePostExternalWrite, + incoming: MobilePostExternalWrite, +): MobilePostExternalWrite { + return { + postUri: local.postUri, + uri: preferPopulated(local.uri, incoming.uri, false), + title: preferPopulated(local.title, incoming.title, false), + description: preferPopulated(local.description, incoming.description, false), + thumbUrl: preferPopulated(local.thumbUrl, incoming.thumbUrl, false), + // A local copy of the thumbnail beats a URL, and beats another local copy + // only if this account does not already have one that works. + thumbLocalPath: preferPopulated( + local.thumbLocalPath, + incoming.thumbLocalPath, + false, + ), + }; +} + +function unionBookmark( + local: MobileBookmarkWrite, + incoming: MobileBookmarkWrite, +): MobileBookmarkWrite { + const newer = incoming.savedAt > local.savedAt; + return { + subjectUri: local.subjectUri, + postAuthorDid: preferPopulated( + local.postAuthorDid, + incoming.postAuthorDid, + newer, + ), + postAuthorHandle: preferPopulated( + local.postAuthorHandle, + incoming.postAuthorHandle, + newer, + ), + postText: preferPopulated(local.postText, incoming.postText, newer), + postCreatedAt: preferPopulated( + local.postCreatedAt, + incoming.postCreatedAt, + newer, + ), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + deletedAt: earliest(local.deletedAt, incoming.deletedAt), + }; +} + +function unionFollow( + local: MobileFollowWrite, + incoming: MobileFollowWrite, +): MobileFollowWrite { + const newer = incoming.savedAt > local.savedAt; + return { + uri: local.uri, + cid: preferPopulated(local.cid, incoming.cid, newer), + subjectDid: preferPopulated(local.subjectDid, incoming.subjectDid, newer), + handle: preferPopulated(local.handle, incoming.handle, newer), + displayName: preferPopulated(local.displayName, incoming.displayName, newer), + avatarUrl: preferPopulated(local.avatarUrl, incoming.avatarUrl, newer), + createdAt: preferPopulated(local.createdAt, incoming.createdAt, false), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + unfollowedAt: earliest(local.unfollowedAt, incoming.unfollowedAt), + }; +} + +function unionConversation( + local: MobileConversationWrite, + incoming: MobileConversationWrite, +): MobileConversationWrite { + const newer = incoming.updatedAt > local.updatedAt; + return { + convoId: local.convoId, + rev: preferPopulated(local.rev, incoming.rev, newer), + memberDids: preferPopulated(local.memberDids, incoming.memberDids, newer), + muted: unionFlag(local.muted, incoming.muted), + lastMessageId: preferPopulated( + local.lastMessageId, + incoming.lastMessageId, + newer, + ), + lastMessageText: preferPopulated( + local.lastMessageText, + incoming.lastMessageText, + newer, + ), + lastMessageSentAt: preferPopulated( + local.lastMessageSentAt, + incoming.lastMessageSentAt, + newer, + ), + lastMessageSenderDid: preferPopulated( + local.lastMessageSenderDid, + incoming.lastMessageSenderDid, + newer, + ), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + updatedAt: Math.max(local.updatedAt, incoming.updatedAt), + leftAt: earliest(local.leftAt, incoming.leftAt), + }; +} + +function unionMessage( + local: MobileMessageWrite, + incoming: MobileMessageWrite, +): MobileMessageWrite { + const newer = incoming.savedAt > local.savedAt; + return { + messageId: local.messageId, + convoId: preferPopulated(local.convoId, incoming.convoId, newer), + rev: preferPopulated(local.rev, incoming.rev, newer), + senderDid: preferPopulated(local.senderDid, incoming.senderDid, newer), + text: preferPopulated(local.text, incoming.text, newer), + facetsJSON: preferPopulated(local.facetsJSON, incoming.facetsJSON, newer), + embedJSON: preferPopulated(local.embedJSON, incoming.embedJSON, newer), + sentAt: preferPopulated(local.sentAt, incoming.sentAt, false), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + deletedAt: earliest(local.deletedAt, incoming.deletedAt), + }; +} + +/** + * One media file, as this account holds it. + * + * A file already on this device is the richest thing either side has, so a + * local copy is never traded for a source URL, and a failed download is + * upgraded the moment an archive turns up with the bytes. + */ +function unionMediaAsset( + local: ExistingMediaAssetRow, + incoming: ExistingMediaAssetRow, +): ExistingMediaAssetRow { + const incomingComplete = incoming.downloadState === "complete"; + const localComplete = local.downloadState === "complete"; + const takeIncoming = incomingComplete && !localComplete; + + return { + contentCid: local.contentCid, + mediaType: preferPopulated(local.mediaType, incoming.mediaType, takeIncoming), + mimeType: preferPopulated(local.mimeType, incoming.mimeType, takeIncoming), + byteLength: preferPopulated( + local.byteLength, + incoming.byteLength, + takeIncoming, + ), + localPath: preferPopulated(local.localPath, incoming.localPath, takeIncoming), + sourceUrl: preferPopulated(local.sourceUrl, incoming.sourceUrl, takeIncoming), + sourceDid: preferPopulated(local.sourceDid, incoming.sourceDid, takeIncoming), + sourceMetadataJSON: preferPopulated( + local.sourceMetadataJSON, + incoming.sourceMetadataJSON, + takeIncoming, + ), + downloadState: takeIncoming ? incoming.downloadState : local.downloadState, + // The account's own record of why a download failed stays until a file + // actually arrives to contradict it. + lastError: takeIncoming ? incoming.lastError : local.lastError, + attemptCount: local.attemptCount, + downloadedAt: takeIncoming + ? incoming.downloadedAt + : latest(local.downloadedAt, incoming.downloadedAt), + }; +} + +/** + * When Cyd first held this. + * + * `savedAt` is the moment something entered Bluesky saved data, so the union + * of two accounts of it is the earlier one. A zero means the archive did not + * say, which is not a claim that it was saved at the epoch. + */ +function earliestObservation(local: number, incoming: number): number { + if (local === 0) { + return incoming; + } + if (incoming === 0) { + return local; + } + return Math.min(local, incoming); +} diff --git a/services/archive-merge/merge-writer.ts b/services/archive-merge/merge-writer.ts new file mode 100644 index 0000000..cebc49b --- /dev/null +++ b/services/archive-merge/merge-writer.ts @@ -0,0 +1,252 @@ +import type { BlueskyArchiveMergePlan } from "./merge-plan"; +import type { MergeableAccountDatabase } from "./ports"; + +/** + * Writing a merged plan into a Bluesky local account. + * + * Almost the same statements as a restore's, with one difference that matters: + * `INSERT OR REPLACE` deletes the stored row and inserts a new one, so every + * column a live account fills in for itself has to be named here or a merge + * would quietly clear it. Those columns — a preserved post, a downloader's + * attempt count — come off the merged row, where the union rules already + * carried the local value across. + * + * The order is the restore's order, for the same reason: Mobile's schema has + * foreign keys on, so profiles precede the records that name them, media + * assets precede the attachments that reference them, and conversations + * precede their messages. + */ +export async function writeMergedAccountRows( + database: MergeableAccountDatabase, + plan: BlueskyArchiveMergePlan, +): Promise { + for (const profile of plan.profiles) { + await database.run( + `INSERT OR REPLACE INTO profile (did, handle, displayName, avatarUrl, savedAt, updatedAt) + VALUES (?, ?, ?, ?, ?, ?);`, + [ + profile.did, + profile.handle, + profile.displayName, + profile.avatarUrl, + profile.savedAt, + profile.updatedAt, + ], + ); + } + + for (const post of plan.posts) { + await database.run( + `INSERT OR REPLACE INTO post ( + uri, cid, authorDid, + text, facetsJSON, embedType, embedJSON, langs, + isReply, replyParentUri, replyRootUri, + isQuote, quotedPostUri, + isRepost, repostUri, repostCid, originalPostUri, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, likeUri, viewerReposted, viewerBookmarked, + createdAt, savedAt, + deletedPostAt, deletedRepostAt, deletedLikeAt, deletedBookmarkAt, + preserve + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + post.uri, + post.cid, + post.authorDid, + post.text, + post.facetsJSON, + post.embedType, + post.embedJSON, + post.langs, + post.isReply, + post.replyParentUri, + post.replyRootUri, + post.isQuote, + post.quotedPostUri, + post.isRepost, + post.repostUri, + post.repostCid, + post.originalPostUri, + post.likeCount, + post.repostCount, + post.replyCount, + post.quoteCount, + post.viewerLiked, + post.likeUri, + post.viewerReposted, + post.viewerBookmarked, + post.createdAt, + post.savedAt, + post.deletedPostAt, + post.deletedRepostAt, + post.deletedLikeAt, + post.deletedBookmarkAt, + post.preserve, + ], + ); + } + + for (const asset of plan.mediaAssets) { + await database.run( + `INSERT OR REPLACE INTO media_asset ( + contentCid, mediaType, mimeType, byteLength, localPath, sourceUrl, + sourceDid, sourceMetadataJSON, downloadState, lastError, attemptCount, + downloadedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + asset.contentCid, + asset.mediaType, + asset.mimeType, + asset.byteLength, + asset.localPath, + asset.sourceUrl, + asset.sourceDid, + asset.sourceMetadataJSON, + asset.downloadState, + asset.lastError, + asset.attemptCount, + asset.downloadedAt, + ], + ); + } + + for (const media of plan.postMedia) { + await database.run( + `INSERT OR REPLACE INTO post_media ( + postUri, position, mediaType, blobCid, mimeType, alt, + width, height, aspectRatioWidth, aspectRatioHeight, + thumbUrl, fullsizeUrl, playlistUrl, downloadedAt, assetCid + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + media.postUri, + media.position, + media.mediaType, + media.blobCid, + media.mimeType, + media.alt, + media.width, + media.height, + media.width, + media.height, + media.thumbUrl, + media.fullsizeUrl, + media.playlistUrl, + media.downloadedAt, + media.assetCid, + ], + ); + } + + for (const external of plan.postExternals) { + await database.run( + `INSERT OR REPLACE INTO post_external ( + postUri, uri, title, description, thumbUrl, thumbLocalPath + ) VALUES (?, ?, ?, ?, ?, ?);`, + [ + external.postUri, + external.uri, + external.title, + external.description, + external.thumbUrl, + external.thumbLocalPath, + ], + ); + } + + for (const bookmark of plan.bookmarks) { + await database.run( + `INSERT OR REPLACE INTO bookmark ( + subjectUri, postAuthorDid, postAuthorHandle, postText, postCreatedAt, + savedAt, deletedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?);`, + [ + bookmark.subjectUri, + bookmark.postAuthorDid, + bookmark.postAuthorHandle, + bookmark.postText, + bookmark.postCreatedAt, + bookmark.savedAt, + bookmark.deletedAt, + ], + ); + } + + for (const follow of plan.follows) { + await database.run( + `INSERT OR REPLACE INTO follow ( + uri, cid, subjectDid, handle, displayName, avatarUrl, + createdAt, savedAt, unfollowedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + follow.uri, + follow.cid, + follow.subjectDid, + follow.handle, + follow.displayName, + follow.avatarUrl, + follow.createdAt, + follow.savedAt, + follow.unfollowedAt, + ], + ); + } + + for (const conversation of plan.conversations) { + await database.run( + `INSERT OR REPLACE INTO conversation ( + convoId, rev, memberDids, muted, + lastMessageId, lastMessageText, lastMessageSentAt, lastMessageSenderDid, + savedAt, updatedAt, leftAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + conversation.convoId, + conversation.rev, + conversation.memberDids, + conversation.muted, + conversation.lastMessageId, + conversation.lastMessageText, + conversation.lastMessageSentAt, + conversation.lastMessageSenderDid, + conversation.savedAt, + conversation.updatedAt, + conversation.leftAt, + ], + ); + } + + for (const message of plan.messages) { + await database.run( + `INSERT OR REPLACE INTO message ( + messageId, convoId, rev, senderDid, text, facetsJSON, embedJSON, + sentAt, savedAt, deletedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + message.messageId, + message.convoId, + message.rev, + message.senderDid, + message.text, + message.facetsJSON, + message.embedJSON, + message.sentAt, + message.savedAt, + message.deletedAt, + ], + ); + } +} + +/** How many rows a plan would write, which is what "no effect" means. */ +export function countPlannedWrites(plan: BlueskyArchiveMergePlan): number { + return ( + plan.profiles.length + + plan.posts.length + + plan.postMedia.length + + plan.postExternals.length + + plan.bookmarks.length + + plan.follows.length + + plan.conversations.length + + plan.messages.length + + plan.mediaAssets.length + ); +} diff --git a/services/archive-merge/merge.ts b/services/archive-merge/merge.ts new file mode 100644 index 0000000..83bba6f --- /dev/null +++ b/services/archive-merge/merge.ts @@ -0,0 +1,273 @@ +import { + placeArchivedMedia, + predictArchivedMedia, + readBlueskyInterchange, + translateInterchangeToMobileRows, + type BlueskyInterchangeSnapshot, + type InterchangeAsset, + type LocalAccountIdentity, + type RestoredMobileAccount, + type UnrestorableContent, +} from "@/services/archive-restore"; + +import { readExistingAccountRows } from "./account-rows"; +import { accountRowsFromArchive } from "./rows"; +import { BlueskyArchiveMergeError } from "./errors"; +import { + planBlueskyArchiveMerge, + type BlueskyArchiveMergePlan, + type BlueskyArchiveMergeSummary, +} from "./merge-plan"; +import { countPlannedWrites, writeMergedAccountRows } from "./merge-writer"; +import type { + BlueskyArchiveMergeEnvironment, + PreparedArchiveLocation, +} from "./ports"; + +/** + * The commit half of a Bluesky archive import for an identity Cyd already + * holds. + * + * It runs in two acts, and the split is the point. A **preview** reads the + * prepared archive and works out exactly what merging it would do, touching + * nothing; a **commit** takes that preview and carries it out. Somebody is + * shown the preview first because a recovery merge can bring back records they + * deleted from Cyd on purpose, and nobody should find that out afterwards. + * + * Everything else follows the restore's shape (#96): media is copied in before + * rows are written, so a record's local file path is known when its row is + * built, and an asset that will not copy becomes a failed download rather than + * a failed import. + */ + +export type BlueskyArchiveMergePhase = + | "reading" + | "merging-media" + | "writing" + | "done"; + +export type BlueskyArchiveMergeProgress = { + phase: BlueskyArchiveMergePhase; + mergedAssets: number; + totalAssets: number; +}; + +export type BlueskyArchiveMergeRequest = { + /** An archive intake that ended *prepared* (#95). */ + archive: PreparedArchiveLocation; + /** The Bluesky local account holding this archive's identity. */ + account: LocalAccountIdentity; + onProgress?: (progress: BlueskyArchiveMergeProgress) => void; +}; + +export type MergedAssetSummary = { + total: number; + merged: number; + missing: number; +}; + +export type BlueskyArchiveMergePreview = { + accountUuid: string; + accountDid: string; + /** What the archive says about itself, for somebody deciding about it. */ + archive: { + createdAt: string; + completeness: "complete" | "incomplete"; + accountUuid: string; + }; + summary: BlueskyArchiveMergeSummary; + assets: MergedAssetSummary; + unrestorable: UnrestorableContent; + /** Everything the commit needs, so agreeing to a preview commits that archive. */ + readonly source: { + location: PreparedArchiveLocation; + snapshot: BlueskyInterchangeSnapshot; + }; +}; + +export type BlueskyArchiveMergeResult = { + accountUuid: string; + accountDid: string; + /** Rows actually written. Zero is what a repeated import looks like. */ + written: number; + summary: BlueskyArchiveMergeSummary; + assets: MergedAssetSummary; +}; + +/** + * Work out what merging this archive would do, without doing any of it. + * + * Media is not copied yet, so the plan is built against where each file *will* + * live: the paths are content-addressed, so they are known before the bytes + * move (ADR 0007). A file that then refuses to copy is downgraded at commit + * time, which can only ever turn a restored asset into a failed download. + */ +export async function previewBlueskyArchiveMerge( + environment: BlueskyArchiveMergeEnvironment, + request: BlueskyArchiveMergeRequest, +): Promise { + const report = reporter(request); + report("reading", 0, 0); + + const archive = environment.openPreparedArchive(request.archive); + const interchange = await archive.openInterchange(); + let snapshot: BlueskyInterchangeSnapshot; + try { + snapshot = await readBlueskyInterchange(interchange); + } finally { + await interchange.close(); + } + + requireMatchingIdentity(snapshot.archive.account_did, request.account); + + const incoming = translateInterchangeToMobileRows(snapshot, { + placements: predictArchivedMedia(snapshot.assets, (fileName) => + environment.accountMediaUri(request.account.uuid, fileName), + ), + }); + const plan = await planAgainstAccount( + environment, + request.account.uuid, + snapshot.archive.account_did, + incoming, + ); + + report("done", 0, snapshot.assets.length); + return { + accountUuid: request.account.uuid, + accountDid: snapshot.archive.account_did, + archive: { + createdAt: snapshot.archive.created_at, + completeness: snapshot.archive.completeness, + accountUuid: snapshot.archive.account_uuid, + }, + summary: plan.summary, + assets: summarizeAssets(snapshot.assets), + unrestorable: incoming.unrestorable, + source: { location: request.archive, snapshot }, + }; +} + +/** + * Carry out a preview somebody agreed to. + * + * The account is read again rather than trusted from the preview: a save that + * ran in between is newer than the archive, and the union rules can only reach + * the right answer if they are given what the account holds *now*. Committing + * twice is therefore as safe as importing twice — the second commit finds + * nothing left to write. + */ +export async function commitBlueskyArchiveMerge( + environment: BlueskyArchiveMergeEnvironment, + preview: BlueskyArchiveMergePreview, + options: { onProgress?: (progress: BlueskyArchiveMergeProgress) => void } = {}, +): Promise { + const { snapshot, location } = preview.source; + const totalAssets = snapshot.assets.length; + const report = reporter({ onProgress: options.onProgress }); + + const archive = environment.openPreparedArchive(location); + + report("merging-media", 0, totalAssets); + const placements = await placeArchivedMedia(environment, { + accountUuid: preview.accountUuid, + archive, + assets: snapshot.assets, + onPlaced: (placed) => report("merging-media", placed, totalAssets), + }); + + const incoming = translateInterchangeToMobileRows(snapshot, { placements }); + const plan = await planAgainstAccount( + environment, + preview.accountUuid, + preview.accountDid, + incoming, + ); + + report("writing", placements.size, totalAssets); + const database = await environment.openAccountDatabase(preview.accountUuid); + try { + await database.transaction(async () => { + await writeMergedAccountRows(database, plan); + }); + } finally { + await database.close(); + } + + // The account holds everything the archive carried, so the staged copy is + // nothing but a second copy of data this device now has. + await archive.discard(); + + report("done", placements.size, totalAssets); + return { + accountUuid: preview.accountUuid, + accountDid: preview.accountDid, + written: countPlannedWrites(plan), + summary: plan.summary, + assets: summarizeAssets(snapshot.assets), + }; +} + +function reporter(options: { + onProgress?: (progress: BlueskyArchiveMergeProgress) => void; +}) { + return ( + phase: BlueskyArchiveMergePhase, + mergedAssets: number, + totalAssets: number, + ): void => options.onProgress?.({ phase, mergedAssets, totalAssets }); +} + +async function planAgainstAccount( + environment: BlueskyArchiveMergeEnvironment, + accountUuid: string, + accountDid: string, + incoming: RestoredMobileAccount, +): Promise { + const database = await environment.openAccountDatabase(accountUuid); + try { + return planBlueskyArchiveMerge( + await readExistingAccountRows(database), + accountRowsFromArchive(incoming), + accountDid, + ); + } finally { + await database.close(); + } +} + +/** + * Refuse an archive that belongs to somebody else. + * + * The DID is the identity (ADR 0011), so this is the only check worth making: + * a handle that matches proves nothing, and a handle that does not is routine + * for somebody who renamed. + */ +function requireMatchingIdentity( + archiveDid: string, + account: LocalAccountIdentity, +): void { + if (account.did !== archiveDid) { + throw new BlueskyArchiveMergeError( + "identity-mismatch", + "This archive belongs to a different Bluesky identity than the account it was about to be merged into.", + ); + } +} + +/** + * What the archive's media amounts to for this account. + * + * An asset the account already holds is not counted as missing: the file is + * there, and the merge simply had nothing to change about it. + */ +function summarizeAssets(assets: InterchangeAsset[]): MergedAssetSummary { + const available = assets.filter( + (asset) => asset.availability === "available" && asset.sha256, + ).length; + return { + total: assets.length, + merged: available, + missing: assets.length - available, + }; +} diff --git a/services/archive-merge/ports.ts b/services/archive-merge/ports.ts new file mode 100644 index 0000000..eee39b5 --- /dev/null +++ b/services/archive-merge/ports.ts @@ -0,0 +1,56 @@ +import type { + LocalAccountIdentity, + PreparedArchiveLocation, + PreparedArchiveStore, + RestoredAccountDatabase, + StoredMediaFile, +} from "@/services/archive-restore"; + +/** + * The platform capabilities a recovery merge needs, and deliberately no more. + * + * What is missing from this list is the point of it. There is no way from here + * to write a Bluesky local account's settings or schedule, to touch a Bluesky + * connection, to rename an account or to remove one: a merge into an existing + * Bluesky local account can only add to that account's Bluesky saved data, so + * "an existing identity keeps its UUID, its settings, its schedules and its + * connection" is a property of the interface rather than a promise somebody + * has to keep. + */ + +/** An existing account's database, which a merge reads before it writes. */ +export type MergeableAccountDatabase = RestoredAccountDatabase & { + all(sql: string): Promise; +}; + +export type BlueskyArchiveMergeEnvironment = { + openPreparedArchive(archive: PreparedArchiveLocation): PreparedArchiveStore; + + /** Every Bluesky local account this installation has, for routing (#97). */ + listLocalAccountIdentities(): Promise; + + openAccountDatabase(accountUuid: string): Promise; + + /** + * Copy a staged payload into the account's own media storage. + * + * Content-addressed, so a file the account already holds is written once + * (ADR 0007) and merging the same archive twice copies nothing new. + */ + storeAccountMedia( + accountUuid: string, + fileName: string, + write: (push: (bytes: Uint8Array) => void) => Promise, + ): Promise; + + /** + * Where a file of this name will live inside an account's media storage. + * + * Media is content-addressed, so a merge can say where a file is going + * before it moves the bytes. That is what lets somebody be shown the exact + * rows a merge would write without anything being written. + */ + accountMediaUri(accountUuid: string, fileName: string): string; +}; + +export type { PreparedArchiveLocation, StoredMediaFile }; diff --git a/services/archive-merge/rows.ts b/services/archive-merge/rows.ts new file mode 100644 index 0000000..31bfdec --- /dev/null +++ b/services/archive-merge/rows.ts @@ -0,0 +1,88 @@ +import type { + RestoredMobileAccount, + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMediaAssetWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobilePostWrite, + MobileProfileWrite, +} from "@/services/archive-restore"; + +/** + * The rows a Bluesky local account already holds, in the shape a restore + * writes them. + * + * A merge compares two descriptions of the same Bluesky saved data, so both + * sides have to be the same shape. Restore's row types are that shape, plus + * the few columns that only a live account has: a person's own decision to + * preserve a post, and what Cyd's downloader has been through with a file. + * They are local facts an archive cannot know, so the merge carries them + * across untouched rather than letting an `INSERT OR REPLACE` quietly reset + * them. + */ + +export type ExistingPostRow = MobilePostWrite & { + /** The person's own "never delete this", which no archive may clear. */ + preserve: number; +}; + +export type ExistingMediaAssetRow = Omit< + MobileMediaAssetWrite, + "downloadState" +> & { + downloadState: "pending" | "downloading" | "complete" | "failed"; + attemptCount: number; +}; + +export type ExistingAccountRows = { + profiles: MobileProfileWrite[]; + posts: ExistingPostRow[]; + postMedia: MobilePostMediaWrite[]; + postExternals: MobilePostExternalWrite[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; + mediaAssets: ExistingMediaAssetRow[]; +}; + +/** + * A Cyd Bluesky archive's rows, in the shape the account holds them. + * + * The two columns an archive cannot know get the value a newly saved record + * would have, and the union rules carry the account's own values across, so an + * archive can never reset a person's own decision to preserve a post or a + * downloader's record of what it has been through. + */ +export function accountRowsFromArchive( + restored: RestoredMobileAccount, +): ExistingAccountRows { + return { + profiles: restored.profiles, + posts: restored.posts.map((row) => ({ ...row, preserve: 0 })), + postMedia: restored.postMedia, + postExternals: restored.postExternals, + bookmarks: restored.bookmarks, + follows: restored.follows, + conversations: restored.conversations, + messages: restored.messages, + mediaAssets: restored.mediaAssets.map((row) => ({ + ...row, + attemptCount: 0, + })), + }; +} + +export type { + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobilePostWrite, + MobileProfileWrite, +}; diff --git a/services/archive-merge/union.ts b/services/archive-merge/union.ts new file mode 100644 index 0000000..16fd0a9 --- /dev/null +++ b/services/archive-merge/union.ts @@ -0,0 +1,93 @@ +/** + * The four rules a recovery union comes down to. + * + * They are small on purpose: every column of every table in `merge-plan.ts` is + * settled by one of them, so "what does importing an old archive do to my + * account?" has one answer to read rather than one per table. + */ + +function populated(value: unknown): boolean { + return value !== null && value !== undefined && value !== ""; +} + +/** + * Keep whichever side actually says something. + * + * Absence is never an observation: an archive exported before Cyd captured a + * post's alt text, or one written by a client that has no column for it, says + * nothing about that field rather than saying it is empty. Only when both + * sides hold a value does the newer observation win. + */ +export function preferPopulated( + local: T, + incoming: T, + incomingIsNewer: boolean, +): T { + if (!populated(incoming)) { + return local; + } + if (!populated(local)) { + return incoming; + } + return incomingIsNewer ? incoming : local; +} + +/** + * An engagement count, where a zero is usually "not counted". + * + * The interchange model carries metrics inside a record's payload, and an + * archive written by a client that did not capture them translates to zero + * rather than to nothing. A zero is therefore not an observation that a post + * has no likes, and must not overwrite a number this device actually saw. A + * count that really did fall to zero is the price, and it is the safe side of + * the trade: nothing is lost, and the next save corrects it. + */ +export function preferCounted( + local: number, + incoming: number, + incomingIsNewer: boolean, +): number { + if (incoming === 0) { + return local; + } + if (local === 0) { + return incoming; + } + return incomingIsNewer ? incoming : local; +} + +/** A flag either side set stays set: a union never takes a like back. */ +export function unionFlag( + local: number | null, + incoming: number | null, +): number { + return local === 1 || incoming === 1 ? 1 : 0; +} + +/** The first time either side saw something happen, such as a deletion. */ +export function earliest( + local: number | null, + incoming: number | null, +): number | null { + if (local === null) { + return incoming; + } + if (incoming === null) { + return local; + } + return Math.min(local, incoming); +} + +/** The most recent of two timestamps, when later means better informed. */ +export function latest( + local: number | null, + incoming: number | null, +): number | null { + if (local === null) { + return incoming; + } + if (incoming === null) { + return local; + } + return Math.max(local, incoming); +} diff --git a/services/archive-restore/__tests__/mobile-rows.test.ts b/services/archive-restore/__tests__/mobile-rows.test.ts index 9441c0b..e2e34de 100644 --- a/services/archive-restore/__tests__/mobile-rows.test.ts +++ b/services/archive-restore/__tests__/mobile-rows.test.ts @@ -811,4 +811,19 @@ describe("translating a Cyd Bluesky archive into Mobile's rows", () => { displayName: "Owner", }); }); + + it("treats a display name nobody set as no display name", () => { + // An account that never set one exports an empty string, which is an + // absence rather than a name: keeping it would show a blank where the + // account's name goes, instead of falling back to its handle. + const snapshot = emptySnapshot(); + snapshot.profiles[0].display_name = ""; + + const { identity } = translate(snapshot); + + expect(identity).toMatchObject({ + handle: "owner.bsky.social", + displayName: null, + }); + }); }); diff --git a/services/archive-restore/environment.ts b/services/archive-restore/environment.ts index 02628de..06753f1 100644 --- a/services/archive-restore/environment.ts +++ b/services/archive-restore/environment.ts @@ -10,6 +10,10 @@ import { applyAccountMigrations, blueskyAccountMigrations, } from "@/database/account-db"; +import { + acquireAccountDatabase, + releaseAccountDatabase, +} from "@/database/account-db/shared-handles"; import { createBlueskyAccount, deleteAccount, @@ -65,13 +69,18 @@ function asReadableInterchange( function asRestoredAccountDatabase( database: SQLiteDatabase, + accountUuid: string, ): RestoredAccountDatabase { + const paths = buildAccountPaths("bluesky", accountUuid); return { run: async (sql, params) => { await database.runAsync(sql, params as never[]); }, transaction: (work) => database.withTransactionAsync(work), - close: async () => database.closeAsync(), + // Handed back rather than closed: the handle is shared with anything else + // in the app holding this account open. + close: async () => + releaseAccountDatabase(paths.dbDirForSQLite, paths.dbNameForSQLite), }; } @@ -81,17 +90,24 @@ async function openAccountDatabase(accountUuid: string): Promise intermediates: true, idempotent: true, }); - const database = await openDatabaseAsync( - paths.dbNameForSQLite, - {}, + // Borrowed rather than opened: the app may already hold this database, and a + // second handle over the same connection closes it for the first one when it + // is collected. + const database = await acquireAccountDatabase( paths.dbDirForSQLite, + paths.dbNameForSQLite, ); - await database.execAsync("PRAGMA foreign_keys = ON;"); applyAccountMigrations(database, blueskyAccountMigrations); return database; } -function openPreparedArchive( +/** + * Reading a prepared archive out of intake staging. + * + * Exported because a merge reads the same staging the same way (#97): the + * archive does not care which half of the import opened it. + */ +export function openPreparedArchive( archive: PreparedArchiveLocation, ): PreparedArchiveStore { const nativeRoot = `${nativeStagingRoot()}/${archive.intakeId}`; @@ -180,13 +196,21 @@ export function createBlueskyArchiveRestoreEnvironment(): BlueskyArchiveRestoreE // Creating the database here means a restore that fails later leaves an // account directory to delete rather than a half-migrated one to guess at. - (await openAccountDatabase(request.uuid)).closeSync(); + await openAccountDatabase(request.uuid); + const created = buildAccountPaths("bluesky", request.uuid); + await releaseAccountDatabase( + created.dbDirForSQLite, + created.dbNameForSQLite, + ); return { accountId: account.id, accountUuid: account.uuid }; }, openAccountDatabase: async (accountUuid) => - asRestoredAccountDatabase(await openAccountDatabase(accountUuid)), + asRestoredAccountDatabase( + await openAccountDatabase(accountUuid), + accountUuid, + ), storeAccountMedia: async ( accountUuid, diff --git a/services/archive-restore/index.ts b/services/archive-restore/index.ts index d993bcb..f5839b2 100644 --- a/services/archive-restore/index.ts +++ b/services/archive-restore/index.ts @@ -12,8 +12,14 @@ * * What leaves this module is the entry point, the failures a caller has to * tell somebody about, and the ports an adapter has to implement. Everything - * else — the interchange reader, the translation, the row writer — is internal, - * and its tests reach for it directly. + * else — the translation and the row writer — is internal, and its tests reach + * for it directly. + * + * The pieces a merge needs are the exception. Reading a version 2 interchange + * database, translating it into Mobile's rows, and copying its media into an + * account are the same work whichever half of the import is running, so they + * are exported here and #97 consumes them rather than growing a second v2 + * adapter that can drift from this one. */ export { createBlueskyArchiveRestoreEnvironment } from "./environment"; @@ -32,7 +38,31 @@ export type { RestoredAssetSummary, RestoredCategoryCounts, } from "./restore"; -export type { UnrestorableContent } from "./mobile-rows"; +export { readBlueskyInterchange } from "./interchange-reader"; +export type { + BlueskyInterchangeSnapshot, + InterchangeAsset, +} from "./interchange-reader"; +export { + placeArchivedMedia, + predictArchivedMedia, + restoredMediaFileName, +} from "./media"; +export { translateInterchangeToMobileRows } from "./mobile-rows"; +export type { + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMediaAssetWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobilePostWrite, + MobileProfileWrite, + RestoredAssetPlacement, + RestoredMobileAccount, + UnrestorableContent, +} from "./mobile-rows"; export type { BlueskyArchiveRestoreEnvironment, CreatedLocalAccount, diff --git a/services/archive-restore/media.ts b/services/archive-restore/media.ts new file mode 100644 index 0000000..b547a49 --- /dev/null +++ b/services/archive-restore/media.ts @@ -0,0 +1,158 @@ +import type { InterchangeAsset } from "./interchange-reader"; +import type { RestoredAssetPlacement } from "./mobile-rows"; +import type { PreparedArchiveStore, StoredMediaFile } from "./ports"; + +/** + * Copying a Cyd Bluesky archive's packaged assets into a Bluesky local + * account. + * + * Both halves of an import land here: a restore copies into the account it is + * creating, and a merge copies into the account it is merging with (#97). The + * rule is the same either way, which is why it is one file — an archive's + * media is content-addressed, so the same bytes referenced by several records + * are stored once (ADR 0007). + */ + +/** Content-addressed name of a restored file inside the account's media store. */ +export function restoredMediaFileName(sha256: string): string { + return `sha256-${sha256}`; +} + +/** + * What an asset the archive cannot supply looks like, wherever it is noticed. + * + * A merge works this out before it copies anything, so that somebody can be + * shown the rows it would write; a restore works it out as it copies. Both + * have to reach the same answer, so they ask the same function. + */ +function missingPlacement(asset: InterchangeAsset): RestoredAssetPlacement { + return { + assetId: asset.id, + availability: "missing", + reason: + asset.unavailable_reason ?? "This file was not included in the archive.", + }; +} + +/** Whether the archive claims to carry this file's bytes at all. */ +function isPackaged( + asset: InterchangeAsset, +): asset is InterchangeAsset & { archive_path: string; sha256: string } { + return ( + asset.availability === "available" && + asset.archive_path !== null && + asset.sha256 !== null + ); +} + +/** + * Where each packaged asset will end up, without moving a byte. + * + * Media is content-addressed, so its path is a fact about the file rather than + * a result of copying it. That is what lets a merge plan the exact rows it + * would write before anybody has agreed to the merge (ADR 0018). + */ +export function predictArchivedMedia( + assets: InterchangeAsset[], + mediaUriFor: (fileName: string) => string, +): Map { + const placements = new Map(); + for (const asset of assets) { + placements.set( + asset.id, + isPackaged(asset) + ? { + assetId: asset.id, + availability: "restored", + localPath: mediaUriFor(restoredMediaFileName(asset.sha256)), + } + : missingPlacement(asset), + ); + } + return placements; +} + +/** The one capability placing media needs, out of the larger environments. */ +export type MediaStore = { + storeAccountMedia( + accountUuid: string, + fileName: string, + write: (push: (bytes: Uint8Array) => void) => Promise, + ): Promise; +}; + +/** + * Copy each packaged asset into the Bluesky local account, once per file. + * + * An asset the archive marked unavailable never had bytes to copy. One that + * will not read, or that arrives the wrong size, is treated the same way: the + * archive's promise about that file did not hold, and calling it restored + * would make an incomplete backup look complete. Either way the record keeps + * its reference and the source URL, so saving can fetch it later. + */ +export async function placeArchivedMedia( + environment: MediaStore, + options: { + accountUuid: string; + archive: Pick; + assets: InterchangeAsset[]; + onPlaced: (placed: number) => void; + }, +): Promise> { + const placements = new Map(); + const byDigest = new Map(); + let placed = 0; + + for (const asset of options.assets) { + if (!isPackaged(asset)) { + placements.set(asset.id, missingPlacement(asset)); + continue; + } + + const alreadyPlaced = byDigest.get(asset.sha256); + if (alreadyPlaced) { + placements.set(asset.id, { + assetId: asset.id, + availability: "restored", + localPath: alreadyPlaced, + }); + continue; + } + + const archivePath = asset.archive_path; + let stored: StoredMediaFile | null = null; + try { + stored = await environment.storeAccountMedia( + options.accountUuid, + restoredMediaFileName(asset.sha256), + (push) => options.archive.readPayload(archivePath, push), + ); + } catch { + stored = null; + } + + const wrongSize = + stored !== null && + asset.byte_count !== null && + stored.byteLength !== asset.byte_count; + if (stored === null || wrongSize) { + placements.set(asset.id, { + assetId: asset.id, + availability: "missing", + reason: "Cyd could not restore this file from the archive.", + }); + continue; + } + + byDigest.set(asset.sha256, stored.uri); + placements.set(asset.id, { + assetId: asset.id, + availability: "restored", + localPath: stored.uri, + }); + placed += 1; + options.onPlaced(placed); + } + + return placements; +} diff --git a/services/archive-restore/mobile-rows.ts b/services/archive-restore/mobile-rows.ts index 09d4c8c..f178013 100644 --- a/services/archive-restore/mobile-rows.ts +++ b/services/archive-restore/mobile-rows.ts @@ -227,6 +227,12 @@ function millisFrom(value: string | null | undefined): number | null { return Number.isNaN(parsed) ? null : parsed; } +/** A name, or nothing: blank is an absence of one rather than an empty one. */ +function named(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed ? trimmed : null; +} + function parseJson(value: string | null): unknown { if (!value) { return null; @@ -338,7 +344,11 @@ class MobileRowBuilder { return { did, handle: restored?.handle ?? profile?.handle ?? did, - displayName: restored?.displayName ?? profile?.display_name ?? null, + // A display name nobody ever set arrives as an empty string, which is an + // absence rather than a name — the same thing the merge's `populated` + // rule refuses to treat as an observation. Storing it as nothing is what + // lets the account fall back to its handle instead of showing a blank. + displayName: named(restored?.displayName ?? profile?.display_name), avatarUrl: restored?.avatarUrl ?? null, }; } diff --git a/services/archive-restore/restore.ts b/services/archive-restore/restore.ts index 0911ab8..c5115d8 100644 --- a/services/archive-restore/restore.ts +++ b/services/archive-restore/restore.ts @@ -9,8 +9,8 @@ import { import { readBlueskyInterchange, type BlueskyInterchangeSnapshot, - type InterchangeAsset, } from "./interchange-reader"; +import { placeArchivedMedia } from "./media"; import { translateInterchangeToMobileRows, type RestoredAssetPlacement, @@ -22,9 +22,7 @@ import type { BlueskyArchiveRestoreEnvironment, CreatedLocalAccount, PreparedArchiveLocation, - PreparedArchiveStore, RestoredAccountDatabase, - StoredMediaFile, } from "./ports"; import { writeRestoredAccountRows } from "./account-writer"; @@ -99,11 +97,6 @@ export type BlueskyArchiveRestoreResult = { unrestorable: UnrestorableContent; }; -/** Content-addressed name of a restored file inside the account's media store. */ -export function restoredMediaFileName(sha256: string): string { - return `sha256-${sha256}`; -} - export async function restoreBlueskyArchiveAccount( environment: BlueskyArchiveRestoreEnvironment, request: BlueskyArchiveRestoreRequest, @@ -200,88 +193,6 @@ export async function restoreBlueskyArchiveAccount( } } -/** - * Copy each packaged asset into the Bluesky local account, once per file. - * - * An asset the archive marked unavailable never had bytes to copy. One that - * will not read, or that arrives the wrong size, is treated the same way: the - * archive's promise about that file did not hold, and calling it restored - * would make an incomplete backup look complete. Either way the record keeps - * its reference and the source URL, so saving can fetch it later. - */ -async function placeArchivedMedia( - environment: BlueskyArchiveRestoreEnvironment, - options: { - accountUuid: string; - archive: Pick; - assets: InterchangeAsset[]; - onPlaced: (placed: number) => void; - }, -): Promise> { - const placements = new Map(); - const byDigest = new Map(); - let placed = 0; - - for (const asset of options.assets) { - if (asset.availability !== "available" || !asset.archive_path || !asset.sha256) { - placements.set(asset.id, { - assetId: asset.id, - availability: "missing", - reason: - asset.unavailable_reason ?? - "This file was not included in the archive.", - }); - continue; - } - - const alreadyPlaced = byDigest.get(asset.sha256); - if (alreadyPlaced) { - placements.set(asset.id, { - assetId: asset.id, - availability: "restored", - localPath: alreadyPlaced, - }); - continue; - } - - const archivePath = asset.archive_path; - let stored: StoredMediaFile | null = null; - try { - stored = await environment.storeAccountMedia( - options.accountUuid, - restoredMediaFileName(asset.sha256), - (push) => options.archive.readPayload(archivePath, push), - ); - } catch { - stored = null; - } - - const wrongSize = - stored !== null && - asset.byte_count !== null && - stored.byteLength !== asset.byte_count; - if (stored === null || wrongSize) { - placements.set(asset.id, { - assetId: asset.id, - availability: "missing", - reason: "Cyd could not restore this file from the archive.", - }); - continue; - } - - byDigest.set(asset.sha256, stored.uri); - placements.set(asset.id, { - assetId: asset.id, - availability: "restored", - localPath: stored.uri, - }); - placed += 1; - options.onPlaced(placed); - } - - return placements; -} - /** * What the restored account knows about where it came from. * diff --git a/services/bluesky-sign-in.ts b/services/bluesky-sign-in.ts new file mode 100644 index 0000000..59528ab --- /dev/null +++ b/services/bluesky-sign-in.ts @@ -0,0 +1,86 @@ +import { + ACCOUNT_AUTH_STATUS, + withBlueskyController, + type AccountAuthStatusValue, +} from "@/controllers"; +import type { AccountListItem } from "@/database/accounts"; +import { trackEvent } from "@/services/analytics"; +import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; +import { authenticateBlueskyAccount } from "@/services/bluesky-oauth"; +import { PlausibleEvents } from "@/types/analytics"; + +/** + * Establish a Bluesky connection and leave the account knowing it has one. + * + * Authorizing is only half of signing in. Whether Cyd can act on a Bluesky + * local account is a value cached in that account's own database, and + * `verifyBlueskyAccountAuthStatus` returns the cached "signed out" without + * looking at the stored connection at all unless it is forced — which is + * exactly what an account that has never been connected holds. So an account + * that was just authorized still reads as signed out, and asks the person to + * authorize again, until something rebuilds its agent from the connection that + * now exists. + * + * That makes the forced check part of signing in rather than something each + * caller remembers, which matters most for the callers furthest from the + * account screen: a Bluesky local account restored from a Cyd Bluesky archive + * has no cached status and no connection, and is signed in from the import + * that created it. + * + * Everywhere somebody signs in comes through here, because the steps that + * follow authorizing are the ones easy to leave out and hard to notice + * missing: an account that has to be authorized twice, or one that goes on + * showing the name and avatar an archive carried long after Bluesky told Cyd + * the real ones. + */ +export type BlueskySignIn = { + account: AccountListItem; + /** What the account now knows about itself, for a caller showing it. */ + status: AccountAuthStatusValue; +}; + +export async function connectBlueskyAccount( + handle: string, +): Promise { + const account = await authenticateBlueskyAccount(handle); + trackEvent(PlausibleEvents.BLUESKY_USER_SIGNED_IN); + + let status: AccountAuthStatusValue = ACCOUNT_AUTH_STATUS.signedOut; + try { + status = await withBlueskyController( + account.id, + account.uuid, + async (controller) => { + const verified = await verifyBlueskyAccountAuthStatus( + controller, + account, + { force: true }, + ); + if (verified === ACCOUNT_AUTH_STATUS.authenticated) { + try { + // Browse reads an author out of the account's own database, which + // for a restored account holds what the Cyd Bluesky archive + // carried. This is the first moment Cyd has anything newer to put + // there — and failing to write it down is not a failed sign-in, + // so it does not take the status with it. + await controller.refreshOwnProfile(); + } catch (err) { + console.warn("[BlueskySignIn] could not refresh the profile", err); + } + } + return verified; + }, + ); + } catch (err) { + // The connection is stored either way, so this is not a failed sign-in. + // The account will read as signed out until some forced check succeeds — + // opening it is not enough, since that check trusts the cached status — + // but signing in again runs one. + console.warn( + "[BlueskySignIn] could not finish signing in after authorizing", + err, + ); + } + + return { account, status }; +} diff --git a/testUtils/archiveEnvironments.ts b/testUtils/archiveEnvironments.ts index 7957dee..7417069 100644 --- a/testUtils/archiveEnvironments.ts +++ b/testUtils/archiveEnvironments.ts @@ -31,16 +31,19 @@ import type { StagedFileWriter, } from "@/services/archive-import/ports"; import { stagedPayloadPath } from "@/services/archive-import"; +import type { + BlueskyArchiveMergeEnvironment, + MergeableAccountDatabase, +} from "@/services/archive-merge"; import type { BlueskyArchiveRestoreEnvironment, DiscardableAccount, + LocalAccountIdentity, RestorableSettingColumn, NewLocalAccountRequest, PreparedArchiveStore, ReadableInterchangeDatabase, - RestoredAccountDatabase, } from "@/services/archive-restore"; -import type { LocalAccountIdentity } from "@/services/archive-restore"; const createNodeHasher = (): Hasher => { const hash = crypto.createHash("sha256"); @@ -129,10 +132,12 @@ function asReadableInterchange( }; } -function asRestoredAccountDatabase( +function asMergeableAccountDatabase( database: DatabaseSync, -): RestoredAccountDatabase { +): MergeableAccountDatabase { return { + all: async (sql: string): Promise => + database.prepare(sql).all() as T[], run: async (sql, params) => { database.prepare(sql).run(...(params as never[])); }, @@ -150,13 +155,21 @@ function asRestoredAccountDatabase( }; } -export type NodeRestoreEnvironment = BlueskyArchiveRestoreEnvironment & { +/** + * One Node-backed environment for both halves of an import. + * + * Restore and merge run against the same `main.db`, the same account + * directories and the same media, so splitting them into two doubles would + * only invite the two to disagree about what the device looks like. + */ +export type NodeRestoreEnvironment = BlueskyArchiveRestoreEnvironment & + BlueskyArchiveMergeEnvironment & { /** Mobile's own `main.db`, for asserting what a restore created. */ mainDatabase: DatabaseSync; accountDirectory(accountUuid: string): string; openRestoredAccountDatabase(accountUuid: string): DatabaseSync; close(): void; -}; + }; export type NodeRestoreEnvironmentOptions = { /** A directory standing in for the app's private storage. */ @@ -186,6 +199,12 @@ export function createNodeBlueskyArchiveRestoreEnvironment( const accountDirectory = (accountUuid: string): string => path.join(options.root, "accounts", `bluesky-${accountUuid}`); + const mediaDirectory = (accountUuid: string): string => + path.join(accountDirectory(accountUuid), "media"); + + const accountMediaUri = (accountUuid: string, fileName: string): string => + `file://${path.join(mediaDirectory(accountUuid), fileName)}`; + const openAccount = (accountUuid: string): DatabaseSync => { const directory = accountDirectory(accountUuid); fs.mkdirSync(directory, { recursive: true }); @@ -211,6 +230,30 @@ export function createNodeBlueskyArchiveRestoreEnvironment( return database; }; + const removeAccount = (account: DiscardableAccount): void => { + const row = mainDatabase + .prepare( + account.accountId === null + ? "SELECT bskyAccountID FROM account WHERE uuid = ?;" + : "SELECT bskyAccountID FROM account WHERE id = ?;", + ) + .get(account.accountId ?? account.accountUuid) as + | { bskyAccountID: number } + | undefined; + mainDatabase + .prepare("DELETE FROM account WHERE uuid = ?;") + .run(account.accountUuid); + if (row) { + mainDatabase + .prepare("DELETE FROM bsky_account WHERE id = ?;") + .run(row.bskyAccountID); + } + fs.rmSync(accountDirectory(account.accountUuid), { + recursive: true, + force: true, + }); + }; + let generated = 0; return { @@ -293,10 +336,10 @@ export function createNodeBlueskyArchiveRestoreEnvironment( }, openAccountDatabase: async (accountUuid) => - asRestoredAccountDatabase(openAccount(accountUuid)), + asMergeableAccountDatabase(openAccount(accountUuid)), storeAccountMedia: async (accountUuid, fileName, write) => { - const directory = path.join(accountDirectory(accountUuid), "media"); + const directory = mediaDirectory(accountUuid); fs.mkdirSync(directory, { recursive: true }); const location = path.join(directory, fileName); const chunks: Uint8Array[] = []; @@ -306,25 +349,10 @@ export function createNodeBlueskyArchiveRestoreEnvironment( return { uri: `file://${location}`, byteLength: contents.byteLength }; }, - discardLocalAccount: async (account: DiscardableAccount) => { - if (account.accountId !== null) { - const row = mainDatabase - .prepare("SELECT bskyAccountID FROM account WHERE id = ?;") - .get(account.accountId) as { bskyAccountID: number } | undefined; - mainDatabase - .prepare("DELETE FROM account WHERE id = ?;") - .run(account.accountId); - if (row) { - mainDatabase - .prepare("DELETE FROM bsky_account WHERE id = ?;") - .run(row.bskyAccountID); - } - } - fs.rmSync(accountDirectory(account.accountUuid), { - recursive: true, - force: true, - }); - }, + accountMediaUri, + + discardLocalAccount: async (account: DiscardableAccount) => + removeAccount(account), newUuid: options.newUuid ?? (() => `generated-uuid-${(generated += 1)}`), now: options.now ?? (() => new Date("2026-09-12T00:00:00.000Z")),