okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
1import type { Session } from './types' ; 2import { 3HOST_FLAG_KEY , PENDING_KEY , TransportError , readBrowserSessions , 4type 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 { 17const headers = ( extra :Record < string , string > = {}) => ({ 'x-strata-client' :'ui' , 'x-strata-window' :WINDOW_ID , ...extra }); 18async function call ( method :string , path :string , init :{ body ?:string ; headers ?:Record < string , string > } = {}) :Promise < Response > { 19let res :Response ; 20try { res = await fetchImpl ( ` ${ BASE ()} ${ path } ` , { method, headers :headers ( init . headers ), body :init . body }); } 21catch ( e ) { throw new TransportError ( e instanceof Error ?e . message :'The host did not answer.' , 0 , 'offline' , true ); } 22if ( res . ok ) return res ; 23let code :string | undefined , message = `Request failed ( ${ res . status } )` ; 24try { const data = await res . json () as { error ?:string ; code ?:string }; code = data . code ; if ( data . error ) message = data . error ; } catch { /* no body */ } 25throw new TransportError ( message , res . status , code ); 26} 27return { 28async list () { return await ( await call ( 'GET' , '/api/chats' )). json () as { chats :HostChatEntry []; damaged ?:string [] }; }, 29async get ( id ) { 30try { 31const data = await ( await call ( 'GET' , `/api/chats/ ${ encodeURIComponent ( id )} ` )). json () as { rev :number ; session :Session }; 32return { rev :Number ( data . rev ) || 0 , session :data . session }; 33} catch ( e ) { if ( isTransportError ( e ) && ( e as TransportError ). status === 404 ) return null ; throw e ; } 34}, 35async put ( id , text , baseRev ) { 36const res = await call ( 'PUT' , `/api/chats/ ${ encodeURIComponent ( id )} ` , { body :text , headers :{ 'content-type' :'application/json' , ...( baseRev !== null ?{ 'x-strata-base-rev' :String ( baseRev ) } :{}) } }); 37const data = await res . json () as { rev :number ; conflict ?:boolean }; 38return { rev :Number ( data . rev ) || 0 , conflict :data . conflict === true }; 39}, 40async remove ( id ) { await call ( 'DELETE' , `/api/chats/ ${ encodeURIComponent ( id )} ` ); }, 41async importMany ( sessions ) { 42const res = await call ( 'POST' , '/api/chats/import' , { body :JSON . stringify ({ sessions}), headers :{ 'content-type' :'application/json' } }); 43return 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. */ 50sessions :Session []; 51/** [id, rev] of every chat read from the host. */ 52revs :Map < string , number >; 53/** The host could not be asked: `sessions` is what the page had, nothing was moved. */ 54offline :boolean ; 55/** Chats moved from the browser's storage to the host this time. */ 56moved :number ; 57/** Chats the host refused during the move (disk full / permission) or could not be read; they stay in the browser. */ 58failed :{ id :string ; error :string ; code ?:string }[]; 59/** Chats that came back from the last-moment copy because the host's version was older. */ 60recovered :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 }>> { 69const out = new Map < string , { rev :number ; session :Session }>(); 70let next = 0 ; 71const worker = async () => { 72for (;;) { 73const entry = entries [ next ++ ]; 74if ( ! entry ) return ; 75const got = await transport . get ( entry . id ); 76if ( got ) out . set ( entry . id , got ); 77} 78}; 79await Promise . all ( Array . from ({ length :Math . min ( parallel , entries . length ) }, worker )); 80return 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 :{ 89transport :ChatTransport ; 90browser :StorageLike ; 91/** The chats in memory now (the browser's copy at start, or what this window already holds). */ 92current :Session []; 93/** A chat that must not be replaced from the host (a turn is running in it). */ 94isLive ?:( id :string ) => boolean ; 95/** Whether a chat in memory has changes the host does not have yet. */ 96isDirty ?:( session :Session ) => boolean ; 97}) :Promise < HydrateResult > { 98const { transport, browser} = opts ; 99const isLive = opts . isLive ?? (() => false ); 100const isDirty = opts . isDirty ?? (() => false ); 101let moved = 0 ; 102const failed :HydrateResult [ 'failed' ] = []; 103try { 104let flagged = false ; 105try { flagged = browser . getItem ( HOST_FLAG_KEY ) === '1' ; } catch { flagged = false ; } 106let list = await transport . list (); 107if ( ! flagged ) { 108const old = readBrowserSessions ( browser ). sessions ; 109if ( old . length ) { 110const result = await transport . importMany ( old ); 111moved = result . imported . length ; 112failed . push ( ...result . failed ); 113list = await transport . list (); 114} 115// Set only when nothing was refused: a disk-full move is tried again at the next start. 116if ( ! failed . length ) { try { browser . setItem ( HOST_FLAG_KEY , '1' ); } catch { /* the flag is a courtesy; the host skips what it has */ } } 117} 118const fromHost = await readAll ( transport , list . chats ); 119const revs = new Map ([ ...fromHost ]. map (([ id , v ]) => [ id , v . rev ])); 120const mine = new Map ( opts . current . map ( s => [ s . id , s ])); 121const merged :Session [] = []; 122for ( const entry of list . chats ) { 123const remote = fromHost . get ( entry . id ); 124const local = mine . get ( entry . id ); 125if ( ! remote ) { if ( local ) merged . push ( local ); continue ; } 126merged . push ( local && ( isLive ( entry . id ) || isDirty ( local ) || newer ( local . updatedAt , remote . session . updatedAt )) ?local :remote . session ); 127mine . delete ( entry . id ); 128} 129// Chats only this page has (made while the host was being read): kept, and saved when the writer starts. 130const hostIds = new Set ( list . chats . map ( c => c . id )); 131const onlyHere = opts . current . filter ( s => ! hostIds . has ( s . id )); 132const sessions = [ ...onlyHere , ...merged ]; 133const recovered = takeLastMomentCopy ( browser , sessions , revs ); 134return { sessions :recovered . sessions , revs, offline :false , moved, failed, recovered :recovered . ids }; 135} catch ( e ) { 136if ( isTransportError ( e )) return { sessions :opts . current , revs :new Map (), offline :true , moved, failed, recovered :[] }; 137throw 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 { 145try { 146if ( ! sessions . length ) { storage . removeItem ( PENDING_KEY ); return true ; } 147storage . setItem ( PENDING_KEY , JSON . stringify ( sessions )); 148return 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 [] } { 154let kept :Session [] = []; 155try { const raw = storage . getItem ( PENDING_KEY ); if ( raw ) { const parsed = JSON . parse ( raw ) as unknown ; if ( Array . isArray ( parsed )) kept = parsed . filter (( s ) :s isSession => !! s && typeof ( s as Session ). id === 'string' ); } } catch { kept = []; } 156if ( ! kept . length ) return { sessions, ids :[] }; 157const byId = new Map ( sessions . map ( s => [ s . id , s ])); 158const ids :string [] = []; 159for ( const copy of kept ) { 160const have = byId . get ( copy . id ); 161if ( ! have || newer ( copy . updatedAt , have . updatedAt )) { byId . set ( copy . id , copy ); ids . push ( copy . id ); } 162} 163try { storage . removeItem ( PENDING_KEY ); } catch { /* removed at the next start */ } 164if ( ! ids . length ) return { sessions, ids}; 165const order = sessions . map ( s => s . id ); 166const result = order . map ( id => byId . get ( id ) ! ). concat ([ ...byId . keys ()]. filter ( id => ! order . includes ( id )). map ( id => byId . get ( id ) ! )); 167void revs ; 168return { sessions :result , ids}; 169}