okami.mom/strata

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

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

main
13.3 KiB287 linesraw
1import type { Session } from './types';
2
3/**
4 * Saving the chats: by the app host, as files (owner decision 11-04; #5192, #3604, #3603).
5 *
6 * The chats used to live in the browser's localStorage, which holds about 5 MB for a whole origin. To fit, the writer first cut
7 * long fields and dropped old messages and chats (#5192), and after that fix a full storage meant chats that could not be saved
8 * at all. Now the host keeps one file per chat in the profile's data folder (server/chat-store.mjs) and the page only sends the
9 * chats that changed. The write side keeps the rules of the renderer-memory fix (#3604, #3603):
10 *
11 *  1. Coalesce: the newest state wins and at most one save happens per `delayMs`. The caller flushes when a turn ends or the
12 *     page goes away.
13 *  2. Only the chats that changed are serialised again (a chat is replaced by a new object when it changes, the store never
14 *     mutates), so the previous JSON of every other chat is reused by object identity, and only those are sent.
15 *
16 * And, new with the files:
17 *  - A chat is sent exactly as it is (JSON.stringify of the chat): no clipping, no dropped messages or chats.
18 *  - A save the host refuses (disk full, no permission) or cannot be asked (the host is not answering) leaves the chat whole in
19 *    memory and marked unsaved; it is tried again at the next change and on a timer, and the failure is reported through
20 *    `onResult` so the caller can say so and offer the unsaved chats (`unsaved()`, `exportSessions`).
21 *  - A chat removed from the list is removed on the host. Only chats this writer has seen are ever removed.
22 *  - The writer does not save before `enable()` (the first read of the host's chats has to land first, so an older copy in the
23 *    page never replaces a newer file).
24 *
25 * The browser's old storage is read once for the move to files (`readBrowserSessions`) and is never written or emptied again:
26 * it stays as a fallback for one release.
27 */
28
29/** The old whole-list entry of the released versions (0.2.10 and before). */
30export const LEGACY_SESSIONS_KEY = 'strata.sessions.v1';
31/** The order of the chats in the short-lived per-chat browser layout (this branch before the files). */
32export const SESSION_INDEX_KEY = 'strata.sessions.v2';
33/** One chat per entry in that layout: this prefix plus the chat id. */
34export const SESSION_KEY_PREFIX = 'strata.session.v2.';
35/** Set when the browser's chats were handed to the host. After it, the host's files are the only truth. */
36export const HOST_FLAG_KEY = 'strata.chats.host.v1';
37/** Chats that were not yet on the host when the page went away (a last-moment copy, taken back at the next start). */
38export const PENDING_KEY = 'strata.chats.pending.v1';
39
40/** The part of `Storage` that is read from. */
41export interface StorageLike {
42  getItem(key: string): string | null;
43  setItem(key: string, value: string): void;
44  removeItem(key: string): void;
45  key(index: number): string | null;
46  readonly length: number;
47}
48
49/** The JSON text sent for one chat: the chat exactly as it is. */
50export function serializeSession(session: Session): string {
51  return JSON.stringify(session);
52}
53
54/** The chats as one JSON text, for keeping a copy by hand when they cannot be saved. */
55export function exportSessions(sessions: Session[]): string {
56  return JSON.stringify(sessions);
57}
58
59/* ------------------------------------------------------------- the browser's old storage (read only) */
60
61function readIndex(storage: StorageLike): string[] {
62  try {
63    const raw = storage.getItem(SESSION_INDEX_KEY);
64    if (!raw) return [];
65    const parsed = JSON.parse(raw) as { ids?: unknown };
66    return Array.isArray(parsed.ids) ? parsed.ids.filter((id): id is string => typeof id === 'string') : [];
67  } catch {
68    return [];
69  }
70}
71
72/**
73 * Every chat in the browser's storage, from both layouts: one entry per chat (strata.session.v2.<id>) and the old whole list
74 * (strata.sessions.v1). Where a chat is in both, the per-chat entry wins. Nothing is written, moved or removed.
75 */
76export function readBrowserSessions(storage: StorageLike): { sessions: Session[]; damaged: string[] } {
77  const damaged: string[] = [];
78  const found = new Map<string, Session>();
79  try {
80    const raw = storage.getItem(LEGACY_SESSIONS_KEY);
81    if (raw) {
82      const parsed = JSON.parse(raw) as unknown;
83      if (Array.isArray(parsed)) {
84        parsed.forEach((entry, n) => {
85          if (!entry || typeof entry !== 'object') return;
86          const s = entry as Session;
87          const id = typeof s.id === 'string' && s.id ? s.id : `legacy_${n}`;
88          found.set(id, id === s.id ? s : { ...s, id });
89        });
90      } else damaged.push(LEGACY_SESSIONS_KEY);
91    }
92  } catch { damaged.push(LEGACY_SESSIONS_KEY); }
93  try {
94    const keys: string[] = [];
95    for (let i = 0; i < storage.length; i++) {
96      const key = storage.key(i);
97      if (key && key.startsWith(SESSION_KEY_PREFIX)) keys.push(key);
98    }
99    for (const key of keys) {
100      try {
101        const parsed = JSON.parse(storage.getItem(key) ?? 'null') as Session | null;
102        if (parsed && typeof parsed === 'object' && typeof parsed.id === 'string') found.set(parsed.id, parsed);
103        else damaged.push(key);
104      } catch { damaged.push(key); }
105    }
106  } catch { /* storage not readable: nothing to load */ }
107  const rank = new Map(readIndex(storage).map((id, i) => [id, i]));
108  const sessions = [...found.values()].sort((a, b) => {
109    const ra = rank.get(a.id), rb = rank.get(b.id);
110    if (ra !== undefined && rb !== undefined) return ra - rb;
111    if (ra !== undefined) return -1;
112    if (rb !== undefined) return 1;
113    return String(b.createdAt ?? '') < String(a.createdAt ?? '') ? -1 : 1;
114  });
115  return { sessions, damaged };
116}
117
118/* ------------------------------------------------------------- the host */
119
120export class TransportError extends Error {
121  constructor(message: string, readonly status: number, readonly code: string | undefined, readonly network = false) { super(message); this.name = 'TransportError'; }
122}
123
124export interface HostChatEntry { id: string; rev: number; createdAt?: string | null; updatedAt?: string | null }
125
126/** What the page asks of the host about chats (chat-sync.ts makes the real one; a test passes a fake). */
127export interface ChatTransport {
128  list(): Promise<{ chats: HostChatEntry[]; damaged?: string[] }>;
129  get(id: string): Promise<{ rev: number; session: Session } | null>;
130  put(id: string, text: string, baseRev: number | null): Promise<{ rev: number; conflict: boolean }>;
131  remove(id: string): Promise<void>;
132  importMany(sessions: Session[]): Promise<{ imported: string[]; skipped: string[]; failed: { id: string; error: string; code?: string }[] }>;
133}
134
135export type FailureReason = 'disk-full' | 'permission' | 'offline' | 'other';
136
137export interface SaveFailure {
138  id: string;
139  reason: FailureReason;
140  message: string;
141}
142
143export interface SaveResult {
144  ok: boolean;
145  failed: SaveFailure[];
146  /** How many chats were saved by this pass. */
147  written: number;
148  deleted: number;
149}
150
151export function failureReason(error: unknown): FailureReason {
152  const e = error as Partial<TransportError> | null;
153  if (e && e.name === 'TransportError') {
154    if (e.network) return 'offline';
155    if (e.code === 'disk-full' || e.status === 507) return 'disk-full';
156    if (e.code === 'permission' || e.status === 403) return 'permission';
157  }
158  return 'other';
159}
160
161export interface SessionWriterOptions {
162  transport: ChatTransport;
163  delayMs?: number;
164  /** After a pass with failures the unsaved chats are tried again after this long. */
165  retryMs?: number;
166  /** Counts a serialisation of one chat; for tests. */
167  onSerialize?: (session: Session) => void;
168  /** Called after every pass, with what was saved and which chats the host did not take. */
169  onResult?: (result: SaveResult) => void;
170  /** The chats the host already has: [id, rev]. Only these (and chats this writer saved) are ever removed from it. */
171  known?: Iterable<[string, number]>;
172  /** Start saving at once. The page leaves it off until the host's chats have been read. */
173  enabled?: boolean;
174}
175
176export function createSessionWriter(options: SessionWriterOptions) {
177  const transport = options.transport;
178  const delayMs = options.delayMs ?? 1_000;
179  const retryMs = options.retryMs ?? 8_000;
180  let enabled = options.enabled ?? true;
181  let timer: ReturnType<typeof setTimeout> | null = null;
182  let retryTimer: ReturnType<typeof setTimeout> | null = null;
183  let pending: Session[] | null = null;
184  let lastSessions: Session[] = [];
185  let running: Promise<SaveResult> | null = null;
186  let rerun = false;
187  let lastResult: SaveResult = { ok: true, failed: [], written: 0, deleted: 0 };
188  let failures = 0;
189  // Chat object -> its JSON. WeakMap: a replaced chat is forgotten with its object.
190  const cache = new WeakMap<Session, string>();
191  // The JSON of each chat as the host last confirmed it (or as it was read from the host).
192  const sent = new Map<string, string>();
193  const revs = new Map<string, number>(options.known ?? []);
194  const known = new Set<string>(revs.keys());
195  const failedIds = new Set<string>();
196
197  const textOf = (s: Session): string => {
198    let text = cache.get(s);
199    if (text === undefined) {
200      options.onSerialize?.(s);
201      text = serializeSession(s);
202      cache.set(s, text);
203    }
204    return text;
205  };
206
207  async function pass(): Promise<SaveResult> {
208    const sessions = pending;
209    pending = null;
210    if (!sessions) return lastResult;
211    lastSessions = sessions;
212    const ids = new Set(sessions.map(s => s.id));
213    const failed: SaveFailure[] = [];
214    let written = 0, deleted = 0;
215
216    // Removed chats first.
217    for (const id of [...known]) {
218      if (ids.has(id)) continue;
219      try { await transport.remove(id); known.delete(id); sent.delete(id); revs.delete(id); failedIds.delete(id); deleted++; }
220      catch (error) { failed.push({ id, reason: failureReason(error), message: error instanceof Error ? error.message : String(error) }); }
221    }
222    for (const s of sessions) {
223      const text = textOf(s);
224      if (sent.get(s.id) === text) { failedIds.delete(s.id); continue; }
225      try {
226        const saved = await transport.put(s.id, text, revs.get(s.id) ?? null);
227        revs.set(s.id, saved.rev); known.add(s.id); sent.set(s.id, text); failedIds.delete(s.id);
228        written++;
229      } catch (error) {
230        // The host keeps the last good file of this chat; the chat stays whole in memory and is tried again.
231        failedIds.add(s.id);
232        failed.push({ id: s.id, reason: failureReason(error), message: error instanceof Error ? error.message : String(error) });
233      }
234    }
235    lastResult = { ok: failedIds.size === 0 && failed.length === 0, failed, written, deleted };
236    if (retryTimer !== null) { clearTimeout(retryTimer); retryTimer = null; }
237    if (!lastResult.ok) {
238      // Tried again, a little later each time (up to a minute); the timer never keeps a closing page or process alive.
239      failures = Math.min(failures + 1, 6);
240      retryTimer = setTimeout(() => { retryTimer = null; if (pending === null) pending = lastSessions; void flush(); }, Math.min(retryMs * 2 ** (failures - 1), 60_000));
241      (retryTimer as unknown as { unref?: () => void }).unref?.();
242    } else failures = 0;
243    options.onResult?.(lastResult);
244    return lastResult;
245  }
246
247  const flush = (): Promise<SaveResult> => {
248    if (timer !== null) { clearTimeout(timer); timer = null; }
249    if (!enabled) return Promise.resolve(lastResult);
250    // Nothing new, but a chat the host refused earlier: a flush (a turn ended, the page is going away) tries it again.
251    if (pending === null && failedIds.size) pending = lastSessions;
252    if (running) { rerun = true; return running; }
253    running = (async () => {
254      let result = lastResult;
255      do { rerun = false; result = await pass(); } while (rerun || pending !== null);
256      return result;
257    })().finally(() => { running = null; });
258    return running;
259  };
260
261  const schedule = (sessions: Session[]) => {
262    pending = sessions;
263    if (enabled && timer === null) timer = setTimeout(() => { timer = null; void flush(); }, delayMs);
264  };
265
266  return {
267    schedule,
268    flush,
269    hasPending: () => pending !== null || running !== null,
270    /** Start saving (the host's chats have been read). Whatever was scheduled meanwhile is saved now. */
271    enable() { enabled = true; if (pending !== null) void flush(); },
272    /** The chats whose newest state is not on the host. */
273    unsaved: (): Session[] => lastSessions.filter(s => failedIds.has(s.id)),
274    /** A chat that was read from the host (or arrived from another window): its JSON and revision are what the host has. */
275    adopt(session: Session, rev: number | null) { known.add(session.id); if (rev === null) revs.delete(session.id); else revs.set(session.id, rev); sent.set(session.id, serializeSession(session)); failedIds.delete(session.id); },
276    /** A chat the host no longer has (removed from another window). */
277    forget(id: string) { known.delete(id); revs.delete(id); sent.delete(id); failedIds.delete(id); },
278    rev: (id: string) => revs.get(id) ?? 0,
279    /** True when the page holds a newer state of this chat than the host has (scheduled, in flight or refused). */
280    dirty(session: Session) { return sent.get(session.id) !== textOf(session); },
281    /** The chats not confirmed by the host right now: what to keep if the page goes away this instant. */
282    notOnHost(): Session[] {
283      const list = pending ?? lastSessions;
284      return list.filter(s => sent.get(s.id) !== textOf(s));
285    },
286  };
287}