robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
7.2 KiB222 linesraw
1-- For "--listen", ":restart", and related remote/server functionality.
2
3local util = require('vim._core.util')
4
5local M = {}
6
7--- Called by builtin serverlist(). Returns the combined server list (own + peers).
8---
9---@class vim.ServerInfo
10---@field addr string Server address (socket path, named pipe, or TCP host:port).
11---@field pid integer PID of the Nvim process.
12---@field own boolean True if this server belongs to the current Nvim instance.
13---@field active integer Timestamp of last user activity.
14
15--- @param opts? table Options:
16---              - opts.peer (boolean): If true, also discover peer servers.
17---              - opts.info (boolean): If true, return a list of |vim.ServerInfo| dicts
18---                instead of a list of addresses. Implies peer=true.
19--- @param addrs string[] Internal ("own") addresses, from server_address_list.
20--- @return string[]|vim.ServerInfo[]
21function M.serverlist(opts, addrs)
22  if type(opts) ~= 'table' then
23    return addrs
24  end
25
26  local want_info = opts.info == true
27  if opts.peer ~= true and not want_info then
28    return addrs
29  end
30
31  local seen = {} ---@type table<string, true>
32  for _, a in ipairs(addrs) do
33    seen[a] = true
34  end
35
36  local peers ---@type string[]|vim.ServerInfo[]
37  if want_info then
38    local self_pid = vim.fn.getpid()
39    local self_active = vim.v.useractive
40    peers = vim.tbl_map(function(addr)
41      return {
42        addr = addr,
43        pid = self_pid,
44        own = true,
45        active = self_active,
46      }
47    end, addrs)
48  else
49    peers = addrs
50  end
51
52  -- Discover peer servers in stdpath("run").
53  -- TODO: track TCP servers, somehow.
54  -- TODO: support Windows named pipes.
55  local root = vim.fs.normalize(vim.fn.stdpath('run') .. '/..')
56  local socket_paths = vim.fs.find(function(name, _)
57    return name:match('nvim.*')
58  end, { path = root, type = 'socket', limit = math.huge })
59
60  for _, socket in ipairs(socket_paths) do
61    if not seen[socket] then
62      local ok, chan = pcall(vim.fn.sockconnect, 'pipe', socket, { rpc = true })
63      if ok and chan and chan > 0 then
64        --- @cast chan integer
65        -- Check that the server is responding
66        -- TODO: do we need a timeout or error handling here?
67        local ok_rpc, peer_info = pcall(
68          vim.fn.rpcrequest,
69          chan,
70          'nvim_exec_lua',
71          [[return { pid = vim.fn.getpid(), active = vim.v.useractive, }]],
72          {}
73        )
74
75        if ok_rpc and type(peer_info) == 'table' then
76          ---@cast peer_info vim.ServerInfo
77          seen[socket] = true
78          if want_info then
79            table.insert(peers, {
80              addr = socket,
81              pid = peer_info.pid,
82              own = false,
83              active = peer_info.active,
84            })
85          else
86            table.insert(peers, socket)
87          end
88        end
89        pcall(vim.fn.chanclose, chan)
90      end
91    end
92  end
93
94  return peers
95end
96
97-- (Windows only) Canonical --listen address persisted across restarts.
98M.restart_canonical_addr = nil ---@type string?
99
100--- (Windows only)
101--- Called on the new server via nvim_exec_lua RPC from the old server (:restart).
102--- Windows named pipes can't be rebound immediately, so the new server starts on a
103--- temporary bootstrap address and polls until the canonical address is reclaimable.
104--- @param canonical_addr string  The original --listen address to reclaim.
105--- @param expected_uis   integer Number of UIs expected to reattach (0 = don't wait).
106function M.rebind_after_restart(canonical_addr, expected_uis)
107  M.restart_canonical_addr = canonical_addr
108  local bootstrap_addr = vim.v.servername -- Temporary autogenerated address.
109  local poll_ms = 50
110  local max_wait_ms = 30000
111  local timer = assert(vim.uv.new_timer())
112
113  -- Poll until the canonical address can be reclaimed (or timeout).
114  local poll_elapsed = 0
115  timer:start(poll_ms, poll_ms, function()
116    vim.schedule(function()
117      if timer:is_closing() then
118        return
119      end
120      poll_elapsed = poll_elapsed + poll_ms
121      if poll_elapsed >= max_wait_ms then
122        timer:stop()
123        timer:close()
124        return
125      end
126      if not vim.list_contains(vim.fn.serverlist(), canonical_addr) then
127        local ok = vim._with({ log_level = 5 }, function()
128          return pcall(vim.fn.serverstart, canonical_addr)
129        end)
130        if not ok then
131          return -- pipe still held by old server; retry next tick
132        end
133      end
134
135      -- Wait for UIs to reattach, then retire the bootstrap address.
136      local elapsed = 0
137      timer:stop()
138      timer:start(poll_ms, poll_ms, function()
139        vim.schedule(function()
140          if timer:is_closing() then
141            return
142          end
143          elapsed = elapsed + poll_ms
144          local all_uis = expected_uis <= 0 or #vim.api.nvim_list_uis() >= expected_uis
145          if all_uis or elapsed >= max_wait_ms then
146            if canonical_addr ~= bootstrap_addr then
147              vim._with({ log_level = 5 }, function()
148                pcall(vim.fn.serverstop, bootstrap_addr)
149              end)
150            end
151            timer:stop()
152            timer:close()
153          end
154        end)
155      end)
156    end)
157  end)
158end
159
160-- Called by ex_restart(). Saves the current session and calls ex_restart() (again) with the
161-- updated arguments.
162--
163-- TODO: https://github.com/neovim/neovim/issues/34204
164--
165--- @param eap vim._core.ExCmdArgs
166--- @param extra { quit_cmd: string }
167function M.ex_session_restart(eap, extra)
168  local after_cmd = eap.args -- User-provided [command].
169  assert(not after_cmd:find(']==]'))
170
171  -- Use custom +cmd if given.
172  local quit_cmd = extra.quit_cmd == '' and 'qall' or extra.quit_cmd
173
174  -- Preserve v:this_session in the restarted Nvim.
175  local this_session = vim.v.this_session
176  assert(not this_session:find(']==]'))
177
178  -- Nvim temp "root dir": "/tmp/…/nvim.<user>/"
179  local tmproot = vim.fs.abspath(vim.fs.dirname(vim.fs.dirname(vim.fn.tempname())))
180  assert(not tmproot:find(']==]'))
181  local fd, session = vim.uv.fs_mkstemp(vim.fs.joinpath(tmproot, 'restart_session_XXXXXX'))
182  if not fd then
183    error('Failed to get temporary filename for restart session')
184  end
185  vim.uv.fs_close(fd)
186
187  -- Write session
188  local session_arg = vim.fn.fnameescape(session)
189  vim.cmd('%argdelete')
190  vim.cmd.mksession { session_arg, bang = true }
191
192  -- Lua commands to restore the session and remove the session file
193  local after_list = {}
194  table.insert(after_list, ('vim.cmd("source %s")'):format(session_arg))
195  table.insert(after_list, ('pcall(vim.fs.rm, [==[%s]==])'):format(session))
196  table.insert(after_list, ('vim.v.this_session = [==[%s]==]'):format(this_session))
197  if after_cmd ~= '' then
198    table.insert(after_list, ('vim.cmd([==[%s]==])'):format(after_cmd))
199  end
200  local after = 'lua ' .. table.concat(after_list, ';')
201
202  -- Restart Neovim and run our Lua commands
203  local success, msg = pcall(function()
204    -- "+:::" dummy prefix tells the C handler that this is actually a non-bang restart.
205    -- Then v:startreason (if any) can be preserved.
206    vim.cmd.restart { '+:::', quit_cmd, after, bang = true }
207  end)
208
209  if not success then
210    --- @cast msg string
211    vim.fs.rm(session, { force = true })
212
213    -- Trim error message to be equivalent to `:restart!`
214    if msg:find('Vim:') then
215      util.echo_err(util.cmd_errmsg(msg))
216    else
217      error(msg)
218    end
219  end
220end
221
222return M