okami.mom/strata

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

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

main
10.4 KiB186 linesraw
1/**
2 * The chats, saved by the host as files (owner decision 11-04: the browser's 5 MB storage limit is gone).
3 *
4 *   <data folder>/chats/index.json         { v: 1, chats: [{ id, rev, createdAt, updatedAt, bytes, title }] }
5 *   <data folder>/chats/<id>.json          { "v": 1, "rev": N, "savedAt": ISO, "session": { ...the chat exactly as the page sent it... } }
6 *   <data folder>/chats/conflicts/         the version a later save displaced when two windows saved the same chat from an older copy
7 *
8 * - One file per chat. A save writes a temporary file next to it, flushes it and renames it over the chat: a crash or a full disk
9 *   in the middle leaves the older file whole. Temporary files left by a crash are removed at the next start.
10 * - `rev` counts the saves of a chat. A save that names a `baseRev` older than the stored one (a second window saved first) is still
11 *   written, but the version it displaces is kept in conflicts/ first, so nothing is lost.
12 * - The index is a list for fast start. If it is missing or does not match the files it is rebuilt from the files; a file that cannot
13 *   be read is reported and left exactly as it is.
14 * - Nothing is cut: the chat is stored byte for byte as received (a text splice, no re-serialising).
15 * - Owner-only: the folder is created private (POSIX 0700 and files 0600; on Windows the folder gets a protected ACL that its files
16 *   inherit), the same level as the rest of the profile.
17 */
18import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
19import { open, readFile, rename, unlink, mkdir, copyFile, readdir } from 'node:fs/promises';
20import { join } from 'node:path';
21
22export const CHAT_FORMAT = 1;
23const ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
24const RESERVED = /^(con|prn|aux|nul|com\d|lpt\d|index|import|conflicts)(\.|$)/i;
25const KEEP_CONFLICTS = 5;
26
27export class ChatStoreError extends Error {
28  constructor(message, status, code) { super(message); this.status = status; this.code = code; }
29}
30
31/** The disk operations, replaceable in tests to make a disk full, a permission failure or a crash in the middle of a write. */
32export const realIo = {
33  async writeFile(path, text) {
34    const handle = await open(path, 'w', 0o600);
35    try { await handle.writeFile(text, 'utf8'); await handle.sync(); } finally { await handle.close(); }
36  },
37  rename, unlink, copyFile, readFile, readdir, mkdir,
38};
39
40export const validChatId = id => typeof id === 'string' && ID.test(id) && !RESERVED.test(id);
41
42/** Map a failed disk operation to what the page is told: a full disk and a refused write are different words for the same "not saved". */
43export function storeFailure(error) {
44  if (error instanceof ChatStoreError) return error;
45  const code = error?.code;
46  if (code === 'ENOSPC' || code === 'EDQUOT' || code === 'EFBIG') return new ChatStoreError('The disk is full.', 507, 'disk-full');
47  if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS') return new ChatStoreError('Strata may not write its chat folder.', 403, 'permission');
48  return new ChatStoreError(error?.message ?? 'The chat could not be written.', 500, code ?? 'write-failed');
49}
50
51export function createChatStore({ dir, io = realIo, privateDir = () => {}, now = () => new Date() }) {
52  const root = join(dir, 'chats');
53  const conflictsDir = join(root, 'conflicts');
54  mkdirSync(root, { recursive: true, mode: 0o700 });
55  try { privateDir(root); } catch { /* the folder is inside the profile; the tighter ACL is best effort */ }
56  let tmpCount = 0;
57  let index = new Map();   // id -> entry
58  const damaged = new Set();
59
60  const fileOf = id => join(root, `${id}.json`);
61  const bytesOf = text => Buffer.byteLength(text, 'utf8');
62  const entryOf = (id, rev, session, bytes) => ({ id, rev, createdAt: session?.createdAt ?? null, updatedAt: session?.updatedAt ?? null, bytes, title: typeof session?.title === 'string' ? session.title.slice(0, 200) : '' });
63
64  // A chain, so saves of one host never overlap: the file, the index and the conflicts folder change one save at a time.
65  let chain = Promise.resolve();
66  const queue = work => { const run = chain.then(work, work); chain = run.catch(() => {}); return run; };
67
68  function loadSync() {
69    // Temporary files from a write that never finished.
70    let names = [];
71    try { names = readdirSync(root); } catch { /* empty */ }
72    for (const name of names) if (/\.tmp-\d+-\d+$/.test(name)) { try { unlinkSync(join(root, name)); } catch { /* left */ } }
73    const files = names.filter(n => n.endsWith('.json') && n !== 'index.json' && !/\.tmp-/.test(n)).map(n => n.slice(0, -5)).filter(validChatId);
74    let saved = null;
75    try { const parsed = JSON.parse(readFileSync(join(root, 'index.json'), 'utf8')); if (parsed?.v === CHAT_FORMAT && Array.isArray(parsed.chats)) saved = parsed.chats; } catch { /* rebuilt below */ }
76    const map = new Map();
77    if (saved) for (const e of saved) if (e && validChatId(e.id) && files.includes(e.id)) map.set(e.id, e);
78    // Files the index does not know (a crash before the index was written, an index lost): read from the files.
79    for (const id of files) {
80      if (map.has(id)) continue;
81      try {
82        const parsed = JSON.parse(readFileSync(fileOf(id), 'utf8'));
83        if (parsed?.v !== CHAT_FORMAT || !parsed.session || parsed.session.id !== id) throw new Error('not a chat file');
84        map.set(id, entryOf(id, Number(parsed.rev) || 1, parsed.session, statSync(fileOf(id)).size));
85      } catch { damaged.add(id); }
86    }
87    index = map;
88  }
89  loadSync();
90
91  async function writeAtomic(path, text) {
92    const temp = `${path}.tmp-${process.pid}-${++tmpCount}`;
93    try {
94      await io.writeFile(temp, text);
95      for (let attempt = 0; ; attempt++) {
96        try { await io.rename(temp, path); break; }
97        catch (e) { if (attempt >= 5 || !['EPERM', 'EBUSY', 'EACCES'].includes(e?.code)) throw e; await new Promise(r => setTimeout(r, 40 * (attempt + 1))); }   // an antivirus scan holds the file for a moment on Windows
98      }
99    } catch (e) {
100      try { await io.unlink(temp); } catch { /* nothing to remove */ }
101      throw e;
102    }
103  }
104
105  async function writeIndex() {
106    const list = [...index.values()];
107    try { await writeAtomic(join(root, 'index.json'), JSON.stringify({ v: CHAT_FORMAT, savedAt: now().toISOString(), chats: list })); }
108    catch { /* only a list: it is rebuilt from the files when it does not match */ }
109  }
110
111  async function keepDisplaced(id, rev) {
112    try {
113      await io.mkdir(conflictsDir, { recursive: true });
114      await io.copyFile(fileOf(id), join(conflictsDir, `${id}.rev${rev}.json`));
115      const mine = (await io.readdir(conflictsDir)).filter(n => n.startsWith(`${id}.rev`)).sort((a, b) => Number(a.match(/rev(\d+)/)?.[1]) - Number(b.match(/rev(\d+)/)?.[1]));
116      for (const old of mine.slice(0, Math.max(0, mine.length - KEEP_CONFLICTS))) { try { await io.unlink(join(conflictsDir, old)); } catch { /* left */ } }
117    } catch (e) {
118      throw storeFailure(e);   // not saved rather than saved over the only copy of the other window's work
119    }
120  }
121
122  return {
123    root,
124    /** The chats, newest first. */
125    list() {
126      const chats = [...index.values()].sort((a, b) => String(b.createdAt ?? '').localeCompare(String(a.createdAt ?? '')) || a.id.localeCompare(b.id));
127      return { v: CHAT_FORMAT, chats, damaged: [...damaged] };
128    },
129    has: id => index.has(id),
130    rev: id => index.get(id)?.rev ?? 0,
131    /** The stored file text of a chat ({"v","rev","savedAt","session"}), or null. */
132    async read(id) {
133      if (!validChatId(id) || !index.has(id)) return null;
134      try { return await io.readFile(fileOf(id), 'utf8'); }
135      catch (e) { if (e?.code === 'ENOENT') { index.delete(id); return null; } throw storeFailure(e); }
136    },
137    /**
138     * Save one chat. `sessionText` is the chat's JSON as the page wrote it. Resolves { id, rev, bytes, conflict }.
139     * Rejects with a ChatStoreError (status 400 for a chat that is not a chat, 507 disk full, 403 refused, 500 other): nothing was changed.
140     */
141    save(id, sessionText, { baseRev = null } = {}) {
142      if (!validChatId(id)) return Promise.reject(new ChatStoreError('That is not a chat id.', 400, 'bad-id'));
143      let session;
144      try { session = JSON.parse(sessionText); } catch { return Promise.reject(new ChatStoreError('The chat must be JSON.', 400, 'bad-json')); }
145      if (!session || typeof session !== 'object' || Array.isArray(session) || session.id !== id) return Promise.reject(new ChatStoreError('The chat does not match its id.', 400, 'bad-chat'));
146      const body = sessionText.trim();
147      return queue(async () => {
148        const current = index.get(id);
149        const rev = (current?.rev ?? 0) + 1;
150        let conflict = false;
151        if (current && baseRev !== null && Number(baseRev) !== current.rev) { conflict = true; await keepDisplaced(id, current.rev); }
152        const text = `{"v":${CHAT_FORMAT},"rev":${rev},"savedAt":${JSON.stringify(now().toISOString())},"session":${body}}`;
153        try { await writeAtomic(fileOf(id), text); } catch (e) { throw storeFailure(e); }
154        const bytes = bytesOf(text);
155        index.set(id, entryOf(id, rev, session, bytes));
156        damaged.delete(id);
157        await writeIndex();
158        return { id, rev, bytes, conflict };
159      });
160    },
161    /** Delete a chat (the person deleted it). A chat that is not there is already gone. */
162    remove(id) {
163      if (!validChatId(id)) return Promise.reject(new ChatStoreError('That is not a chat id.', 400, 'bad-id'));
164      return queue(async () => {
165        try { await io.unlink(fileOf(id)); } catch (e) { if (e?.code !== 'ENOENT') throw storeFailure(e); }
166        const had = index.delete(id);
167        await writeIndex();
168        return { id, removed: had };
169      });
170    },
171    /** Chats from the browser's old storage: every one the host does not have yet is saved; the ones it has are left alone. */
172    async importMany(sessions) {
173      const imported = [], skipped = [], failed = [];
174      for (const session of Array.isArray(sessions) ? sessions : []) {
175        const id = session?.id;
176        if (!validChatId(id)) { failed.push({ id: String(id ?? ''), error: 'not a chat id' }); continue; }
177        if (index.has(id)) { skipped.push(id); continue; }
178        try { await this.save(id, JSON.stringify(session)); imported.push(id); }
179        catch (e) { failed.push({ id, error: e.message, code: e.code }); if (e.code === 'disk-full') break; }
180      }
181      return { imported, skipped, failed };
182    },
183    /** Wait until every save queued so far is on disk (tests, shutdown). */
184    idle: () => chain,
185  };
186}