okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
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 { 28constructor ( 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 = { 33async writeFile ( path , text ) { 34const handle = await open ( path , 'w' , 0o600 ); 35try { 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 ) { 44if ( error instanceof ChatStoreError ) return error ; 45const code = error ?. code ; 46if ( code === 'ENOSPC' || code === 'EDQUOT' || code === 'EFBIG' ) return new ChatStoreError ( 'The disk is full.' , 507 , 'disk-full' ); 47if ( code === 'EACCES' || code === 'EPERM' || code === 'EROFS' ) return new ChatStoreError ( 'Strata may not write its chat folder.' , 403 , 'permission' ); 48return 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 () }) { 52const root = join ( dir , 'chats' ); 53const conflictsDir = join ( root , 'conflicts' ); 54mkdirSync ( root , { recursive :true , mode :0o700 }); 55try { privateDir ( root ); } catch { /* the folder is inside the profile; the tighter ACL is best effort */ } 56let tmpCount = 0 ; 57let index = new Map (); // id -> entry 58const damaged = new Set (); 59 60const fileOf = id => join ( root , ` ${ id } .json` ); 61const bytesOf = text => Buffer . byteLength ( text , 'utf8' ); 62const 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. 65let chain = Promise . resolve (); 66const queue = work => { const run = chain . then ( work , work ); chain = run . catch (() => {}); return run ; }; 67 68function loadSync () { 69// Temporary files from a write that never finished. 70let names = []; 71try { names = readdirSync ( root ); } catch { /* empty */ } 72for ( const name of names ) if ( / \.tmp-\d + -\d + $ / . test ( name )) { try { unlinkSync ( join ( root , name )); } catch { /* left */ } } 73const files = names . filter ( n => n . endsWith ( '.json' ) && n !== 'index.json' && ! /\.tmp- / . test ( n )). map ( n => n . slice ( 0 , - 5 )). filter ( validChatId ); 74let saved = null ; 75try { 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 */ } 76const map = new Map (); 77if ( 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. 79for ( const id of files ) { 80if ( map . has ( id )) continue ; 81try { 82const parsed = JSON . parse ( readFileSync ( fileOf ( id ), 'utf8' )); 83if ( parsed ?. v !== CHAT_FORMAT || ! parsed . session || parsed . session . id !== id ) throw new Error ( 'not a chat file' ); 84map . set ( id , entryOf ( id , Number ( parsed . rev ) || 1 , parsed . session , statSync ( fileOf ( id )). size )); 85} catch { damaged . add ( id ); } 86} 87index = map ; 88} 89loadSync (); 90 91async function writeAtomic ( path , text ) { 92const temp = ` ${ path } .tmp- ${ process . pid } - ${ ++ tmpCount } ` ; 93try { 94await io . writeFile ( temp , text ); 95for ( let attempt = 0 ; ; attempt ++ ) { 96try { await io . rename ( temp , path ); break ; } 97catch ( 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 ) { 100try { await io . unlink ( temp ); } catch { /* nothing to remove */ } 101throw e ; 102} 103} 104 105async function writeIndex () { 106const list = [ ...index . values ()]; 107try { await writeAtomic ( join ( root , 'index.json' ), JSON . stringify ({ v :CHAT_FORMAT , savedAt :now (). toISOString (), chats :list })); } 108catch { /* only a list: it is rebuilt from the files when it does not match */ } 109} 110 111async function keepDisplaced ( id , rev ) { 112try { 113await io . mkdir ( conflictsDir , { recursive :true }); 114await io . copyFile ( fileOf ( id ), join ( conflictsDir , ` ${ id } .rev ${ rev } .json` )); 115const 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 ])); 116for ( 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 ) { 118throw storeFailure ( e ); // not saved rather than saved over the only copy of the other window's work 119} 120} 121 122return { 123 root, 124/** The chats, newest first. */ 125list () { 126const chats = [ ...index . values ()]. sort (( a , b ) => String ( b . createdAt ?? '' ). localeCompare ( String ( a . createdAt ?? '' )) || a . id . localeCompare ( b . id )); 127return { v :CHAT_FORMAT , chats, damaged :[ ...damaged ] }; 128}, 129has :id => index . has ( id ), 130rev :id => index . get ( id )?. rev ?? 0 , 131/** The stored file text of a chat ({"v","rev","savedAt","session"}), or null. */ 132async read ( id ) { 133if ( ! validChatId ( id ) || ! index . has ( id )) return null ; 134try { return await io . readFile ( fileOf ( id ), 'utf8' ); } 135catch ( 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*/ 141save ( id , sessionText , { baseRev= null } = {}) { 142if ( ! validChatId ( id )) return Promise . reject ( new ChatStoreError ( 'That is not a chat id.' , 400 , 'bad-id' )); 143let session ; 144try { session = JSON . parse ( sessionText ); } catch { return Promise . reject ( new ChatStoreError ( 'The chat must be JSON.' , 400 , 'bad-json' )); } 145if ( ! 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' )); 146const body = sessionText . trim (); 147return queue ( async () => { 148const current = index . get ( id ); 149const rev = ( current ?. rev ?? 0 ) + 1 ; 150let conflict = false ; 151if ( current && baseRev !== null && Number ( baseRev ) !== current . rev ) { conflict = true ; await keepDisplaced ( id , current . rev ); } 152const text = `{"v": ${ CHAT_FORMAT } ,"rev": ${ rev } ,"savedAt": ${ JSON . stringify ( now (). toISOString ())} ,"session": ${ body } }` ; 153try { await writeAtomic ( fileOf ( id ), text ); } catch ( e ) { throw storeFailure ( e ); } 154const bytes = bytesOf ( text ); 155index . set ( id , entryOf ( id , rev , session , bytes )); 156damaged . delete ( id ); 157await writeIndex (); 158return { id, rev, bytes, conflict}; 159}); 160}, 161/** Delete a chat (the person deleted it). A chat that is not there is already gone. */ 162remove ( id ) { 163if ( ! validChatId ( id )) return Promise . reject ( new ChatStoreError ( 'That is not a chat id.' , 400 , 'bad-id' )); 164return queue ( async () => { 165try { await io . unlink ( fileOf ( id )); } catch ( e ) { if ( e ?. code !== 'ENOENT' ) throw storeFailure ( e ); } 166const had = index . delete ( id ); 167await writeIndex (); 168return { 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. */ 172async importMany ( sessions ) { 173const imported = [], skipped = [], failed = []; 174for ( const session of Array . isArray ( sessions ) ?sessions :[]) { 175const id = session ?. id ; 176if ( ! validChatId ( id )) { failed . push ({ id :String ( id ?? '' ), error :'not a chat id' }); continue ; } 177if ( index . has ( id )) { skipped . push ( id ); continue ; } 178try { await this . save ( id , JSON . stringify ( session )); imported . push ( id ); } 179catch ( e ) { failed . push ({ id, error :e . message , code :e . code }); if ( e . code === 'disk-full' ) break ; } 180} 181return { imported, skipped, failed}; 182}, 183/** Wait until every save queued so far is on disk (tests, shutdown). */ 184idle :() => chain , 185}; 186}