feat(persistence): bidirectional local/cloud story sync (Supabase)

Connect the previously-skeleton cloudStore to the client with a full
bidirectional reconcile engine. Commercial build (AUTH_ENABLED) only; the
open-source build is byte-for-byte unchanged — all cloud paths short-circuit
when AUTH_ENABLED is false.

- cloudSync.ts: reconcile engine — decideAction (pure, LWW rev->updatedAt with
  tombstone priority) + syncOnLogin/pushOnSave/pushDeletion (best-effort,
  serialized, isAuthed-gated)
- cloudSyncClient.ts: browser fetch bridge (short-circuit + fault-tolerant)
- /api/stories/{manifest,pull,push,delete}: RLS-guarded sync endpoints
- upsert_story_if_newer RPC: optimistic concurrency (SECURITY INVOKER,
  auth.uid() injection, rev->updated_at guard, revoked from public)
- cloudStore: +manifest/pullBlobs, save->RPC {stored,won}, softDelete w/ rev
- localStore: +listAllRecordsForSync/putSyncedRecord/markRecordSynced
  (concurrency-guarded sync writes); types: +StorySyncMeta/StorySyncEnvelope
- facade + UserChip: inject pushOnSave/pushDeletion + login-triggered reconcile

Sync model: full reconcile on login + background push on save (no Realtime;
eventual consistency). Conflict resolution: last-write-wins.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Kai ki
2026-06-28 11:20:47 +08:00
parent da74e3e763
commit ff12b2759f
12 changed files with 824 additions and 66 deletions
+10 -1
View File
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useState } from "react";
import { AUTH_ENABLED } from "@/lib/supabase/config";
import { createClient } from "@/lib/supabase/client";
import { syncOnLogin } from "@/lib/persistence/cloudSync";
import type { AuthChangeEvent, Session, User } from "@supabase/supabase-js";
export function UserChip() {
@@ -15,8 +16,16 @@ export function UserChip() {
supabase.auth.getUser().then(({ data }: { data: { user: User | null } }) => setUser(data.user));
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event: AuthChangeEvent, session: Session | null) => {
} = supabase.auth.onAuthStateChange((event: AuthChangeEvent, session: Session | null) => {
setUser(session?.user ?? null);
// A signed-in user — a fresh login (SIGNED_IN) OR an already-authed mount
// (INITIAL_SESSION fires on subscribe with the current session) — triggers
// a full reconcile. syncOnLogin serializes via its in-flight guard, so
// overlapping events never run concurrent syncs (Req 4.1, 4.2, 4.3). This
// is the single global trigger point; AuthModal instances don't duplicate it.
if (session?.user && (event === "SIGNED_IN" || event === "INITIAL_SESSION")) {
void syncOnLogin();
}
});
return () => subscription.unsubscribe();
}, []);