robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
69e61d52e2
master
1// TODO: Add a fallback when SharedArrayBuffer is unavailable. 2// Transport: owns the worker and SharedArrayBuffer 3class WorkerTransport { 4constructor ( workerPath , { cols= 80 , rows= 24 , cap= 1 << 16 } = {}) { 5this . CAP = cap ; 6this . sab = new SharedArrayBuffer ( 12 + this . CAP ); 7this . state = new Int32Array ( this . sab , 0 , 3 ); // [head, tail, closed] 8this . ringData = new Uint8Array ( this . sab , 12 , this . CAP ); // offset 12 9 10this . _bytesHandlers = []; 11this . _statusHandlers = []; 12this . _readyHandlers = []; 13this . _exitHandlers = []; 14 15this . worker = new Worker ( workerPath ); 16this . worker . onmessage = ( ev ) => { 17console . log ( "[main] worker message" , ev . data . type , ev . data ); 18this . _onWorkerMessage ( ev . data ); 19}; 20this . worker . onerror = ( e ) => this . _emitStatus ( "worker error: " + e . message ); 21this . worker . postMessage ({ type :"init" , sab :this . sab , cols, rows}); 22} 23 24shutdown () { 25Atomics . store ( this . state , 2 , 1 ); 26Atomics . notify ( this . state , 0 ); 27this . worker . postMessage ({ type :"shutdown" }); 28} 29 30_onWorkerMessage ( msg ) { 31console . log ( "[main] _onWorkerMessage got" , msg . type ); 32 33if ( msg . type === "stdout" ) { 34console . log ( `[main] stdout bytes:` , msg . bytes ); 35this . _bytesHandlers . forEach (( h ) => h ( msg . bytes )); 36} else if ( msg . type === "stderr" ) { 37const text = new TextDecoder (). decode ( new Uint8Array ( msg . bytes )); 38this . _emitStatus ( "[stderr] " + text ); 39} else if ( msg . type === "status" ) { 40this . _emitStatus ( msg . text ); 41} else if ( msg . type === "shared-info" ) { 42this . sharedState = new Int32Array ( 43msg . memory , 44msg . statePtr , 451 + 256 + 256 , 46); 47console . log ( "[main] shared-info received, direct futex wake enabled" ); 48} else if ( msg . type === "ready" ) { 49console . log ( "[main] worker signaled ready, RPC channel should be live" ); 50this . _readyHandlers . forEach (( h ) => h ()); 51} 52else if ( msg . type === "exited" ) { 53console . log ( "worker signaled nvim exited, code=" , msg . code ); 54this . _exitHandlers . forEach (( h ) => h ( msg . code )); 55} 56} 57 58_emitStatus ( text ) { 59console . log ( "[main] status:" , text ); 60this . _statusHandlers . forEach (( h ) => h ( text )); 61} 62 63send ( bytes ) { 64console . log ( "[main] Send: writing" , bytes . length , "bytes" ); 65const hexStr = Array . from ( bytes ) 66. map (( b ) => b . toString ( 16 ). padStart ( 2 , "0" )) 67. join ( " " ); 68console . log ( `[main] Send: ${ bytes . length } bytes: ${ hexStr } ` ); 69 70let lastHead = 0 ; 71for ( let i = 0 ; i < bytes . length ; i ++ ) { 72const b = bytes [ i ]; 73const head = Atomics . load ( this . state , 0 ); 74const tail = Atomics . load ( this . state , 1 ); 75const next = ( head + 1 ) % this . CAP ; 76if ( next === tail ) { 77console . error ( "[main] Send: ring buffer full" ); 78return false ; 79} 80this . ringData [ head ] = b ; 81Atomics . store ( this . state , 0 , next ); 82lastHead = next ; 83} 84 85if ( this . sharedState ) { 86// Write straight into the C-side shared struct, then wake the futex. 87// This only works if the worker is already inside 88// emscripten_futex_wait() at the moment call notify() if it is 89// not waiting yet, the notify does nothing. Atomics.notify() does not 90// queue up a wake for some future wait() call as it only wakes threads 91// that are waiting right now. 92const STDIN_FD = 9 ; 93const tail = Atomics . load ( this . state , 1 ); 94const n = ( lastHead - tail + this . CAP ) % this . CAP ; 95Atomics . store ( this . sharedState , 1 + STDIN_FD , n ); // readable[STDIN_FD] = n 96Atomics . add ( this . sharedState , 0 , 1 ); // generation++ 97Atomics . notify ( this . sharedState , 0 , 1 ); // wake the futex_wait, if any 98console . log ( "[main] Send Done, direct notified futex, n=" , n ); 99} 100// There's a real startup race here: if this send() happens before the 101// worker's event loop has reached its first Atomics.wait() (e.g. 102// auto-attach fires the instant ready arrives), the direct notify 103// above lands on nobody and is silently wasted. And if the C side poll 104// loop only reacts to notify events instead of rechecking the shared 105// value on every scan that missed wake is gone for good and the 106// request just sits in the ring buffer forever. 107// 108// But until the worker actually starts blocking, it is still free to 109// process its own message queue so this postMessage gets handled 110// right away, routing through the worker's own markReadable() -> 111// uv_browser_set_readable ccall path. That makes send() correct 112// whether or not nvim has reached its poll loop yet instead of 113// depending on lucky notify timing. 114this . worker . postMessage ({ type :"readable-hint" }); 115console . log ( 116"[main] SEND DONE, also sent readable-hint as belt-and-suspenders" , 117); 118 119return true ; 120} 121 122onBytes ( cb ) { 123this . _bytesHandlers . push ( cb ); 124} 125onStatus ( cb ) { 126this . _statusHandlers . push ( cb ); 127} 128onReady ( cb ) { 129this . _readyHandlers . push ( cb ); 130} 131onExit ( cb ) { 132this . _exitHandlers . push ( cb ); 133} 134persist () { 135this . worker . postMessage ({ type :"persist" }); 136} 137} 138 139class RpcClient { 140constructor ( transport ) { 141this . transport = transport ; 142this . nextMsgId = 1 ; 143this . pending = new Map (); 144this . notificationHandlers = new Map (); 145 146this . _buffer = new Uint8Array ( 0 ); 147 148transport . onBytes (( bytes ) => this . _handleBytes ( bytes )); 149} 150 151_handleBytes ( newBytes ) { 152console . log ( 153"[RpcClient] _handleBytes" , 154newBytes . length , 155newBytes . slice ( 0 , 32 ), 156); 157 158const combined = new Uint8Array ( this . _buffer . length + newBytes . length ); 159combined . set ( this . _buffer , 0 ); 160combined . set ( newBytes , this . _buffer . length ); 161this . _buffer = combined ; 162 163const { messages, consumed} = MsgpackCodec . decodeMultiple ( this . _buffer ); 164 165for ( const msg of messages ) { 166console . log ( "[RpcClient] raw decoded:" , JSON . stringify ( msg )); 167this . _dispatch ( msg ); 168} 169 170this . _buffer = this . _buffer . slice ( consumed ); 171} 172 173_dispatch ( rawMsg ) { 174console . log ( "[RpcClient] dispatching:" , rawMsg ); 175 176let msg ; 177try { 178msg = Protocol . parseMessage ( rawMsg ); 179} catch ( e ) { 180console . error ( "[RpcClient] parse failed" , rawMsg , e ); 181return ; 182} 183 184console . log ( "[RpcClient] parsed:" , msg ); 185 186if ( msg . kind === "response" ) { 187const p = this . pending . get ( msg . msgid ); 188if ( ! p ) { 189console . warn ( "[RpcClient] unknown msgid" , msg . msgid , "pending:" , [ 190 ...this . pending . keys (), 191]); 192return ; 193} 194this . pending . delete ( msg . msgid ); 195clearTimeout ( p . timeoutId ); 196console . log ( "[RpcClient] resolved msgid" , msg . msgid ); 197if ( msg . error ) { 198p . reject ( new Error ( msg . error )); 199} else { 200p . resolve ( msg . result ); 201} 202} else if ( msg . kind === "notification" ) { 203console . log ( "[RpcClient] notification:" , msg . method ); 204const handlers = this . notificationHandlers . get ( msg . method ) || []; 205handlers . forEach (( h ) => h ( msg . params )); 206} else if ( msg . kind === "request" ) { 207console . warn ( "[RpcClient] unhandled request" , msg ); 208} 209} 210 211request ( method , params = []) { 212const msgid = this . nextMsgId ++ ; 213const bytes = Protocol . encodeRequest ( msgid , method , params ); 214console . log ( 215`[RpcClient] sending request ${ msgid } ( ${ method } ), ${ bytes . length } bytes` , 216); 217 218return new Promise (( resolve , reject ) => { 219this . pending . set ( msgid , { 220 resolve, 221 reject, 222 method, 223timestamp :Date . now (), 224}); 225 226const timeoutId = setTimeout (() => { 227if ( this . pending . has ( msgid )) { 228this . pending . delete ( msgid ); 229reject ( new Error ( `Request ${ msgid } ( ${ method } ) timed out after 30s` )); 230} 231}, 30000 ); 232 233this . pending . get ( msgid ). timeoutId = timeoutId ; 234 235this . transport . send ( bytes ); 236}); 237} 238 239notify ( method , params = []) { 240const bytes = Protocol . encodeNotification ( method , params ); 241console . log ( 242`[RpcClient] sending notification ${ method } , ${ bytes . length } bytes` , 243); 244this . transport . send ( bytes ); 245} 246 247on ( method , handler ) { 248if ( ! this . notificationHandlers . has ( method )) { 249this . notificationHandlers . set ( method , []); 250} 251this . notificationHandlers . get ( method ). push ( handler ); 252} 253}