robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
10.0 KiB317 linesraw
1local core = require('vim.async._core')
2local validate = vim.validate
3local new_queue = require('vim.async._queue')
4local runtime = require('vim.async._runtime')
5local F = vim.F
6
7--- Structured async API for Lua code that waits on event-loop work.
8---
9--- `vim.async` lets Lua code wait for timers, callbacks, and other tasks
10--- without blocking Nvim's event loop. Async work runs inside tasks, which can
11--- pause at checkpoints and manage child tasks created while they are running.
12---
13--- Start async work with [vim.async.run()]. Inside a task, use
14--- [vim.async.await()] to wait for callback-style APIs or other tasks without
15--- blocking the event loop. Use [vim.async.pawait()] when an awaited operation
16--- can fail and the current task should continue.
17---
18--- Examples in this help use `local async = vim.async` for brevity.
19---
20--- Example: run async work without blocking Nvim:
21---
22--- ```lua
23--- local async = vim.async
24---
25--- async.run(function()
26---   vim.notify('waiting...')
27---   async.sleep(1000)
28---   vim.notify('done')
29--- end)
30--- ```
31---
32--- Example: await a callback-style API. Callback results are returned
33--- unchanged, so an error-first callback still returns `err, value`:
34---
35--- ```lua
36--- local async = vim.async
37---
38--- async.run(function()
39---   local err, stat = async.await(2, fs_stat, 'notes.txt')
40---   if err then
41---     error(err, 0)
42---   end
43---   print(('notes.txt is %d bytes'):format(stat.size))
44--- end)
45--- ```
46---
47--- A task has two roles:
48---
49--- - it is a handle that can be awaited, waited for, or closed
50--- - it is a scope for child tasks created while the task is running
51---
52--- [vim.async.run()] creates a task. A top-level task starts immediately. A
53--- task created while another task is running becomes a child of that task, and
54--- its function starts when the parent reaches its next checkpoint. A parent
55--- task finishes only after its attached children finish. If a child fails
56--- without being handled, the parent fails and closes the remaining children.
57---
58--- Use [Task:detach()] for background work that should keep running after the
59--- current task finishes. A detached task becomes top-level work; the original
60--- parent no longer waits for it or closes it.
61---
62--- Awaiting a task observes that task's result; it does not attach the task to
63--- the awaiter or change which task owns it. Ownership is decided when the task
64--- is created.
65---
66--- Scheduling is cooperative. When a task awaits a timer, I/O operation,
67--- callback, or another task, `vim.async` saves the Lua stack and returns
68--- control to the event loop. Other callbacks can run while the task is paused.
69--- Nothing interrupts synchronous Lua code in the middle of a stack frame.
70---
71--- Checkpoints are the places where a task can pause, start pending child
72--- tasks, observe cancellation, and receive unhandled child failures. Inside a
73--- task, these operations are checkpoints:
74---
75--- - `vim.async.await(...)`
76--- - `vim.async.pawait(...)`
77--- - `vim.async.checkpoint()`
78--- - successful return from the task function, which is the final checkpoint
79---   for child management
80---
81--- Convenience APIs such as [vim.async.sleep()] and [vim.async.timeout()] can
82--- also checkpoint because they call checkpointing APIs internally.
83---
84--- Closing a task closes its attached children. Cancellation is cooperative:
85--- [Task:close()] marks a task as closing, and the task observes that state at
86--- a checkpoint. If a task is suspended on a closable operation such as a timer
87--- or child task, `vim.async` closes that operation before reporting the
88--- cancellation.
89---
90--- Use [vim.async.await()] inside a task to suspend until work completes. It
91--- accepts a task, a callback-taking function, or an argument position plus a
92--- callback-taking function. `await(task)` returns the task result or raises
93--- the task failure. [vim.async.pawait()] is the async counterpart to `pcall()`
94--- for recoverable awaited-operation failures; it returns `ok, ...` instead of
95--- failing the current task for that awaited operation. It does not suppress
96--- cancellation or a failure already pending on the current task.
97---
98--- From synchronous code, use [Task:wait()] or [Task:pwait()] to pump the event
99--- loop until the task completes. Use [Task:on_complete()] to observe
100--- completion without blocking.
101---
102--- Coordination helpers work with task handles. [vim.async.iter()] yields
103--- completed task handles in completion order, [vim.async.timeout()] awaits a
104--- task with a deadline, and `vim.async.semaphore(permits)` creates a
105--- [vim.async.Semaphore] that limits how many tasks can hold a permit for a
106--- section at once.
107--- @class vim.async: vim.async._core
108local M = setmetatable({}, { __index = core })
109
110M.semaphore = require('vim.async._semaphore')
111
112--- @param unsubscribe fun()[]
113local function unsubscribe_all(unsubscribe)
114  for _, unsub in ipairs(unsubscribe) do
115    unsub()
116  end
117end
118
119--- Create an async function from a callback-style function.
120---
121--- The callback is inserted at argument position `argc`. If `func` returns a
122--- closable handle, it is closed when the awaiting task is cancelled.
123---
124--- This is a reusable wrapper around [vim.async.await()]. Use it when the same
125--- callback API is awaited from more than one place.
126---
127--- ```lua
128--- local async = vim.async
129--- local fs_stat = async.wrap(2, vim.uv.fs_stat)
130---
131--- async.run(function()
132---   local err, stat = fs_stat(vim.api.nvim_buf_get_name(0))
133---   if not err and stat then
134---     print(stat.size)
135---   end
136--- end)
137--- ```
138---
139--- @generic T, R
140--- @param argc integer
141--- @param func fun(...: T..., callback: fun(...: R...)): vim.async.Closable?
142--- @return async fun(...: T...): R...
143function M.wrap(argc, func)
144  validate('argc', argc, 'number')
145  validate('func', func, 'callable')
146  --- @async
147  return function(...)
148    return M.await(argc, func, ...)
149  end
150end
151
152--- Iterate completed tasks in completion order.
153---
154--- The iterator yields task handles, not task results. Use
155--- [vim.async.await()] or [vim.async.pawait()] to retrieve each result. The
156--- tasks are observed in the order they complete, regardless of the order in
157--- the input list.
158---
159--- ```lua
160--- local async = vim.async
161---
162--- async.run(function()
163---   local tasks = {
164---     async.run(function() return 'cache', read_cache() end):detach(),
165---     async.run(function() return 'disk', read_file() end):detach(),
166---   }
167---
168---   for task in async.iter(tasks) do
169---     local ok, source, text = async.pawait(task)
170---     if ok then
171---       for _, other in ipairs(tasks) do
172---         if other ~= task then
173---           other:close()
174---         end
175---       end
176---       print(('loaded from %s'):format(source))
177---       return text
178---     end
179---   end
180--- end)
181--- ```
182---
183--- If code must support PUC Lua 5.1, use the direct-call form instead of a
184--- generic `for` loop. The iterator may need to suspend while waiting for the
185--- next completed task, and PUC Lua 5.1 cannot yield from a generic-for
186--- iterator call.
187---
188--- ```lua
189--- local next_task = async.iter(tasks)
190--- while true do
191---   local task = next_task()
192---   if task == nil then
193---     break
194---   end
195---   async.await(task)
196--- end
197--- ```
198--- @async
199--- @generic R
200--- @param tasks vim.async.Task<R>[] A list of tasks to wait for and iterate over.
201--- @return async fun(): vim.async.Task<R>? iterator that yields each completed task.
202function M.iter(tasks)
203  validate('tasks', tasks, 'table')
204
205  local remaining = #tasks
206  local queue = new_queue()
207  local unsubscribe = {} --- @type fun()[]
208
209  if remaining == 0 then
210    queue:put_nowait()
211  else
212    for _, task in ipairs(tasks) do
213      unsubscribe[#unsubscribe + 1] = task:on_complete(function()
214        remaining = remaining - 1
215        queue:put_nowait(task)
216        if remaining == 0 then
217          queue:put_nowait()
218        end
219      end)
220    end
221  end
222
223  local proxy = newproxy(true)
224  getmetatable(proxy).__gc = function()
225    unsubscribe_all(unsubscribe)
226  end
227
228  --- @async
229  return function()
230    local _ = proxy -- Keep the GC proxy alive with the iterator.
231    return queue:get()
232  end
233end
234
235--- Asynchronously sleep for a given duration.
236---
237--- Suspends the current task for the given duration without blocking the event
238--- loop. After the delay and timer cleanup complete, `sleep()` returns to its
239--- caller through the runtime's `schedule` hook.
240---
241--- ```lua
242--- vim.async.run(function()
243---   vim.async.sleep(100)
244---   vim.notify('resumed later')
245--- end)
246--- ```
247--- @async
248--- @param duration integer ms
249function M.sleep(duration)
250  validate('duration', duration, 'number')
251  M.await(function(callback)
252    local timer = runtime.new_timer()
253    timer:start(duration, 0, callback)
254    return timer
255  end)
256  -- Timer cleanup resumes this function directly from its close callback.
257  -- Yield once more so M.sleep() returns through the runtime scheduler.
258  M.await(runtime.schedule)
259end
260
261--- Await a task with a timeout.
262---
263--- If the task completes first, returns or raises the task result as
264--- [vim.async.await()] would. If the deadline wins, closes the task and raises
265--- `"timeout"` after the target task finishes cancellation cleanup.
266---
267--- ```lua
268--- local async = vim.async
269---
270--- async.run(function()
271---   local task = async.run(read_file, 'notes.txt')
272---   local text = async.timeout(5000, task)
273---   show_buffer(text)
274--- end)
275--- ```
276--- @async
277--- @generic R
278--- @param duration integer Timeout duration in milliseconds
279--- @param task vim.async.Task<R>
280--- @return R...
281function M.timeout(duration, task)
282  validate('duration', duration, 'number')
283  validate('task', task, 'table')
284
285  local timed_out = false
286  local timer = M.run('__timeout', function()
287    M.sleep(duration)
288    timed_out = true
289    task:close()
290  end)
291  --- @diagnostic disable-next-line: access-invisible
292  timer._hidden = true
293
294  local result = F.pack_len(M.pawait(task))
295  timer:close()
296  M.pawait(timer)
297
298  if timed_out then
299    error('timeout', 0)
300  end
301
302  if not result[1] then
303    error(result[2], 0)
304  end
305
306  return unpack(result, 2, result.n)
307end
308
309if type(vim) == 'table' then
310  runtime.config({
311    wait = vim.wait,
312    schedule = vim.schedule,
313    new_timer = vim.uv.new_timer,
314  })
315end
316
317return M