Asynchronous I/O runtime for Lilush, built on epoll.
Provides coroutine-based concurrency with timers, UDP/TCP sockets, cancellation tokens, conditions, and structured task combinators.
| Name | Signature |
|---|---|
| set_logger | set_logger(logger) |
| own | own(resource) -> resource |
| defer | defer(fn) |
| disown | disown(resource) -> resource |
| spawn | spawn(fn, opts) -> task |
| await | await(task) -> result, err |
| cancel_token | cancel_token() -> token |
| sleep | sleep(seconds, cancel) -> true, err |
| cond | cond() -> cond |
| race | race(fns) -> results, err |
| all | all(fns) -> results, err |
| on_signal | on_signal(signum, handler) -> true, err |
| stop | stop() |
| loop_id | loop_id() -> id |
| udp | udp() -> socket, err |
| tls_identity | tls_identity(cert_path, key_path, names) -> identity, err |
| tcp | tcp() -> socket, err |
| connect | connect(addr, port, opts) -> socket, err |
| listen | listen(addr, port, opts) -> listener, err |
| connect_unix | connect_unix(path, opts) -> socket, err |
| listen_unix | listen_unix(path, opts) -> listener, err |
| exec | exec(path, args, opts) -> proc, err |
| task_name | task_name(name) -> name |
| stats | stats() -> stats |
| task_tree | task_tree() -> tasks |
| task_dump | task_dump() -> tasks |
| enable_dump_signal | enable_dump_signal(format) -> true, err |
| set_nonblocking | set_nonblocking(fd, enable) -> was_nonblocking, err |
| fd_reader | fd_reader(fd) -> reader |
| run | run(fn) -> result, err |
set_logger(
logger)
Inject a structured logger for LEV error reporting
Sets a std.logger instance to receive LEV error messages (cleanup
errors, detached task errors). The logger persists across run() calls.
Pass nil to revert to stderr.
own(
resource) ->resource
Register a resource for auto-close when the current task completes
Registers resource for automatic cleanup when the current coroutine
finishes (success or error). The resource must have a close() method.
Returns the resource for chaining: local sock = lev.own(lev.connect(...)).
No-op outside lev.run() or from non-spawned coroutines.
The loop calls close() itself once the task has ended, outside any
task. A wait in it raises lev: wait outside a task.
defer(
fn)
Register an arbitrary cleanup function for the current task
Registers fn to run when the current coroutine finishes (success or
error). Cleanups run in LIFO order, like Go's defer. Errors in cleanup
functions are logged via log_error and don't prevent other cleanups from running.
No-op outside lev.run() or from non-spawned coroutines.
The loop calls fn itself once the task has ended, outside any task.
A wait in it raises lev: wait outside a task.
disown(
resource) ->resource
Remove a resource from auto-close tracking
Removes resource from the current task's cleanup list (identity
comparison). Use for ownership transfer between coroutines. Returns
the resource for chaining. No-op if the resource is not tracked.
spawn(
fn,opts) ->task
Spawn a new concurrent task
Spawns fn as a new coroutine that runs concurrently within the
current lev.run() event loop. Returns a task handle that can be
passed to await().
Options:
detached (boolean): If true, errors are logged when the task
completes and the task is typically not awaited.Raises outside lev.run(), and when fn is not a function.
await(
task) ->result,err
Wait for a spawned task to complete
Yields the current coroutine until the given task finishes. Returns
the task's return values on success, or nil, err on error.
cancel_token() ->
token
Create a cancellation token
Returns a cancel token that can be passed to sleep(), connect(),
accept(), and other blocking operations to enable cooperative
cancellation. Call token:cancel() to interrupt all registered waiters.
token.cancelled reads true once it has fired.
sleep(
seconds,cancel) ->true,err
Suspend the current coroutine for a duration
Yields the current coroutine and resumes it after the given number
of seconds (fractional seconds supported). Returns true on
normal completion, or nil, "cancelled" if the cancel token has
fired by the time the coroutine wakes up.
cond() ->
cond
Create a condition, on which tasks wait for one another
Returns a condition: a list of waiting tasks that another task, a signal
handler or a cleanup wakes. A wait with no timeout holds no timer and no
fd. A condition made outside lev.run() serves every loop after it.
cond:wait(timeout_or_opts) parks the calling task. It returns true
once a signal takes it, nil, "timeout", or nil, "cancelled". The
argument is a timeout in seconds or { timeout = N, cancel = token }.
A timeout at or below zero returns nil, "timeout" with no wait, and a
token that has fired returns nil, "cancelled" with none.cond:signal() wakes the task that has waited longest. Returns true
if one waited, false otherwise.cond:broadcast() wakes every waiting task. Returns their count.A condition has no memory: a signal with no waiter is dropped. Check the state the wait is for, then wait, with no other wait between the two, and check again after the wake:
while #queue == 0 do
if not ready:wait() then
return
end
end
signal and broadcast only queue the waiters, which run on the loop's
next turn. Neither waits, so a signal handler and a cleanup may call them.
wait raises lev: wait outside a task there.
race(
fns) ->results,err
Run functions concurrently, return first result
Spawns each function in the list. When the first one finishes (success or error), cancels the rest and returns that result. Each function receives a cancel token as its first argument. A competitor's raise goes into the answer or is dropped, and lev does not log it.
all(
fns) ->results,err
Run functions concurrently, wait for all to complete
Spawns each function and waits for all to complete. Returns a list
of result tables, one per function in the order given. Each holds its
function's values and their count in n, so a trailing nil counts.
If any task errors, cancels the rest and returns nil, err immediately.
The answer carries the first raise. Lev logs no member's raise, the
first or a later one.
on_signal(
signum,handler) ->true,err
Register a signal handler
Registers a callback to be invoked when the specified signal is
delivered. Must be called within lev.run(). The handler receives
the signal number as its argument.
The loop calls the handler itself, outside any task. A wait in it
raises lev: wait outside a task. A handler that must wait spawns a
task.
A second handler for one signal takes the first one's place. A handler
stays until the run ends: nil is no handler and raises.
Raises on SIGKILL and SIGSTOP, which no program can catch, and on a
number that names no signal. Returns nil, err when the kernel refuses
the setup. The handlers and the signal mask are then as they were.
stop()
Force-stop the event loop
Sets the loop's running flag to false, causing lev.run() to exit
on the next iteration regardless of active coroutines. Intended for
use in signal handlers to implement graceful shutdown with a deadline.
Must be called within lev.run().
loop_id() ->
id
The current run's id
Returns a number that names the running lev.run, or nil outside one.
Each run takes a number greater than the one before it.
State kept across runs uses it to tell a waiter of this run from one a
stopped run left: lev.stop ends a run with its tasks parked, and they
never resume.
udp() ->
socket,err
Create a non-blocking UDP socket
Returns a wrapped UDP socket that integrates with the event loop.
The recvfrom method yields the current coroutine until data
arrives, with optional timeout and cancellation support.
bind(addr, 0) binds a port the kernel picks. getsockname returns the
bound addr, port, or 0.0.0.0 and 0 on a socket not yet bound. A
sendto on an unbound socket binds it.
bind and sendto answer nil, "invalid port" for a port outside
0..65535.
tls_identity(
cert_path,key_path,names) ->identity,err
Parse a cert+key PEM pair into a reusable TLS identity
Parses a PEM certificate chain and private key from regular files into a
Lua userdata for starttls() (identity or certs). Each file holds at
most 256 KB, and both paths may name one combined PEM bundle. Reusing one
identity across connections avoids per-connection file I/O and PEM parsing.
An identity answers for a list of hostnames when used for SNI. names
is a single hostname or an array of them; omitting it derives the list
from the certificate itself -- its SAN dNSName entries, or its common
name when it has none. A wildcard certificate covering both an apex and
its subdomains therefore needs no configuration at all. Explicit names
replace the certificate's own rather than adding to them.
Fails when the certificate declares no name usable for SNI and none was given.
tcp() ->
socket,err
Create a non-blocking TCP socket
Returns a wrapped TCP socket that integrates with the event loop.
Provides send, recv, recv_exactly, recv_until methods
with async I/O via wait_readable/wait_writable. Supports TLS
upgrade via starttls. One task may read while another writes: each
direction holds its own waiter on the socket. Until a TLS handshake is
done, send and recv from another task return nil, "not connected".
On a TLS client socket past its handshake, peer_key_hash returns the
SHA-256 of the SubjectPublicKeyInfo of the server's certificate, as 32
raw bytes. It reads the same with verify = false, so a caller can pin
a server's key or trust it on first use.
getsockname returns the socket's own addr, port, and getpeername
the far end's. On an AF_UNIX socket both return
nil, "not an IP socket". getpeercred returns the peer's
pid, uid, gid on a connected AF_UNIX socket, and
nil, "not a unix socket" on a TCP socket.
send(data, opts) takes two limits. opts.timeout is the deadline for
the whole call: 30 seconds when nil, none when false. opts.stall ends
the send with "timeout" once the socket has taken nothing for that many
seconds. A send that fails returns nil, err, sent, where sent counts
the bytes the socket took. After a timeout or a cancel the stream is
whole, and send(data:sub(sent + 1)) resumes it. Under TLS sent counts
bytes sealed into records, and the last record may wait in the socket:
the next send writes it first, an empty one included.
recv(maxlen) reads up to 4096 bytes when maxlen is nil or at or
below zero. recv_exactly(0) returns "", and a negative n returns
nil, "invalid length". A recv_exactly that fails keeps the bytes it
read for the next read. recv_until answers nil, "max_size exceeded"
when its match ends past max_size (65536 when nil), and keeps the
bytes.
connect(
addr,port,opts) ->socket,err
Connect to a remote TCP server
Creates a TCP socket, connects to addr:port, and optionally
performs a TLS handshake. Returns a wrapped TCP socket on success.
A port outside 0..65535 answers nil, "invalid port".
Options:
timeout (number): connection timeout in seconds. At or below zero,
a connect that does not finish at once answers "timeout"tls (table): if present, perform TLS after connecting (passed to starttls)cancel (token): cancel token; propagated to TLS handshake if tls.cancel is not setlisten(
addr,port,opts) ->listener,err
Create a bound listening TCP socket
Creates and binds a TCP listener socket. Returns a listener object
with an accept method that yields until a client connects.
accept takes a timeout (number) or an options table
{ timeout = N, cancel = token }.
Port 0 binds a port the kernel picks. The listener's getsockname
returns the bound addr, port, so a caller reads the pick back with no
probe for a free port, and no race for it. A port outside 0..65535
answers nil, "invalid port".
Options:
reuseport (boolean): enable SO_REUSEPORTbacklog (number): listen backlog (default 128)connect_unix(
path,opts) ->socket,err
Connect to a Unix domain (AF_UNIX) stream socket
Creates an AF_UNIX stream socket and connects to path. A leading @
selects the Linux abstract namespace (no filesystem entry). Returns a
wrapped socket exposing the same methods as a TCP socket. Its
getpeercred method returns pid, uid, gid of the listening process,
recorded when the listener called listen.
Options:
timeout (number): connection timeout in seconds. At or below zero,
a connect that does not finish at once answers "timeout"tls (table): if present, perform TLS after connecting (passed to starttls)cancel (token): cancel token; propagated to TLS handshake if tls.cancel is not setlisten_unix(
path,opts) ->listener,err
Create a bound listening Unix domain (AF_UNIX) stream socket
Creates and binds an AF_UNIX stream listener at path. A leading @
selects the Linux abstract namespace (no filesystem entry, auto-cleaned).
Returns a listener object whose accept method yields until a client
connects, returning a wrapped socket (no peer address for AF_UNIX).
accept takes a timeout (number) or { timeout = N, cancel = token }.
The accepted socket's getpeercred method returns pid, uid, gid of
the connecting process, recorded at connect.
The listener has the methods of a TCP listener. An AF_UNIX socket has no
address and port, so its getsockname returns nil, "not an IP socket".
Options:
backlog (number): listen backlog (default 128)unlink (boolean): for filesystem paths, remove a stale socket file before
binding and on close (default true; ignored for abstract @ paths)exec(
path,args,opts) ->proc,err
Execute an external command asynchronously
Spawns an external command as a child process with non-blocking pipe I/O
and pidfd-based exit notification. Returns a process handle with async
send, recv, recv_stderr, read_all, wait, and kill methods.
Options:
cwd (string): working directory for childenv (table): array of "KEY=VALUE" strings, replaces child environmentstderr_to_stdout (boolean): merge stderr into stdout stream. The child
gets no stderr pipe, and recv_stderr answers nil, "closed"new_session (boolean): start the child in a session of its own, with no
controlling terminal, so a terminal's Ctrl+C reaches the parent aloneThe child starts with no signal blocked and every caught handler at its
default, whatever signals the loop holds through on_signal. A send to a
child that has closed its stdin or exited answers nil, "closed" and raises
no SIGPIPE. An empty send answers the same, and 0 to a child that reads.
A program that closed its own stdin, stdout or stderr spawns as any other: the child moves its pipe ends above descriptor 2 before it redirects.
send(data, opts) takes a socket's limits: opts.timeout, 30 seconds
when nil and none when false, and opts.stall. A send that fails
returns nil, err, sent, where sent counts the bytes the pipe took.
task_name(
name) ->name
Set or get the current task's name
With an argument, sets the name of the current task and returns it.
Without an argument, returns the current task's name (or nil).
No-op outside lev.run().
stats() ->
stats
Get fast loop stats snapshot
Returns a table with loop counters: active_coros, registered_fds,
timer_count, ready_count (from C core), and task_count (Lua-side
count of entries in the task registry). Returns nil outside lev.run().
task_tree() ->
tasks
Get structured task list
Returns a sorted array of task info tables, each with fields:
id, name, status, detached, parent_id, co_status.
Sorted by id for stable output. Returns nil outside lev.run().
task_dump() ->
tasks
Get detailed task dump with tracebacks
Like task_tree() but adds a traceback field for suspended coroutines,
showing the exact yield point. Has meaningful overhead -- use for debugging,
not monitoring. Returns nil outside lev.run().
enable_dump_signal(
format) ->true,err
Enable SIGUSR1 task dump handler
Registers a SIGUSR1 handler that calls task_dump() and outputs the
result. Supports "text" (default) and "json" formats. Uses the
injected logger if set, otherwise stderr. Safe because signal handlers
in LEV run via signalfd dispatch (not async-signal context).
Raises lev: unknown dump format on any other format. Returns what
on_signal returns: true, or nil, err when the kernel refuses the
setup. "json" loads cjson.safe at the call, not in the handler.
set_nonblocking(
fd,enable) ->was_nonblocking,err
Toggle O_NONBLOCK on an arbitrary fd
Sets or clears O_NONBLOCK on fd. Returns the previous non-blocking
state so callers can restore it. Required before cooperatively reading
a shared fd (e.g. stdin) through the event loop.
fd_reader(
fd) ->reader
Wrap an arbitrary fd for cooperative reads on the event loop
Returns a reader for fd (e.g. stdin, fd 0) that integrates with the
event loop. :read(maxlen, opts) yields the current coroutine until at
least one byte is available, returning the bytes, or nil,"closed" on
EOF, or nil,"cancelled"/err.
A zero timeout reads without a wait: :read(maxlen, 0) returns the bytes
the fd holds, or nil,"timeout" when it holds none, and does not yield.
The fd must be in non-blocking mode (see set_nonblocking) and must be
epoll-able (a TTY or pipe, not a regular file). Only one coroutine may
wait on a given fd at a time.
read reports EOF only from a non-blocking fd. On a fd flipped to
blocking, a raw-mode tty (VMIN=0, VTIME>0) returns zero bytes on idle --
a phantom EOF -- so read re-asserts non-blocking and keeps reading. A
caller that flips the flag mid-read gets it flipped back.
run(
fn) ->result,err
Run the event loop with a main function
Creates an event loop, spawns fn as the main coroutine, and runs
the loop until all tasks complete. Returns the main task's results
or nil, err if the main task errored. The caller holds that raise:
the loop does not log it as an unawaited task error.
Returns nil, err when the loop cannot be made. Raises on a nested
lev.run(), and when fn is not a function; neither leaves a loop
behind.