robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
15.3 KiB473 linesraw
1-- Test server -> client RPC scenarios. Note: unlike `rpcnotify`, to evaluate
2-- `rpcrequest` calls we need the client event loop to be running.
3local t = require('test.testutil')
4local n = require('test.functional.testnvim')()
5
6local describe, it, before_each, after_each, pending, finally =
7  t.describe, t.it, t.before_each, t.after_each, t.pending, t.finally
8local clear, eval = n.clear, n.eval
9local eq, neq, run, stop = t.eq, t.neq, n.run, n.stop
10local nvim_prog, command, fn = n.nvim_prog, n.command, n.fn
11local source, next_msg = n.source, n.next_msg
12local ok = t.ok
13local api = n.api
14local new_session, set_session = n.new_session, n.set_session
15local pcall_err = t.pcall_err
16local assert_alive = n.assert_alive
17
18describe('server -> client', function()
19  local cid
20
21  before_each(function()
22    clear()
23    cid = api.nvim_get_chan_info(0).id
24  end)
25
26  it('handles unexpected closed stream while preparing RPC response', function()
27    source([[
28      let g:_nvim_args = [v:progpath, '--embed', '--headless', '-n', '-u', 'NONE', '-i', 'NONE', ]
29      let ch1 = jobstart(g:_nvim_args, {'rpc': v:true})
30      let child1_ch = rpcrequest(ch1, "nvim_get_chan_info", 0).id
31      call rpcnotify(ch1, 'nvim_eval', 'rpcrequest('.child1_ch.', "nvim_get_api_info")')
32
33      let ch2 = jobstart(g:_nvim_args, {'rpc': v:true})
34      let child2_ch = rpcrequest(ch2, "nvim_get_chan_info", 0).id
35      call rpcnotify(ch2, 'nvim_eval', 'rpcrequest('.child2_ch.', "nvim_get_api_info")')
36
37      call jobstop(ch1)
38    ]])
39    assert_alive()
40  end)
41
42  describe('simple call', function()
43    it('works', function()
44      local function on_setup()
45        eq({ 4, 5, 6 }, eval('rpcrequest(' .. cid .. ', "scall", 1, 2, 3)'))
46        stop()
47      end
48
49      local function on_request(method, args)
50        eq('scall', method)
51        eq({ 1, 2, 3 }, args)
52        command('let g:result = [4, 5, 6]')
53        return eval('g:result')
54      end
55      run(on_request, nil, on_setup)
56    end)
57  end)
58
59  describe('empty string handling in arrays', function()
60    -- Because the msgpack encoding for an empty string was interpreted as an
61    -- error, msgpack arrays with an empty string looked like
62    -- [..., '', 0, ..., 0] after the conversion, regardless of the array
63    -- elements following the empty string.
64    it('works', function()
65      local function on_setup()
66        eq({ 1, 2, '', 3, 'asdf' }, eval('rpcrequest(' .. cid .. ', "nstring")'))
67        stop()
68      end
69
70      local function on_request()
71        -- No need to evaluate the args, we are only interested in
72        -- a response that contains an array with an empty string.
73        return { 1, 2, '', 3, 'asdf' }
74      end
75      run(on_request, nil, on_setup)
76    end)
77  end)
78
79  describe('recursive call', function()
80    it('works', function()
81      local function on_setup()
82        api.nvim_set_var('result1', 0)
83        api.nvim_set_var('result2', 0)
84        api.nvim_set_var('result3', 0)
85        api.nvim_set_var('result4', 0)
86        command('let g:result1 = rpcrequest(' .. cid .. ', "rcall", 2)')
87        eq(4, api.nvim_get_var('result1'))
88        eq(8, api.nvim_get_var('result2'))
89        eq(16, api.nvim_get_var('result3'))
90        eq(32, api.nvim_get_var('result4'))
91        stop()
92      end
93
94      local function on_request(method, args)
95        eq('rcall', method)
96        local _n = unpack(args) * 2
97        if _n <= 16 then
98          local cmd
99          if _n == 4 then
100            cmd = 'let g:result2 = rpcrequest(' .. cid .. ', "rcall", ' .. _n .. ')'
101          elseif _n == 8 then
102            cmd = 'let g:result3 = rpcrequest(' .. cid .. ', "rcall", ' .. _n .. ')'
103          elseif _n == 16 then
104            cmd = 'let g:result4 = rpcrequest(' .. cid .. ', "rcall", ' .. _n .. ')'
105          end
106          command(cmd)
107        end
108        return _n
109      end
110      run(on_request, nil, on_setup)
111    end)
112  end)
113
114  describe('requests and notifications interleaved', function()
115    it('does not delay notifications during pending request', function()
116      local received = false
117      local function on_setup()
118        eq('retval', fn.rpcrequest(cid, 'doit'))
119        stop()
120      end
121      local function on_request(method)
122        if method == 'doit' then
123          fn.rpcnotify(cid, 'headsup')
124          eq(true, received)
125          return 'retval'
126        end
127      end
128      local function on_notification(method)
129        if method == 'headsup' then
130          received = true
131        end
132      end
133      run(on_request, on_notification, on_setup)
134    end)
135
136    -- This tests the following scenario:
137    --
138    -- server->client [request     ] (1)
139    -- client->server [request     ] (2) triggered by (1)
140    -- server->client [notification] (3) triggered by (2)
141    -- server->client [response    ] (4) response to (2)
142    -- client->server [request     ] (4) triggered by (3)
143    -- server->client [request     ] (5) triggered by (4)
144    -- client->server [response    ] (6) response to (1)
145    --
146    -- If the above scenario ever happens, the client connection will be closed
147    -- because (6) is returned after request (5) is sent, and nvim
148    -- only deals with one server->client request at a time. (In other words,
149    -- the client cannot send a response to a request that is not at the top
150    -- of nvim's request stack).
151    pending('will close connection if not properly synchronized', function()
152      local function on_setup()
153        eq('notified!', eval('rpcrequest(' .. cid .. ', "notify")'))
154      end
155
156      local function on_request(method)
157        if method == 'notify' then
158          eq(1, eval('rpcnotify(' .. cid .. ', "notification")'))
159          return 'notified!'
160        elseif method == 'nested' then
161          -- do some busywork, so the first request will return
162          -- before this one
163          for _ = 1, 5 do
164            assert_alive()
165          end
166          eq(1, eval('rpcnotify(' .. cid .. ', "nested_done")'))
167          return 'done!'
168        end
169      end
170
171      local function on_notification(method)
172        if method == 'notification' then
173          eq('done!', eval('rpcrequest(' .. cid .. ', "nested")'))
174        elseif method == 'nested_done' then
175          ok(false, 'never sent', 'sent')
176        end
177      end
178
179      run(on_request, on_notification, on_setup)
180      -- ignore disconnect failure, otherwise detected by after_each
181      clear()
182    end)
183  end)
184
185  describe('recursive (child) nvim client', function()
186    before_each(function()
187      command(
188        "let vim = rpcstart('"
189          .. nvim_prog
190          .. "', ['-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--embed', '--headless'])"
191      )
192      neq(0, eval('vim'))
193    end)
194
195    after_each(function()
196      command('call rpcstop(vim)')
197    end)
198
199    it('can send/receive notifications and make requests', function()
200      command("call rpcnotify(vim, 'vim_set_current_line', 'SOME TEXT')")
201
202      -- Wait for the notification to complete.
203      command("call rpcrequest(vim, 'vim_eval', '0')")
204
205      eq('SOME TEXT', eval("rpcrequest(vim, 'vim_get_current_line')"))
206    end)
207
208    it('can communicate buffers, tabpages, and windows', function()
209      eq({ 1 }, eval("rpcrequest(vim, 'nvim_list_tabpages')"))
210      -- Window IDs start at 1000 (LOWEST_WIN_ID in window.h)
211      eq({ 1000 }, eval("rpcrequest(vim, 'nvim_list_wins')"))
212
213      local buf = eval("rpcrequest(vim, 'nvim_list_bufs')")[1]
214      eq(1, buf)
215
216      eval("rpcnotify(vim, 'buffer_set_line', " .. buf .. ", 0, 'SOME TEXT')")
217      command("call rpcrequest(vim, 'vim_eval', '0')") -- wait
218
219      eq('SOME TEXT', eval("rpcrequest(vim, 'buffer_get_line', " .. buf .. ', 0)'))
220
221      -- Call get_lines(buf, range [0,0], strict_indexing)
222      eq({ 'SOME TEXT' }, eval("rpcrequest(vim, 'buffer_get_lines', " .. buf .. ', 0, 1, 1)'))
223    end)
224
225    it('returns an error if the request failed', function()
226      eq(
227        "Vim:Invoking 'does-not-exist' on channel 3:\nInvalid method: does-not-exist",
228        pcall_err(eval, "rpcrequest(vim, 'does-not-exist')")
229      )
230    end)
231  end)
232
233  describe('jobstart()', function()
234    local jobid
235    before_each(function()
236      local channel = api.nvim_get_chan_info(0).id
237      api.nvim_set_var('channel', channel)
238      source([[
239        function! s:OnEvent(id, data, event)
240          call rpcnotify(g:channel, a:event, 0, a:data)
241        endfunction
242        let g:job_opts = {
243        \ 'on_stderr': function('s:OnEvent'),
244        \ 'on_exit': function('s:OnEvent'),
245        \ 'user': 0,
246        \ 'rpc': v:true
247        \ }
248      ]])
249      api.nvim_set_var('args', {
250        nvim_prog,
251        '-l',
252        'test/functional/api/rpc_fixture.lua',
253        package.path,
254        package.cpath,
255      })
256      jobid = eval('jobstart(g:args, g:job_opts)')
257      neq(0, jobid)
258    end)
259
260    after_each(function()
261      pcall(fn.jobstop, jobid)
262    end)
263
264    if t.skip(t.is_os('win')) then
265      return
266    end
267
268    it('rpc and text stderr can be combined', function()
269      local status, rv = pcall(fn.rpcrequest, jobid, 'poll')
270      if not status then
271        error(string.format('missing nvim Lua module? (%s)', rv))
272      end
273      eq('ok', rv)
274      fn.rpcnotify(jobid, 'ping')
275      eq({ 'notification', 'pong', {} }, next_msg())
276      eq('done!', fn.rpcrequest(jobid, 'write_stderr', 'fluff\n'))
277      eq({ 'notification', 'stderr', { 0, { 'fluff', '' } } }, next_msg())
278      pcall(fn.rpcrequest, jobid, 'exit')
279      eq({ 'notification', 'stderr', { 0, { '' } } }, next_msg())
280      eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
281    end)
282  end)
283
284  describe('connecting to another (peer) nvim', function()
285    local function connect_test(server, mode, address)
286      local serverpid = fn.getpid()
287      local client = n.new_session(true)
288      set_session(client)
289
290      local clientpid = fn.getpid()
291      neq(serverpid, clientpid)
292      local id = fn.sockconnect(mode, address, { rpc = true })
293      ok(id > 0)
294
295      fn.rpcrequest(id, 'nvim_set_current_line', 'hello')
296      local client_id = fn.rpcrequest(id, 'nvim_get_chan_info', 0).id
297
298      set_session(server)
299      eq(serverpid, fn.getpid())
300      eq('hello', api.nvim_get_current_line())
301
302      -- Method calls work both ways.
303      fn.rpcrequest(client_id, 'nvim_set_current_line', 'howdy!')
304      eq(id, fn.rpcrequest(client_id, 'nvim_get_chan_info', 0).id)
305
306      set_session(client)
307      eq(clientpid, fn.getpid())
308      eq('howdy!', api.nvim_get_current_line())
309
310      -- Sending notification and then closing channel immediately still works.
311      -- Use a fast API here, as a deferred API call may be aborted by EOF. #13537
312      n.exec_lua(function()
313        vim.rpcnotify(id, 'nvim_input', 'ccbye!<Esc>')
314        vim.fn.chanclose(id)
315      end)
316
317      set_session(server)
318      eq(serverpid, fn.getpid())
319      -- Wait for the notification to be processed.
320      t.retry(nil, 1000, function()
321        eq('bye!', api.nvim_get_current_line())
322      end)
323
324      server:close()
325      client:close()
326    end
327
328    it('via named pipe', function()
329      local server = n.new_session(false)
330      set_session(server)
331      local address = fn.serverlist()[1]
332      local first = string.sub(address, 1, 1)
333      ok(first == '/')
334      connect_test(server, 'pipe', address)
335    end)
336
337    it('via named pipe containing backslashes #39382', function()
338      t.skip(not t.is_os('win'), 'N/A for non-Windows')
339      local address = [[\\.\pipe\Xtest]]
340      local server = new_session(false, {
341        args_rm = { '--listen' },
342        args = { '--listen', address },
343      })
344      set_session(server)
345      eq(vim.fs.normalize(address), api.nvim_get_vvar('servername'))
346      connect_test(server, 'pipe', address)
347    end)
348
349    it('via ipv4 address', function()
350      local server = n.new_session(false)
351      set_session(server)
352      local status, address = pcall(fn.serverstart, '127.0.0.1:')
353      if not status then
354        pending('no ipv4 stack')
355      end
356      eq('127.0.0.1:', string.sub(address, 1, 10))
357      connect_test(server, 'tcp', address)
358    end)
359
360    it('via ipv6 address', function()
361      local server = n.new_session(false)
362      set_session(server)
363      local status, address = pcall(fn.serverstart, '::1:')
364      if not status then
365        pending('no ipv6 stack')
366      end
367      eq('::1:', string.sub(address, 1, 4))
368      connect_test(server, 'tcp', address)
369    end)
370
371    it('via hostname', function()
372      local server = n.new_session(false)
373      set_session(server)
374      local address = fn.serverstart('localhost:')
375      eq('localhost:', string.sub(address, 1, 10))
376      connect_test(server, 'tcp', address)
377    end)
378
379    local function start_server_and_client()
380      local server = n.new_session(false)
381      set_session(server)
382      local address = fn.serverlist()[1]
383      local client = n.new_session(true)
384      set_session(client)
385
386      local id = fn.sockconnect('pipe', address, { rpc = true })
387
388      finally(function()
389        server:close()
390        client:close()
391      end)
392
393      return id
394    end
395
396    it('does not crash on receiving UI events', function()
397      local id = start_server_and_client()
398      fn.rpcrequest(id, 'nvim_ui_attach', 80, 24, {})
399      assert_alive()
400    end)
401
402    it('does not leak memory with channel closed before response', function()
403      local id = start_server_and_client()
404      eq(
405        ('ch %d was closed by the peer'):format(id),
406        pcall_err(n.exec_lua, function()
407          vim.rpcrequest(id, 'nvim_command', 'qall!')
408        end)
409      )
410      eq({}, api.nvim_get_chan_info(id)) -- Channel is closed.
411    end)
412
413    it('response works with channel closed just after response #24214', function()
414      local id = start_server_and_client()
415      eq(
416        'RESPONSE',
417        n.exec_lua(function()
418          local prepare = assert(vim.uv.new_prepare())
419          -- Block the event loop after writing the request but before polling for I/O
420          -- so that response and EOF arrive at the same uv_run() call.
421          prepare:start(function()
422            vim.uv.sleep(50)
423            prepare:close()
424          end)
425          return vim.rpcrequest(
426            id,
427            'nvim_exec_lua',
428            [[vim.schedule(function() vim.cmd('qall!') end); return 'RESPONSE']],
429            {}
430          )
431        end)
432      )
433      t.retry(nil, nil, function()
434        eq({}, api.nvim_get_chan_info(id)) -- Channel is closed.
435      end)
436    end)
437
438    it('via stdio, with many small flushes does not crash #23781', function()
439      source([[
440      let chan = jobstart([v:progpath, '--embed', '--headless', '-n', '-u', 'NONE', '-i', 'NONE'], { 'rpc':v:false })
441      call chansend(chan, 0Z94)
442      sleep 50m
443      call chansend(chan, 0Z00)
444      call chansend(chan, 0Z01)
445      call chansend(chan, 0ZAC)
446      call chansend(chan, 0Z6E76696D5F636F6D6D616E64)
447      call chansend(chan, 0Z91)
448      call chansend(chan, 0ZA5)
449      call chansend(chan, 0Z71616C6C21)
450      let g:statuses = jobwait([chan])
451      ]])
452      eq({ 0 }, eval('g:statuses'))
453      assert_alive()
454    end)
455  end)
456
457  describe('connecting to its own pipe address', function()
458    it('does not deadlock', function()
459      local address = fn.serverlist()[1]
460      local first = string.sub(address, 1, 1)
461      ok(first == '/' or first == '\\')
462      local serverpid = fn.getpid()
463
464      local id = fn.sockconnect('pipe', address, { rpc = true })
465
466      fn.rpcrequest(id, 'nvim_set_current_line', 'hello')
467      eq('hello', api.nvim_get_current_line())
468      eq(serverpid, fn.rpcrequest(id, 'nvim_eval', 'getpid()'))
469
470      eq(id, fn.rpcrequest(id, 'nvim_get_chan_info', 0).id)
471    end)
472  end)
473end)