okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
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 { 42getItem ( key :string ) :string | null ; 43setItem ( key :string , value :string ) :void ; 44removeItem ( key :string ) :void ; 45key ( index :number ) :string | null ; 46readonly length :number ; 47} 48 49/** The JSON text sent for one chat: the chat exactly as it is. */ 50export function serializeSession ( session :Session ) :string { 51return 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 { 56return JSON . stringify ( sessions ); 57} 58 59/* ------------------------------------------------------------- the browser's old storage (read only) */ 60 61function readIndex ( storage :StorageLike ) :string [] { 62try { 63const raw = storage . getItem ( SESSION_INDEX_KEY ); 64if ( ! raw ) return []; 65const parsed = JSON . parse ( raw ) as { ids ?:unknown }; 66return Array . isArray ( parsed . ids ) ?parsed . ids . filter (( id ) :id isstring => typeof id === 'string' ) :[]; 67} catch { 68return []; 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 [] } { 77const damaged :string [] = []; 78const found = new Map < string , Session >(); 79try { 80const raw = storage . getItem ( LEGACY_SESSIONS_KEY ); 81if ( raw ) { 82const parsed = JSON . parse ( raw ) as unknown ; 83if ( Array . isArray ( parsed )) { 84parsed . forEach (( entry , n ) => { 85if ( ! entry || typeof entry !== 'object' ) return ; 86const s = entry as Session ; 87const id = typeof s . id === 'string' && s . id ?s . id :`legacy_ ${ n } ` ; 88found . set ( id , id === s . id ?s :{ ...s , id}); 89}); 90} else damaged . push ( LEGACY_SESSIONS_KEY ); 91} 92} catch { damaged . push ( LEGACY_SESSIONS_KEY ); } 93try { 94const keys :string [] = []; 95for ( let i = 0 ; i < storage . length ; i ++ ) { 96const key = storage . key ( i ); 97if ( key && key . startsWith ( SESSION_KEY_PREFIX )) keys . push ( key ); 98} 99for ( const key of keys ) { 100try { 101const parsed = JSON . parse ( storage . getItem ( key ) ?? 'null' ) as Session | null ; 102if ( parsed && typeof parsed === 'object' && typeof parsed . id === 'string' ) found . set ( parsed . id , parsed ); 103else damaged . push ( key ); 104} catch { damaged . push ( key ); } 105} 106} catch { /* storage not readable: nothing to load */ } 107const rank = new Map ( readIndex ( storage ). map (( id , i ) => [ id , i ])); 108const sessions = [ ...found . values ()]. sort (( a , b ) => { 109const ra = rank . get ( a . id ), rb = rank . get ( b . id ); 110if ( ra !== undefined && rb !== undefined ) return ra - rb ; 111if ( ra !== undefined ) return - 1 ; 112if ( rb !== undefined ) return 1 ; 113return String ( b . createdAt ?? '' ) < String ( a . createdAt ?? '' ) ?- 1 :1 ; 114}); 115return { sessions, damaged}; 116} 117 118/* ------------------------------------------------------------- the host */ 119 120export class TransportError extends Error { 121constructor ( 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 { 128list () :Promise <{ chats :HostChatEntry []; damaged ?:string [] }>; 129get ( id :string ) :Promise <{ rev :number ; session :Session } | null >; 130put ( id :string , text :string , baseRev :number | null ) :Promise <{ rev :number ; conflict :boolean }>; 131remove ( id :string ) :Promise < void >; 132importMany ( 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 { 138id :string ; 139reason :FailureReason ; 140message :string ; 141} 142 143export interface SaveResult { 144ok :boolean ; 145failed :SaveFailure []; 146/** How many chats were saved by this pass. */ 147written :number ; 148deleted :number ; 149} 150 151export function failureReason ( error :unknown ) :FailureReason { 152const e = error as Partial < TransportError > | null ; 153if ( e && e . name === 'TransportError' ) { 154if ( e . network ) return 'offline' ; 155if ( e . code === 'disk-full' || e . status === 507 ) return 'disk-full' ; 156if ( e . code === 'permission' || e . status === 403 ) return 'permission' ; 157} 158return 'other' ; 159} 160 161export interface SessionWriterOptions { 162transport :ChatTransport ; 163delayMs ?:number ; 164/** After a pass with failures the unsaved chats are tried again after this long. */ 165retryMs ?:number ; 166/** Counts a serialisation of one chat; for tests. */ 167onSerialize ?:( session :Session ) => void ; 168/** Called after every pass, with what was saved and which chats the host did not take. */ 169onResult ?:( result :SaveResult ) => void ; 170/** The chats the host already has: [id, rev]. Only these (and chats this writer saved) are ever removed from it. */ 171known ?:Iterable <[ string , number ]>; 172/** Start saving at once. The page leaves it off until the host's chats have been read. */ 173enabled ?:boolean ; 174} 175 176export function createSessionWriter ( options :SessionWriterOptions ) { 177const transport = options . transport ; 178const delayMs = options . delayMs ?? 1_000 ; 179const retryMs = options . retryMs ?? 8_000 ; 180let enabled = options . enabled ?? true ; 181let timer :ReturnType < typeof setTimeout > | null = null ; 182let retryTimer :ReturnType < typeof setTimeout > | null = null ; 183let pending :Session [] | null = null ; 184let lastSessions :Session [] = []; 185let running :Promise < SaveResult > | null = null ; 186let rerun = false ; 187let lastResult :SaveResult = { ok :true , failed :[], written :0 , deleted :0 }; 188let failures = 0 ; 189// Chat object -> its JSON. WeakMap: a replaced chat is forgotten with its object. 190const 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). 192const sent = new Map < string , string >(); 193const revs = new Map < string , number >( options . known ?? []); 194const known = new Set < string >( revs . keys ()); 195const failedIds = new Set < string >(); 196 197const textOf = ( s :Session ) :string => { 198let text = cache . get ( s ); 199if ( text === undefined ) { 200options . onSerialize ?.( s ); 201text = serializeSession ( s ); 202cache . set ( s , text ); 203} 204return text ; 205}; 206 207async function pass () :Promise < SaveResult > { 208const sessions = pending ; 209pending = null ; 210if ( ! sessions ) return lastResult ; 211lastSessions = sessions ; 212const ids = new Set ( sessions . map ( s => s . id )); 213const failed :SaveFailure [] = []; 214let written = 0 , deleted = 0 ; 215 216// Removed chats first. 217for ( const id of [ ...known ]) { 218if ( ids . has ( id )) continue ; 219try { await transport . remove ( id ); known . delete ( id ); sent . delete ( id ); revs . delete ( id ); failedIds . delete ( id ); deleted ++ ; } 220catch ( error ) { failed . push ({ id, reason :failureReason ( error ), message :error instanceof Error ?error . message :String ( error ) }); } 221} 222for ( const s of sessions ) { 223const text = textOf ( s ); 224if ( sent . get ( s . id ) === text ) { failedIds . delete ( s . id ); continue ; } 225try { 226const saved = await transport . put ( s . id , text , revs . get ( s . id ) ?? null ); 227revs . set ( s . id , saved . rev ); known . add ( s . id ); sent . set ( s . id , text ); failedIds . delete ( s . id ); 228written ++ ; 229} catch ( error ) { 230// The host keeps the last good file of this chat; the chat stays whole in memory and is tried again. 231failedIds . add ( s . id ); 232failed . push ({ id :s . id , reason :failureReason ( error ), message :error instanceof Error ?error . message :String ( error ) }); 233} 234} 235lastResult = { ok :failedIds . size === 0 && failed . length === 0 , failed, written, deleted}; 236if ( retryTimer !== null ) { clearTimeout ( retryTimer ); retryTimer = null ; } 237if ( ! lastResult . ok ) { 238// Tried again, a little later each time (up to a minute); the timer never keeps a closing page or process alive. 239failures = Math . min ( failures + 1 , 6 ); 240retryTimer = 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 ; 243options . onResult ?.( lastResult ); 244return lastResult ; 245} 246 247const flush = () :Promise < SaveResult > => { 248if ( timer !== null ) { clearTimeout ( timer ); timer = null ; } 249if ( ! 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. 251if ( pending === null && failedIds . size ) pending = lastSessions ; 252if ( running ) { rerun = true ; return running ; } 253running = ( async () => { 254let result = lastResult ; 255do { rerun = false ; result = await pass (); } while ( rerun || pending !== null ); 256return result ; 257})(). finally (() => { running = null ; }); 258return running ; 259}; 260 261const schedule = ( sessions :Session []) => { 262pending = sessions ; 263if ( enabled && timer === null ) timer = setTimeout (() => { timer = null ; void flush (); }, delayMs ); 264}; 265 266return { 267 schedule, 268 flush, 269hasPending :() => pending !== null || running !== null , 270/** Start saving (the host's chats have been read). Whatever was scheduled meanwhile is saved now. */ 271enable () { enabled = true ; if ( pending !== null ) void flush (); }, 272/** The chats whose newest state is not on the host. */ 273unsaved :() :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. */ 275adopt ( 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). */ 277forget ( id :string ) { known . delete ( id ); revs . delete ( id ); sent . delete ( id ); failedIds . delete ( id ); }, 278rev :( 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). */ 280dirty ( 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. */ 282notOnHost () :Session [] { 283const list = pending ?? lastSessions ; 284return list . filter ( s => sent . get ( s . id ) !== textOf ( s )); 285}, 286}; 287}