okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
9.1 KiB169 linesraw
1import type { Session } from './types';
2import {
3  HOST_FLAG_KEY, PENDING_KEY, TransportError, readBrowserSessions,
4  type ChatTransport, type HostChatEntry, type StorageLike,
5} from './session-persist';
6
7/**
8 * The page's side of the chat files on the host (server/chat-store.mjs): the HTTP transport, the first read at start (with the move of
9 * the browser's old chats to the host), the last-moment copy for a page that goes away, and the merge of what another window saved.
10 */
11
12const BASE = () => (globalThis as { __STRATA_HOST__?: string }).__STRATA_HOST__ ?? '';
13/** Names this window to the host, so the event of its own save is not mistaken for another window's. */
14export const WINDOW_ID = `w_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`;
15
16export function createHttpTransport(fetchImpl: typeof fetch = (...args) => fetch(...args)): ChatTransport {
17  const headers = (extra: Record<string, string> = {}) => ({ 'x-strata-client': 'ui', 'x-strata-window': WINDOW_ID, ...extra });
18  async function call(method: string, path: string, init: { body?: string; headers?: Record<string, string> } = {}): Promise<Response> {
19    let res: Response;
20    try { res = await fetchImpl(`${BASE()}${path}`, { method, headers: headers(init.headers), body: init.body }); }
21    catch (e) { throw new TransportError(e instanceof Error ? e.message : 'The host did not answer.', 0, 'offline', true); }
22    if (res.ok) return res;
23    let code: string | undefined, message = `Request failed (${res.status})`;
24    try { const data = await res.json() as { error?: string; code?: string }; code = data.code; if (data.error) message = data.error; } catch { /* no body */ }
25    throw new TransportError(message, res.status, code);
26  }
27  return {
28    async list() { return await (await call('GET', '/api/chats')).json() as { chats: HostChatEntry[]; damaged?: string[] }; },
29    async get(id) {
30      try {
31        const data = await (await call('GET', `/api/chats/${encodeURIComponent(id)}`)).json() as { rev: number; session: Session };
32        return { rev: Number(data.rev) || 0, session: data.session };
33      } catch (e) { if (isTransportError(e) && (e as TransportError).status === 404) return null; throw e; }
34    },
35    async put(id, text, baseRev) {
36      const res = await call('PUT', `/api/chats/${encodeURIComponent(id)}`, { body: text, headers: { 'content-type': 'application/json', ...(baseRev !== null ? { 'x-strata-base-rev': String(baseRev) } : {}) } });
37      const data = await res.json() as { rev: number; conflict?: boolean };
38      return { rev: Number(data.rev) || 0, conflict: data.conflict === true };
39    },
40    async remove(id) { await call('DELETE', `/api/chats/${encodeURIComponent(id)}`); },
41    async importMany(sessions) {
42      const res = await call('POST', '/api/chats/import', { body: JSON.stringify({ sessions }), headers: { 'content-type': 'application/json' } });
43      return await res.json() as { imported: string[]; skipped: string[]; failed: { id: string; error: string; code?: string }[] };
44    },
45  };
46}
47
48export interface HydrateResult {
49  /** The chats to show: the host's, newest first, with this page's own newer ones kept. */
50  sessions: Session[];
51  /** [id, rev] of every chat read from the host. */
52  revs: Map<string, number>;
53  /** The host could not be asked: `sessions` is what the page had, nothing was moved. */
54  offline: boolean;
55  /** Chats moved from the browser's storage to the host this time. */
56  moved: number;
57  /** Chats the host refused during the move (disk full / permission) or could not be read; they stay in the browser. */
58  failed: { id: string; error: string; code?: string }[];
59  /** Chats that came back from the last-moment copy because the host's version was older. */
60  recovered: string[];
61}
62
63/** By name, so it holds across two copies of this module (a bundle per test file). */
64const isTransportError = (e: unknown): boolean => e instanceof TransportError || (e as { name?: string } | null)?.name === 'TransportError';
65const newer = (a?: string | null, b?: string | null) => String(a ?? '') > String(b ?? '');
66
67/** Read a batch of chats from the host, a few at a time. */
68async function readAll(transport: ChatTransport, entries: HostChatEntry[], parallel = 4): Promise<Map<string, { rev: number; session: Session }>> {
69  const out = new Map<string, { rev: number; session: Session }>();
70  let next = 0;
71  const worker = async () => {
72    for (;;) {
73      const entry = entries[next++];
74      if (!entry) return;
75      const got = await transport.get(entry.id);
76      if (got) out.set(entry.id, got);
77    }
78  };
79  await Promise.all(Array.from({ length: Math.min(parallel, entries.length) }, worker));
80  return out;
81}
82
83/**
84 * The first read of the host's chats at start. Before the host has ever been given the browser's chats (no flag), they are handed over
85 * (the host takes the ones it does not have, in one request) and the flag is set; the browser's copy is left untouched. When the host
86 * cannot be asked the page keeps what it has and the writer stays off.
87 */
88export async function hydrateChats(opts: {
89  transport: ChatTransport;
90  browser: StorageLike;
91  /** The chats in memory now (the browser's copy at start, or what this window already holds). */
92  current: Session[];
93  /** A chat that must not be replaced from the host (a turn is running in it). */
94  isLive?: (id: string) => boolean;
95  /** Whether a chat in memory has changes the host does not have yet. */
96  isDirty?: (session: Session) => boolean;
97}): Promise<HydrateResult> {
98  const { transport, browser } = opts;
99  const isLive = opts.isLive ?? (() => false);
100  const isDirty = opts.isDirty ?? (() => false);
101  let moved = 0;
102  const failed: HydrateResult['failed'] = [];
103  try {
104    let flagged = false;
105    try { flagged = browser.getItem(HOST_FLAG_KEY) === '1'; } catch { flagged = false; }
106    let list = await transport.list();
107    if (!flagged) {
108      const old = readBrowserSessions(browser).sessions;
109      if (old.length) {
110        const result = await transport.importMany(old);
111        moved = result.imported.length;
112        failed.push(...result.failed);
113        list = await transport.list();
114      }
115      // Set only when nothing was refused: a disk-full move is tried again at the next start.
116      if (!failed.length) { try { browser.setItem(HOST_FLAG_KEY, '1'); } catch { /* the flag is a courtesy; the host skips what it has */ } }
117    }
118    const fromHost = await readAll(transport, list.chats);
119    const revs = new Map([...fromHost].map(([id, v]) => [id, v.rev]));
120    const mine = new Map(opts.current.map(s => [s.id, s]));
121    const merged: Session[] = [];
122    for (const entry of list.chats) {
123      const remote = fromHost.get(entry.id);
124      const local = mine.get(entry.id);
125      if (!remote) { if (local) merged.push(local); continue; }
126      merged.push(local && (isLive(entry.id) || isDirty(local) || newer(local.updatedAt, remote.session.updatedAt)) ? local : remote.session);
127      mine.delete(entry.id);
128    }
129    // Chats only this page has (made while the host was being read): kept, and saved when the writer starts.
130    const hostIds = new Set(list.chats.map(c => c.id));
131    const onlyHere = opts.current.filter(s => !hostIds.has(s.id));
132    const sessions = [...onlyHere, ...merged];
133    const recovered = takeLastMomentCopy(browser, sessions, revs);
134    return { sessions: recovered.sessions, revs, offline: false, moved, failed, recovered: recovered.ids };
135  } catch (e) {
136    if (isTransportError(e)) return { sessions: opts.current, revs: new Map(), offline: true, moved, failed, recovered: [] };
137    throw e;
138  }
139}
140
141/* ---------------------------------------------------------- the last-moment copy */
142
143/** The page is going away with chats the host has not confirmed: keep them (best effort, may not fit) for the next start. */
144export function keepLastMomentCopy(storage: StorageLike, sessions: Session[]): boolean {
145  try {
146    if (!sessions.length) { storage.removeItem(PENDING_KEY); return true; }
147    storage.setItem(PENDING_KEY, JSON.stringify(sessions));
148    return true;
149  } catch { return false; }
150}
151
152/** At start: chats from the last-moment copy that are newer than the host's (or the host lacks) replace the host's version in memory, to be saved. */
153export function takeLastMomentCopy(storage: StorageLike, sessions: Session[], revs: Map<string, number>): { sessions: Session[]; ids: string[] } {
154  let kept: Session[] = [];
155  try { const raw = storage.getItem(PENDING_KEY); if (raw) { const parsed = JSON.parse(raw) as unknown; if (Array.isArray(parsed)) kept = parsed.filter((s): s is Session => !!s && typeof (s as Session).id === 'string'); } } catch { kept = []; }
156  if (!kept.length) return { sessions, ids: [] };
157  const byId = new Map(sessions.map(s => [s.id, s]));
158  const ids: string[] = [];
159  for (const copy of kept) {
160    const have = byId.get(copy.id);
161    if (!have || newer(copy.updatedAt, have.updatedAt)) { byId.set(copy.id, copy); ids.push(copy.id); }
162  }
163  try { storage.removeItem(PENDING_KEY); } catch { /* removed at the next start */ }
164  if (!ids.length) return { sessions, ids };
165  const order = sessions.map(s => s.id);
166  const result = order.map(id => byId.get(id)!).concat([...byId.keys()].filter(id => !order.includes(id)).map(id => byId.get(id)!));
167  void revs;
168  return { sessions: result, ids };
169}