okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
1/** Chats as files in the data folder: big chats, restart, a full disk, a refused write, a crash in the middle of a write, two windows. */ 2import test from 'node:test' ; 3import assert from 'node:assert/strict' ; 4import { mkdtempSync , rmSync , readdirSync , readFileSync , writeFileSync , statSync , existsSync } from 'node:fs' ; 5import { tmpdir } from 'node:os' ; 6import { join } from 'node:path' ; 7import { createChatStore , realIo , validChatId , storeFailure } from '../server/chat-store.mjs' ; 8 9const scratch = () => mkdtempSync ( join ( tmpdir (), 'strata-chats-' )); 10const chat = ( id , n , len , extra = {}) => ({ 11 id, title :`Chat ${ id } ` , createdAt :`2026-11-0 ${( id . charCodeAt ( 0 ) % 8 ) + 1 } T10:00:00.000Z` , updatedAt :`2026-11-04T10:00:0 ${ n % 10 } .000Z` , workspace :'C:/w' , tokensIn :0 , tokensOut :0 , 12messages :Array . from ({ length :n }, ( _ , i ) => ({ id :` ${ id } -m ${ i } ` , role :i % 2 ?'assistant' :'user' , content :` ${ id } : ${ i } :` + String . fromCharCode ( 97 + ( i % 26 )). repeat ( len ) })), 13 ...extra , 14}); 15const text = ( session ) => JSON . stringify ( session ); 16const readChat = async ( store , id ) => JSON . parse ( await store . read ( id )); 17const files = ( dir ) => readdirSync ( join ( dir , 'chats' )). sort (); 18 19test ( 'ids: only plain names, nothing that climbs out of the folder or names a device or a reserved file' , () => { 20for ( const ok of [ 's_ab12cd34' , 'chat-1' , 'legacy_0' , 'a.b' ]) assert . ok ( validChatId ( ok ), ok ); 21for ( const bad of [ '' , '..' , '../x' , 'a/b' , 'a\\b' , '.hidden' , 'con' , 'NUL' , 'index' , 'import' , 'conflicts' , 'x' . repeat ( 200 ), null , 5 ]) assert . ok ( ! validChatId ( bad ), String ( bad )); 22}); 23 24test ( 'more than 10 MB of chats: every chat is saved whole, listed, and read back byte for byte after a restart (twice)' , async () => { 25const dir = scratch (); 26try { 27const chats = [ 'a' , 'b' , 'c' , 'd' ]. map (( id ) => chat ( id , 12 , 140_000 )); // 4 x 1.7 MB ... plus one very large one 28chats . push ({ ...chat ( 'e' , 4 , 10 ), messages :[{ id :'e-0' , role :'assistant' , content :'q' . repeat ( 4_000_000 ), tools :[{ name :'read' , result :'y' . repeat ( 3_000_000 ) }] }] }); 29const total = chats . reduce (( n , c ) => n + text ( c ). length , 0 ); 30assert . ok ( total > 10_000_000 , `fixture is ${ total } characters` ); 31let store = createChatStore ({ dir}); 32for ( const c of chats ) await store . save ( c . id , text ( c )); 33for ( let restart = 1 ; restart <= 2 ; restart ++ ) { 34store = createChatStore ({ dir}); // a new host process 35assert . deepEqual ( store . list (). chats . map (( c ) => c . id ). sort (), [ 'a' , 'b' , 'c' , 'd' , 'e' ]); 36for ( const c of chats ) { 37const back = await readChat ( store , c . id ); 38assert . equal ( JSON . stringify ( back . session ), text ( c ), `chat ${ c . id } after restart ${ restart } ` ); 39await store . save ( c . id , JSON . stringify ( back . session )); // saved again unchanged 40} 41} 42assert . equal (( await readChat ( store , 'a' )). rev , 3 , 'rev counts the saves' ); 43} finally { rmSync ( dir , { recursive :true , force :true }); } 44}); 45 46test ( 'the files: one per chat, a version field, an index, no stray temporary files' , async () => { 47const dir = scratch (); 48try { 49const store = createChatStore ({ dir}); 50await store . save ( 's_one' , text ( chat ( 's_one' , 2 , 10 ))); 51await store . save ( 's_two' , text ( chat ( 's_two' , 2 , 10 ))); 52assert . deepEqual ( files ( dir ), [ 'index.json' , 's_one.json' , 's_two.json' ]); 53const file = JSON . parse ( readFileSync ( join ( dir , 'chats' , 's_one.json' ), 'utf8' )); 54assert . deepEqual ([ file . v , file . rev , file . session . id ], [ 1 , 1 , 's_one' ]); 55const index = JSON . parse ( readFileSync ( join ( dir , 'chats' , 'index.json' ), 'utf8' )); 56assert . equal ( index . v , 1 ); assert . deepEqual ( index . chats . map (( c ) => c . id ). sort (), [ 's_one' , 's_two' ]); 57if ( process . platform !== 'win32' ) { 58assert . equal ( statSync ( join ( dir , 'chats' )). mode & 0o777 , 0o700 , 'the folder is owner-only' ); 59assert . equal ( statSync ( join ( dir , 'chats' , 's_one.json' )). mode & 0o777 , 0o600 , 'the chat file is owner-only' ); 60assert . equal ( statSync ( join ( dir , 'chats' , 'index.json' )). mode & 0o777 , 0o600 ); 61} 62} finally { rmSync ( dir , { recursive :true , force :true }); } 63}); 64 65test ( 'a crash in the middle of a write loses nothing older: the chat keeps its last whole version, the half file is removed at the next start' , async () => { 66const dir = scratch (); 67try { 68let store = createChatStore ({ dir}); 69const first = chat ( 's_x' , 6 , 5_000 ); 70await store . save ( 's_x' , text ( first )); 71const bigger = chat ( 's_x' , 12 , 5_000 ); 72// The process dies after half of the new text reached the temporary file: the write throws and nothing after it (cleanup) runs. 73const crashing = createChatStore ({ dir, io :{ ...realIo , 74async writeFile ( path , data ) { await realIo . writeFile ( path , data . slice ( 0 , Math . floor ( data . length / 2 ))); throw Object . assign ( new Error ( 'killed' ), { code :'EIO' }); }, 75async unlink () { throw new Error ( 'process is gone' ); } } }); 76await assert . rejects ( crashing . save ( 's_x' , text ( bigger ))); 77assert . ok ( files ( dir ). some (( n ) => / \.tmp- / . test ( n )), 'the crash left its temporary file' ); 78store = createChatStore ({ dir}); // restart 79assert . ok ( ! files ( dir ). some (( n ) => / \.tmp- / . test ( n )), 'the half-written file is removed at start' ); 80const back = await readChat ( store , 's_x' ); 81assert . equal ( back . rev , 1 ); 82assert . equal ( JSON . stringify ( back . session ), text ( first ), 'the older version is whole' ); 83} finally { rmSync ( dir , { recursive :true , force :true }); } 84}); 85 86test ( 'a full disk: the save is refused with a disk-full error, the older version stays, and the next save works when there is room' , async () => { 87const dir = scratch (); 88try { 89let full = false ; 90const store = createChatStore ({ dir, io :{ ...realIo , async writeFile ( path , data ) { if ( full ) throw Object . assign ( new Error ( 'no space left on device' ), { code :'ENOSPC' }); return realIo . writeFile ( path , data ); } } }); 91const v1 = chat ( 's_d' , 3 , 100 ); 92await store . save ( 's_d' , text ( v1 )); 93full = true ; 94await assert . rejects ( store . save ( 's_d' , text ( chat ( 's_d' , 9 , 100 ))), ( e ) => e . code === 'disk-full' && e . status === 507 ); 95assert . equal ( JSON . stringify (( await readChat ( store , 's_d' )). session ), text ( v1 )); 96assert . ok ( ! files ( dir ). some (( n ) => / \.tmp- / . test ( n )), 'no half file stays' ); 97full = false ; 98const v3 = chat ( 's_d' , 9 , 100 ); 99assert . equal (( await store . save ( 's_d' , text ( v3 ))). rev , 2 , 'the failed save did not use a revision' ); 100assert . equal ( JSON . stringify (( await readChat ( store , 's_d' )). session ), text ( v3 )); 101} finally { rmSync ( dir , { recursive :true , force :true }); } 102}); 103 104test ( 'a refused write (permission) is reported as such and changes nothing' , async () => { 105const dir = scratch (); 106try { 107const store = createChatStore ({ dir, io :{ ...realIo , async writeFile () { throw Object . assign ( new Error ( 'access denied' ), { code :'EACCES' }); } } }); 108await assert . rejects ( store . save ( 's_p' , text ( chat ( 's_p' , 1 , 1 ))), ( e ) => e . code === 'permission' && e . status === 403 ); 109assert . equal ( store . list (). chats . length , 0 ); 110assert . equal ( storeFailure ( Object . assign ( new Error ( 'x' ), { code :'EPERM' })). code , 'permission' ); 111assert . equal ( storeFailure ( Object . assign ( new Error ( 'x' ), { code :'ENOSPC' })). code , 'disk-full' ); 112} finally { rmSync ( dir , { recursive :true , force :true }); } 113}); 114 115test ( 'two windows: each saves its own chats and neither removes the other\'s; the same chat saved from an older copy keeps the displaced version' , async () => { 116const dir = scratch (); 117try { 118const store = createChatStore ({ dir}); 119// window A and window B, same host 120const a1 = await store . save ( 's_a' , text ( chat ( 's_a' , 2 , 10 )), { baseRev :null }); 121const b1 = await store . save ( 's_b' , text ( chat ( 's_b' , 2 , 10 )), { baseRev :null }); 122assert . deepEqual ( store . list (). chats . map (( c ) => c . id ). sort (), [ 's_a' , 's_b' ]); 123// both windows loaded s_a at rev 1; A saves a longer chat, then B saves from its older copy 124const fromA = chat ( 's_a' , 6 , 10 ), fromB = chat ( 's_a' , 4 , 10 , { title :'edited in B' }); 125const savedA = await store . save ( 's_a' , text ( fromA ), { baseRev :a1 . rev }); 126assert . equal ( savedA . conflict , false ); 127const savedB = await store . save ( 's_a' , text ( fromB ), { baseRev :a1 . rev }); // B still thinks rev 1 128assert . equal ( savedB . conflict , true ); 129assert . equal ( JSON . stringify (( await readChat ( store , 's_a' )). session ), text ( fromB ), 'the later save is the chat' ); 130const kept = readdirSync ( join ( dir , 'chats' , 'conflicts' )); 131assert . equal ( kept . length , 1 ); 132assert . equal ( JSON . parse ( readFileSync ( join ( dir , 'chats' , 'conflicts' , kept [ 0 ]), 'utf8' )). session . messages . length , 6 , 'window A\'s version is kept' ); 133assert . ok ( b1 . rev === 1 && ( await readChat ( store , 's_b' )). rev === 1 , 'the other chat is untouched' ); 134} finally { rmSync ( dir , { recursive :true , force :true }); } 135}); 136 137test ( 'saves of one host never overlap, in any order they arrive' , async () => { 138const dir = scratch (); 139try { 140const store = createChatStore ({ dir}); 141const done = await Promise . all ( Array . from ({ length :30 }, ( _ , i ) => store . save ( `s_ ${ i % 3 } ` , text ( chat ( `s_ ${ i % 3 } ` , 1 + ( i % 7 ), 50 ))))); 142assert . deepEqual ( done . map (( d ) => d . rev ). sort (( a , b ) => a - b ), Array . from ({ length :30 }, ( _ , i ) => Math . floor ( i / 3 ) + 1 ). sort (( a , b ) => a - b )); 143assert . equal ( store . list (). chats . length , 3 ); 144for ( const c of store . list (). chats ) JSON . parse ( await store . read ( c . id )); // every file is whole JSON 145} finally { rmSync ( dir , { recursive :true , force :true }); } 146}); 147 148test ( 'the index is rebuilt from the files when it is lost, damaged or behind; an unreadable chat file is reported and left alone' , async () => { 149const dir = scratch (); 150try { 151const store = createChatStore ({ dir}); 152await store . save ( 's_1' , text ( chat ( 's_1' , 2 , 10 ))); 153await store . save ( 's_2' , text ( chat ( 's_2' , 2 , 10 ))); 154writeFileSync ( join ( dir , 'chats' , 'index.json' ), '{"v":1,"chats":[' ); // damaged 155writeFileSync ( join ( dir , 'chats' , 's_bad.json' ), '{"v":1,"rev":1,"session":{"id":"s_bad","mess' ); 156const again = createChatStore ({ dir}); 157assert . deepEqual ( again . list (). chats . map (( c ) => c . id ). sort (), [ 's_1' , 's_2' ]); 158assert . deepEqual ( again . list (). damaged , [ 's_bad' ]); 159assert . equal ( readFileSync ( join ( dir , 'chats' , 's_bad.json' ), 'utf8' ). startsWith ( '{"v":1' ), true , 'left as it is' ); 160rmSync ( join ( dir , 'chats' , 'index.json' )); // lost 161assert . equal ( createChatStore ({ dir}). list (). chats . length , 2 ); 162} finally { rmSync ( dir , { recursive :true , force :true }); } 163}); 164 165test ( 'a chat is refused when it does not match its id or is not JSON; delete removes the file and tolerates a chat that is gone' , async () => { 166const dir = scratch (); 167try { 168const store = createChatStore ({ dir}); 169await assert . rejects ( store . save ( 's_a' , text ( chat ( 's_other' , 1 , 1 ))), ( e ) => e . status === 400 ); 170await assert . rejects ( store . save ( 's_a' , '{nope' ), ( e ) => e . status === 400 ); 171await assert . rejects ( store . save ( '../evil' , text ( chat ( '../evil' , 1 , 1 ))), ( e ) => e . status === 400 ); 172await store . save ( 's_a' , text ( chat ( 's_a' , 1 , 1 ))); 173assert . deepEqual ( await store . remove ( 's_a' ), { id :'s_a' , removed :true }); 174assert . deepEqual ( await store . remove ( 's_a' ), { id :'s_a' , removed :false }); 175assert . ok ( ! existsSync ( join ( dir , 'chats' , 's_a.json' ))); 176assert . equal ( createChatStore ({ dir}). list (). chats . length , 0 ); 177} finally { rmSync ( dir , { recursive :true , force :true }); } 178}); 179 180test ( 'import: only chats the host does not have are taken, the ones it has are left alone, a bad one is reported' , async () => { 181const dir = scratch (); 182try { 183const store = createChatStore ({ dir}); 184await store . save ( 's_have' , text ( chat ( 's_have' , 2 , 10 , { title :'on the host' }))); 185const result = await store . importMany ([ chat ( 's_have' , 5 , 10 , { title :'in the browser' }), chat ( 's_new' , 3 , 10 ), { id :'../x' }, { nope :true }]); 186assert . deepEqual ( result . imported , [ 's_new' ]); 187assert . deepEqual ( result . skipped , [ 's_have' ]); 188assert . equal ( result . failed . length , 2 ); 189assert . equal (( await readChat ( store , 's_have' )). session . title , 'on the host' ); 190} finally { rmSync ( dir , { recursive :true , force :true }); } 191});