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
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/supabase/guard";
import { cloudStoryManifest } from "@/lib/persistence/cloudStore";
export const runtime = "nodejs";
// GET /api/stories/manifest — the reconcile diff basis: every cloud row for the
// signed-in user (INCLUDING tombstones), projected to {id, rev, updatedAt,
// deletedAt} without the bulky session_jsonb. Pure passthrough to cloudStore;
// requireUser 401s an unauthenticated commercial-build caller, and on the
// open-source build (AUTH_ENABLED=false) cloudStoryManifest short-circuits to []
// without ever constructing a Supabase client.
export async function GET() {
const auth = await requireUser();
if (auth instanceof NextResponse) return auth;
const items = await cloudStoryManifest();
return NextResponse.json({ items });
}