1 local log = require "util.logger".init("util.async");
3 local function runner_continue(thread)
4 -- ASSUMPTION: runner is in 'waiting' state (but we don't have the runner to know for sure)
5 if coroutine.status(thread) ~= "suspended" then -- This should suffice
8 local ok, state, runner = coroutine.resume(thread);
11 while debug.getinfo(thread, level, "") do level = level + 1; end
12 ok, runner = debug.getlocal(thread, level-1, 1);
13 local error_handler = runner.watchers.error;
14 if error_handler then error_handler(runner, debug.traceback(thread, state)); end
15 elseif state == "ready" then
16 -- If state is 'ready', it is our responsibility to update runner.state from 'waiting'.
17 -- We also have to :run(), because the queue might have further items that will not be
18 -- processed otherwise. FIXME: It's probably best to do this in a nexttick (0 timer).
19 runner.state = "ready";
25 local function waiter(num)
26 local thread = coroutine.running();
28 error("Not running in an async context, see http://prosody.im/doc/developers/async");
33 if num == 0 then return; end -- already done
35 coroutine.yield("wait");
38 if num == 0 and waiting then
39 runner_continue(thread);
45 runner_mt.__index = runner_mt;
47 local function runner_create_thread(func, self)
48 local thread = coroutine.create(function (self)
50 func(coroutine.yield("ready", self));
53 assert(coroutine.resume(thread, self)); -- Start it up, it will return instantly to wait for the first input
57 local empty_watchers = {};
58 local function runner(func, watchers, data)
59 return setmetatable({ func = func, thread = false, state = "ready", notified_state = "ready",
60 queue = {}, watchers = watchers or empty_watchers, data = data }
64 function runner_mt:run(input)
66 table.insert(self.queue, input);
68 if self.state ~= "ready" then
69 return true, self.state, #self.queue;
72 local q, thread = self.queue, self.thread;
73 if not thread or coroutine.status(thread) == "dead" then
74 thread = runner_create_thread(self.func, self);
78 local n, state, err = #q, self.state, nil;
79 self.state = "running";
80 while n > 0 and state == "ready" do
84 local ok, new_state = coroutine.resume(thread, input);
86 consumed, state, err = i, "ready", debug.traceback(thread, new_state);
89 elseif new_state == "wait" then
90 consumed, state = i, "waiting";
94 if not consumed then consumed = n; end
104 if state ~= self.notified_state then
105 self.notified_state = state;
106 local handler = self.watchers[state];
107 if handler then handler(self, err); end
109 return true, state, n;
112 function runner_mt:enqueue(input)
113 table.insert(self.queue, input);
116 return { waiter = waiter, runner = runner };