Files
infiplot-web/lib/persistence/cloudSyncClient.ts
T
Kai ki ff12b2759f 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>
2026-06-28 11:20:47 +08:00

85 lines
2.9 KiB
TypeScript

// Network bridge — the ONLY fetch layer between the local store / reconcile
// engine and the cloud story API. Browser-only (imports the public AUTH_ENABLED
// flag, never the server-only cloudStore).
//
// Two-layer short-circuit:
// 1. AUTH_ENABLED=false (open-source build) → every method returns a safe empty
// value on its first line and NEVER issues a request.
// 2. The signed-in gate is enforced ONCE by the caller — the reconcile engine
// checks isAuthed() before touching this bridge — so methods here don't
// re-run getUser() per call. If an unauthenticated request slips through
// anyway, the route 401s and the fault-tolerant fetch below maps it to the
// same safe empty value.
//
// Every request is fully fault-tolerant: any non-2xx / network error / parse
// failure resolves to a safe value and never throws (best-effort sync).
import { AUTH_ENABLED } from "@/lib/supabase/config";
import type { StorySyncMeta, StorySyncEnvelope } from "./types";
async function postJson<T>(url: string, body: unknown): Promise<T | null> {
try {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) return null;
return (await res.json()) as T;
} catch {
return null;
}
}
/** GET the cloud manifest (all rows incl. tombstones, lightweight). [] on any
* failure / auth off. */
export async function pullManifest(): Promise<StorySyncMeta[]> {
if (!AUTH_ENABLED) return [];
try {
const res = await fetch("/api/stories/manifest", { method: "GET" });
if (!res.ok) return [];
const data = (await res.json()) as { items?: StorySyncMeta[] };
return data.items ?? [];
} catch {
return [];
}
}
/** Pull full envelopes for the given ids. [] on empty ids / failure / auth off. */
export async function pullBlobs(ids: string[]): Promise<StorySyncEnvelope[]> {
if (!AUTH_ENABLED || ids.length === 0) return [];
const data = await postJson<{ blobs?: StorySyncEnvelope[] }>(
"/api/stories/pull",
{ ids },
);
return data?.blobs ?? [];
}
/** Push one envelope through the optimistic-concurrency RPC. Returns the
* `{ stored, won }` result, or null on failure / auth off (caller leaves the
* record pending for the next reconcile). */
export async function pushBlob(
env: StorySyncEnvelope,
): Promise<{ stored: StorySyncEnvelope | null; won: boolean } | null> {
if (!AUTH_ENABLED) return null;
return postJson<{ stored: StorySyncEnvelope | null; won: boolean }>(
"/api/stories/push",
env,
);
}
/** Propagate a soft-delete tombstone. false on failure / auth off / not-newer. */
export async function pushDelete(
id: string,
rev: number,
deletedAt: number,
): Promise<boolean> {
if (!AUTH_ENABLED) return false;
const data = await postJson<{ ok?: boolean }>("/api/stories/delete", {
id,
rev,
deletedAt,
});
return data?.ok ?? false;
}