robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyestest: improve Nvim EOF handling (for Windows CI) #4084140ab941f79

master
7.4 KiB279 linesraw
1---
2--- Nvim msgpack-RPC protocol session. Manages requests/notifications/responses.
3---
4
5local uv = vim.uv
6local RpcStream = require('test.client.rpc_stream')
7
8--- Nvim msgpack-RPC protocol session. Manages requests/notifications/responses.
9---
10--- @class test.Session
11--- @field private _pending_messages string[] Requests/notifications received from the remote end.
12--- @field private _rpc_stream test.RpcStream
13--- @field private _prepare uv.uv_prepare_t
14--- @field private _timer uv.uv_timer_t
15--- @field private _is_running boolean true during `Session:run()` scope.
16--- @field data table Arbitrary user data.
17local Session = {
18  eof_err_msg = 'Nvim EOF (crash?)',
19}
20Session.__index = Session
21if package.loaded['jit'] then
22  -- luajit pcall is already coroutine safe
23  Session.safe_pcall = pcall
24else
25  Session.safe_pcall = require 'coxpcall'.pcall
26end
27
28local function resume(co, ...)
29  local status, result = coroutine.resume(co, ...)
30
31  if coroutine.status(co) == 'dead' then
32    if not status then
33      error(result)
34    end
35    return
36  end
37
38  assert(coroutine.status(co) == 'suspended')
39  result(co)
40end
41
42local function coroutine_exec(func, ...)
43  local args = { ... }
44  local on_complete --- @type function?
45
46  if #args > 0 and type(args[#args]) == 'function' then
47    -- completion callback
48    on_complete = table.remove(args)
49  end
50
51  resume(coroutine.create(function()
52    local status, result, flag = Session.safe_pcall(func, unpack(args))
53    if on_complete then
54      coroutine.yield(function()
55        -- run the completion callback on the main thread
56        on_complete(status, result, flag)
57      end)
58    end
59  end))
60end
61
62--- Creates a new msgpack-RPC session.
63function Session.new(stream)
64  return setmetatable({
65    _rpc_stream = RpcStream.new(stream),
66    _pending_messages = {},
67    _prepare = uv.new_prepare(),
68    _timer = uv.new_timer(),
69    _is_running = false,
70  }, Session)
71end
72
73--- @param timeout integer?
74--- @return string?
75function Session:next_message(timeout)
76  local function on_request(method, args, response)
77    table.insert(self._pending_messages, { 'request', method, args, response })
78    uv.stop()
79  end
80
81  local function on_notification(method, args)
82    table.insert(self._pending_messages, { 'notification', method, args })
83    uv.stop()
84  end
85
86  if self._is_running then
87    error('Event loop already running')
88  end
89
90  if #self._pending_messages > 0 then
91    return table.remove(self._pending_messages, 1)
92  end
93
94  -- if closed, only return pending messages
95  if self.closed then
96    return nil
97  end
98
99  self:_run(on_request, on_notification, timeout)
100  return table.remove(self._pending_messages, 1)
101end
102
103--- Sends a notification to the RPC endpoint.
104function Session:notify(method, ...)
105  self._rpc_stream:write(method, { ... })
106end
107
108--- Sends a request to the RPC endpoint.
109---
110--- @param method string
111--- @param ... any
112--- @return boolean, table
113function Session:request(method, ...)
114  local args = { ... }
115  local err, result
116  if self._is_running then
117    err, result = self:_yielding_request(method, args)
118  else
119    err, result = self:_blocking_request(method, args)
120  end
121
122  if err then
123    return false, err
124  end
125
126  return true, result
127end
128
129--- Processes incoming RPC requests/notifications until exhausted.
130---
131--- TODO(justinmk): luaclient2 avoids this via uvutil.cb_wait() + uvutil.add_idle_call()?
132---
133--- @param request_cb function Handles requests from the sever to the local end.
134--- @param notification_cb function Handles notifications from the sever to the local end.
135--- @param setup_cb function
136--- @param timeout number
137function Session:run(request_cb, notification_cb, setup_cb, timeout)
138  --- Handles an incoming request.
139  local function on_request(method, args, response)
140    coroutine_exec(request_cb, method, args, function(status, result, flag)
141      if status then
142        response:send(result, flag)
143      else
144        response:send(result, true)
145      end
146    end)
147  end
148
149  --- Handles an incoming notification.
150  local function on_notification(method, args)
151    coroutine_exec(notification_cb, method, args)
152  end
153
154  self._is_running = true
155
156  if setup_cb then
157    coroutine_exec(setup_cb)
158  end
159
160  while #self._pending_messages > 0 do
161    local msg = table.remove(self._pending_messages, 1)
162    if msg[1] == 'request' then
163      on_request(msg[2], msg[3], msg[4])
164    else
165      on_notification(msg[2], msg[3])
166    end
167  end
168
169  self:_run(on_request, on_notification, timeout)
170  self._is_running = false
171end
172
173function Session:stop()
174  uv.stop()
175end
176
177function Session:close(signal, noblock)
178  if not self._timer:is_closing() then
179    self._timer:close()
180  end
181  if not self._prepare:is_closing() then
182    self._prepare:close()
183  end
184  self._rpc_stream:close(signal, noblock)
185  self.closed = true
186end
187
188--- Sends a request to the RPC endpoint, without blocking (schedules a coroutine).
189function Session:_yielding_request(method, args)
190  return coroutine.yield(function(co)
191    self._rpc_stream:write(method, args, function(err, result)
192      resume(co, err, result)
193    end)
194  end)
195end
196
197--- Sends a request to the RPC endpoint, and blocks (polls event loop) until a response is received.
198function Session:_blocking_request(method, args)
199  local err, result
200
201  -- Invoked when a request is received from the remote end.
202  local function on_request(method_, args_, response)
203    table.insert(self._pending_messages, { 'request', method_, args_, response })
204  end
205
206  -- Invoked when a notification is received from the remote end.
207  local function on_notification(method_, args_)
208    table.insert(self._pending_messages, { 'notification', method_, args_ })
209  end
210
211  self._rpc_stream:write(method, args, function(e, r)
212    err = e
213    result = r
214    uv.stop()
215  end)
216
217  -- Poll for incoming requests/notifications received from the remote end.
218  self:_run(on_request, on_notification)
219  return (err or self.eof_err), result
220end
221
222--- Polls for incoming requests/notifications received from the remote end.
223function Session:_run(request_cb, notification_cb, timeout)
224  if type(timeout) == 'number' then
225    self._prepare:start(function()
226      self._timer:start(timeout, 0, function()
227        uv.stop()
228      end)
229      self._prepare:stop()
230    end)
231  end
232  local got_eof = false
233  self._rpc_stream:read_start(request_cb, notification_cb, function()
234    uv.stop()
235    got_eof = true
236  end)
237  local ret, err, _ = uv.run()
238  if ret == nil then
239    error(err)
240  end
241  self._prepare:stop()
242  self._timer:stop()
243  self._rpc_stream:read_stop()
244  if got_eof then
245    self.eof_err = { 1, self:_eof_msg() }
246  end
247end
248
249--- Message shown on unexpected stdout EOF.
250--- @private
251--- @return string
252function Session:_eof_msg()
253  local msg = self.eof_err_msg
254  --- @diagnostic disable-next-line: access-invisible
255  local proc = self._rpc_stream._stream --[[@as test.ProcStream]]
256
257  -- ProcStream (spawned child) has stderr + exit-code; SocketStream (a socket peer) does not.
258  if proc.stderr ~= nil then
259    -- stdout EOF and process-exit are separate libuv events. Wait for up to 1s.
260    vim.wait(1000, function()
261      return proc.status ~= nil or proc.signal ~= nil
262    end)
263    if proc.status ~= nil then
264      msg = ('%s exit code: %d (0x%08X)'):format(msg, proc.status, proc.status % 2 ^ 32)
265    end
266    if proc.signal ~= nil and proc.signal ~= 0 then
267      msg = ('%s signal: %d'):format(msg, proc.signal)
268    end
269  end
270
271  local stderr = proc.stderr --[[@as string?]]
272  if '' ~= ((stderr or ''):match('^%s*(.*%S)') or '') then
273    msg = msg .. ' stderr:\n' .. stderr
274  end
275  return msg
276end
277
278--- Nvim msgpack-RPC session.
279return Session