import { ConvexReactClient } from 'convex/react'; import { api } from '@convex/_generated/api'; import { isDirty, useTaskStore, type LocalTask } from '../task-store'; import { setSubscriptionState } from './entitlement'; import { currentOwnerId, setCurrentOwnerId } from './owner'; const DRAIN_DEBOUNCE_MS = 400; const ERROR_BACKOFF_MS = 5000; type SyncAuth = { fetchToken: () => Promise; }; export type SyncMode = 'readWrite' | 'readOnly'; /** Whether background sync is configured at all (a Convex URL is present). */ export function isSyncEnabled(): boolean { return !!process.env.EXPO_PUBLIC_CONVEX_URL; } /** * Free-sync mode (Glide Beta): signing in *is* the entitlement and there is no * RevenueCat. Read the env flag directly (not via free-sync.tsx) to avoid an * import cycle through @/auth/clerk. See data/sync/free-sync.tsx. */ const freeSync = process.env.EXPO_PUBLIC_FREE_SYNC === '1'; /** Delete the signed-in user's cloud rows before deleting their auth identity. */ export async function deleteCloudAccountData(auth: SyncAuth): Promise { const url = process.env.EXPO_PUBLIC_CONVEX_URL; if (!url) return null; const activeClient = client ?? new ConvexReactClient(url, { unsavedChangesWarning: false }); const transient = activeClient !== client; if (transient) activeClient.setAuth(auth.fetchToken); try { const result = await activeClient.mutation(api.account.deleteMyData, {}); return result.ownerId; } finally { if (transient) activeClient.close(); } } /** The wire shape pushed to `pushTasks` — synced fields keyed by `clientId`. No `ownerId` * (the server stamps it from the authenticated owner) and no local-only `syncedAt`. */ type WireTask = { clientId: string; title: string; status: LocalTask['status']; resistance: number; exposureCount: number; createdAt: number; updatedAt: number; statusChangedAt?: number; order?: number; deferCount?: number; lastDecision?: LocalTask['lastDecision']; completedAt?: number; deletedAt?: number; }; function toWire(t: LocalTask): WireTask { // Omit undefined optionals — Convex args reject explicit `undefined` values. const wire: WireTask = { clientId: t.id, title: t.title, status: t.status, resistance: t.resistance, exposureCount: t.exposureCount, createdAt: t.createdAt, updatedAt: t.updatedAt, }; if (t.statusChangedAt !== undefined) wire.statusChangedAt = t.statusChangedAt; if (t.order !== undefined) wire.order = t.order; if (t.deferCount !== undefined) wire.deferCount = t.deferCount; if (t.lastDecision !== undefined) wire.lastDecision = t.lastDecision; if (t.completedAt !== undefined) wire.completedAt = t.completedAt; if (t.deletedAt !== undefined) wire.deletedAt = t.deletedAt; return wire; } let client: ConvexReactClient | null = null; let cleanups: (() => void)[] = []; let drainTimer: ReturnType | null = null; let bootstrapTimer: ReturnType | null = null; let draining = false; let firstPull = false; let generation = 0; let syncMode: SyncMode = 'readWrite'; /** * Start the Convex sync engine: mirror the local store to the account's server rows in the * background. **No-op when no `EXPO_PUBLIC_CONVEX_URL` is configured** — the app stays fully * local then, preserving the offline / no-account guarantee. Imperative (no ConvexProvider) * so it lives entirely behind the data layer. Returns a stop function. */ export function startConvexSync(auth: SyncAuth, mode: SyncMode = 'readWrite'): () => void { const url = process.env.EXPO_PUBLIC_CONVEX_URL; if (!url || client) return stopConvexSync; syncMode = mode; client = new ConvexReactClient(url, { unsavedChangesWarning: false }); client.setAuth(auth.fetchToken); const startGeneration = ++generation; void bootstrapAuthenticatedSync(startGeneration); return stopConvexSync; } async function bootstrapAuthenticatedSync(startGeneration: number) { const activeClient = client; if (!activeClient) return; try { // In free-sync mode the RevenueCat refresh would throw (no key configured) // and, if it didn't, would reset an entitlement-less user to 'free' and stop // sync. Skip it: FreeSyncBridge already holds the state at 'subscribed', and // the server grants access via SANDBOX_GRANT_ALL. if (!freeSync) { const entitlement = await activeClient.action(api.revenuecat.refresh, {}); if (client !== activeClient || generation !== startGeneration) return; setSubscriptionState( entitlement.status === 'active' ? 'subscribed' : entitlement.status === 'expired' ? 'free' : entitlement.status ); } const viewer = await activeClient.query(api.sync.viewer, {}); if (client !== activeClient || generation !== startGeneration) return; syncMode = viewer.access; setCurrentOwnerId(viewer.ownerId); // Claim local-only rows into this account at the sign-in moment. Rows already // owned by a different authenticated account are left untouched. useTaskStore.getState().adoptOwner(viewer.ownerId); attachPullAndPush(activeClient, syncMode); } catch { if (client === activeClient && generation === startGeneration) { bootstrapTimer = setTimeout(() => void bootstrapAuthenticatedSync(startGeneration), ERROR_BACKOFF_MS); } } } function attachPullAndPush(activeClient: ConvexReactClient, mode: SyncMode) { // Pull: subscribe to the account's server rows; reconcile them in (server wins on // conflict, newer local edits are kept until they push). const watch = activeClient.watchQuery(api.sync.getTasks, {}); const unsubPull = watch.onUpdate(() => { const rows = watch.localQueryResult(); if (rows === undefined) return; // query not loaded yet useTaskStore.getState().ingestServerRows(rows); if (!firstPull) { firstPull = true; // First successful pull. If both the account and the store are empty, this is a // brand-new account → seed the starters once (they then sync up). An existing // account's rows were ingested just above, so we never pollute it with starters. if (useTaskStore.getState().tasks.length === 0) useTaskStore.getState().ensureStarterTasks(); } }); if (mode === 'readOnly') { cleanups = [unsubPull]; return; } // Push: drain dirty rows whenever the store changes (debounced), and once now. const unsubStore = useTaskStore.subscribe(() => scheduleDrain()); cleanups = [unsubPull, unsubStore]; scheduleDrain(); } export function stopConvexSync(): void { if (drainTimer) clearTimeout(drainTimer); if (bootstrapTimer) clearTimeout(bootstrapTimer); drainTimer = null; bootstrapTimer = null; cleanups.forEach((fn) => fn()); cleanups = []; client?.close(); client = null; setCurrentOwnerId(null); firstPull = false; syncMode = 'readWrite'; generation += 1; } function scheduleDrain(delayMs: number = DRAIN_DEBOUNCE_MS) { if (drainTimer) clearTimeout(drainTimer); drainTimer = setTimeout(() => void drain(), delayMs); } async function drain() { if (!client || draining) return; const ownerId = currentOwnerId(); if (ownerId === null) return; const dirty = useTaskStore.getState().tasks.filter((task) => task.ownerId === ownerId && isDirty(task)); if (dirty.length === 0) return; draining = true; let pushed = false; try { // pushTasks returns the authoritative server row per input; ingest confirms our pushes // (marks them clean) and picks up any newer version that beat us. const applied = await client.mutation(api.sync.pushTasks, { tasks: dirty.map(toWire) }); useTaskStore.getState().ingestServerRows(applied); pushed = true; } catch { // A *rejected* push (validation, not-yet-deployed, etc.) — back off rather than hot-loop. // True offline leaves the mutation pending (not rejected), so it resolves on reconnect. } finally { draining = false; // Re-drain promptly after a successful push that left mid-flight edits; back off on failure. const nextOwnerId = currentOwnerId(); if (client && nextOwnerId !== null && useTaskStore.getState().tasks.some((task) => task.ownerId === nextOwnerId && isDirty(task))) { scheduleDrain(pushed ? DRAIN_DEBOUNCE_MS : ERROR_BACKOFF_MS); } } }