robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
d2257402e3
master
1--- 2--- Reading/writing of msgpack over any of the stream types from `uv_stream.lua`. 3--- Does not implement the RPC protocol, see `session.lua` for that. 4--- 5 6local mpack =vim . mpack 7 8local Response ={} 9Response . __index =Response 10 11function Response . new ( rpc_stream , request_id ) 12return setmetatable ( { 13_rpc_stream =rpc_stream , 14_request_id =request_id , 15} , Response ) 16end 17 18function Response : send ( value , is_error ) 19local data =self . _rpc_stream . _session : reply ( self . _request_id ) 20if is_error then 21data =data .. self . _rpc_stream . _pack ( value ) 22data =data .. self . _rpc_stream . _pack ( mpack . NIL ) 23else 24data =data .. self . _rpc_stream . _pack ( mpack . NIL ) 25data =data .. self . _rpc_stream . _pack ( value ) 26end 27self . _rpc_stream . _stream : write ( data ) 28end 29 30--- Nvim msgpack RPC stream. 31--- 32--- @class test.RpcStream 33--- @field private _stream test.Stream 34--- @field private __pack table 35local RpcStream ={} 36RpcStream . __index =RpcStream 37 38function RpcStream . new ( stream ) 39return setmetatable ( { 40_stream =stream , 41_pack =mpack . Packer (), 42_session =mpack . Session ( { 43unpack =mpack . Unpacker ( { 44ext ={ 45-- Buffer 46[ 0 ] =function ( _c , s ) 47return mpack . decode ( s ) 48end , 49-- Window 50[ 1 ] =function ( _c , s ) 51return mpack . decode ( s ) 52end , 53-- Tabpage 54[ 2 ] =function ( _c , s ) 55return mpack . decode ( s ) 56end , 57} , 58} ), 59} ), 60} , RpcStream ) 61end 62 63function RpcStream : write ( method , args , response_cb ) 64local data 65if response_cb then 66assert ( type ( response_cb ) == 'function' ) 67data =self . _session : request ( response_cb ) 68else 69data =self . _session : notify () 70end 71 72data =data .. self . _pack ( method ) .. self . _pack ( args ) 73self . _stream : write ( data ) 74end 75 76function RpcStream : read_start ( on_request , on_notification , on_eof ) 77self . _stream : read_start ( function ( data ) 78if not data then 79return on_eof () 80end 81local type , id_or_cb , method_or_error , args_or_result 82local pos =1 83local len =# data 84while pos <= len do 85type , id_or_cb , method_or_error , args_or_result , pos =self . _session : receive ( data , pos ) 86if type == 'request' or type == 'notification' then 87if type == 'request' then 88on_request ( method_or_error , args_or_result , Response . new ( self , id_or_cb )) 89else 90on_notification ( method_or_error , args_or_result ) 91end 92elseif type == 'response' then 93if method_or_error == mpack . NIL then 94method_or_error =nil 95else 96args_or_result =nil 97end 98id_or_cb ( method_or_error , args_or_result ) 99end 100end 101end ) 102end 103 104function RpcStream : read_stop () 105self . _stream : read_stop () 106end 107 108function RpcStream : close ( signal , noblock ) 109self . _stream : close ( signal , noblock ) 110end 111 112return RpcStream