Async I/O & Readiness Reactor Guide
Veko delivers high-concurrency, non-blocking network I/O without colored async/await functions, garbage collection, or external C runtimes. Instead of transforming every function into a hidden heap state machine, Veko pairs its single-owner ORO memory model and shared-nothing spawn workers with an OS-native Readiness Reactor (lib/reactor.vk) and non-blocking socket primitives (lib/io/net.vk, lib/web.vk, lib/net/client.vk, lib/net/websocket.vk).
1. Architecture & OS Backends
OS-Native Readiness Reactor, Timer Wheel & Multiplexed HTTP Engine
Single-threaded readiness multiplexing over epoll, kqueue, IOCP+WSAPoll, and WASI net-poll without async/await coloring.
Every reactor operation is gated behind the .net capability (allow-caps = [.net] in veko.vk) and compiles to the native kernel readiness primitive of each target:
| Target Platform | Underlying Kernel / Sandbox Mechanism | Cross-Thread Wakeup (reactor/wake-handle) |
|---|---|---|
Linux x86_64 (--target=linux-x64) |
epoll_create1 / epoll_ctl / epoll_pwait (zero-libc syscalls) |
eventfd2 (EFD_NONBLOCK | EFD_CLOEXEC) |
Linux arm64 (--target=linux-arm64) |
epoll_create1 / epoll_ctl / epoll_pwait (zero-libc syscalls) |
eventfd2 (EFD_NONBLOCK | EFD_CLOEXEC) |
macOS Apple Silicon (--target=macos-arm64) |
kqueue / kevent (EVFILT_READ, EVFILT_WRITE) |
EVFILT_USER (NOTE_TRIGGER) |
Windows x64 & ARM64 (--target=win-x64 / --target=win-arm64) |
Win32 IOCP (CreateIoCompletionPort / GetQueuedCompletionStatus) + WSAPoll |
PostQueuedCompletionStatus + loopback UDP wake |
64-bit VKO VM (--vm) |
Delegates directly to host OS native reactor | Host OS native wakeup |
Wasm 3.0 Sandbox (--wasm) |
wasi:sockets@0.3.0 net-poll + wasi:clocks@0.3.0 |
In-sandbox wake flag |
2. Core Low-Level Builtins (net/poll-* & net/try-*)
All 11 non-blocking reactor builtins require the .net capability and preserve the .secret firewall (net/try-write rejects .secret buffers both statically and at runtime):
| Builtin | Arity | Return | Description |
|---|---|---|---|
net/poll-new |
0 |
i64 |
Allocates a new OS readiness poller handle. |
net/poll-ctl |
5 |
enum |
(poller, op, fd, events, token) — op: 1=ADD, 2=MOD, 3=DEL; events: 1=READ, 2=WRITE. |
net/poll-wait |
2 |
block |
(poller, timeout_dur) — returns a block of [token mask] pairs (1=READ, 2=WRITE, 4=ERR, 8=HUP). |
net/poll-wake |
1 |
enum |
(poller) — thread-safe wakeup of a thread blocked in net/poll-wait. |
net/poll-close |
1 |
enum |
(poller) — closes OS poller handles and releases internal slabs (idempotent). |
net/set-nonblock |
2 |
enum |
(sock, enabled bool) — toggles O_NONBLOCK / FIONBIO. |
net/connect-tcp/nonblock |
2 |
i64 |
(host, port) — initiates non-blocking TCP connect (EINPROGRESS / WSAEWOULDBLOCK succeeds). |
net/sock-error |
1 |
i64 |
(sock) — queries SO_ERROR via getsockopt (0 = connected/healthy). |
net/try-accept |
1 |
i64 |
(listener) — returns client socket >= 0, -1 if would-block, or err. |
net/try-read-into |
3 |
i64 |
(sock, mut buf, max_n) — appends up to max_n bytes into mut buf; returns > 0 bytes read, 0 on EOF, -1 if would-block, or err. |
net/try-write |
2 |
i64 |
(sock, data) — writes without blocking; returns >= 0 bytes sent, -1 if would-block, or err (blocks .secret). |
3. Using lib/reactor.vk (Event Loop, Timers & Cross-Thread Wakeup)
lib/reactor.vk provides both pull-mode polling (idiomatic when mutating local single-owner connection tables with zero closure capture limits) and callback-mode dispatching (reactor/register-cb, reactor/after-cb, reactor/tick, reactor/run).
Timers & Cross-Thread spawn Wakeup
Because spawn workers are shared-nothing and cannot capture mut r, call reactor/waker r to extract a copyable i64 waker handle and pass it to any worker thread:
use [reactor]
mut r = reactor/new
defer [ _ = reactor/close mut r ]
w = reactor/waker r
tid = reactor/after mut r 25ms
worker = spawn [
time/sleep 5ms
_ = reactor/wake-handle w
.done
]
// Wakes early (~5ms) instead of sleeping for 2s
evs = reactor/poll mut r 2s
_ = task/await worker
// Poll until timer #tid fires
mut fired = false
while not fired [
_ = reactor/poll mut r 25ms
due = reactor/due-timers mut r
mut i = 0
while i < (len due) [
if due[i] == tid [ fired = true ]
i = i + 1
]
]
Pull-Mode Readiness Helpers
reactor/EV-READ(1),reactor/EV-WRITE(2),reactor/EV-ERR(4),reactor/EV-HUP(8),reactor/EV-RW(3)reactor/readable? ev,reactor/writable? ev,reactor/errored? ev,reactor/closed? evreactor/register mut r fd events->tokenreactor/modify mut r token events->.okreactor/unregister mut r token->.okreactor/after mut r delay/reactor/every mut r interval/reactor/cancel-timer mut r tid
4. Non-Blocking HTTP/1.1 Server (web/serve-reactor & web/serve-async)
lib/web.vk includes a single-threaded, reactor-driven HTTP/1.1 server that multiplexes many concurrent connections over one OS thread. Slow or stalled clients (such as a peer pausing mid-header) never block other requests, and per-connection idle timeouts plus header/body size limits protect server memory automatically:
use [web]
mut app = web/new-app
web/use-security-headers mut app
web/get mut app '/health' fn [req web/Request] web/Response [
web/json-resp 200 { status = 'ok', path = req.path }
]
ln = net/listen-tcp .ip '127.0.0.1:8080'
opts = web/AsyncServerOpts {
max_requests = 0 // 0 = serve indefinitely
read_timeout = 10s
tick_timeout = 25ms
max_header_bytes = 65536
max_body_bytes = 4194304
}
_ = web/serve-reactor ln app opts
For quick tests or bounded batch runs, use the convenience wrapper web/serve-async ln app 100.
5. Concurrent Non-Blocking HTTP/1.1 Client (net/client/request-batch & get-many)
lib/net/client.vk can fan out dozens of HTTP/1.1 requests simultaneously on a single reactor thread with per-request deadlines and transparent gzip/deflate decompression:
use [hc = net/client]
reqs = [
(hc/AsyncRequest { method = 'GET', url = 'http://127.0.0.1:8080/items/1', timeout = 5s })
(hc/AsyncRequest { method = 'GET', url = 'http://127.0.0.1:8080/items/2', timeout = 5s })
(hc/AsyncRequest { method = 'POST', url = 'http://127.0.0.1:8080/echo', body = (bytes/from-str 'ping'), timeout = 5s })
]
resps = hc/request-batch reqs
// resps[i] is either an `hc/HttpResponse` or `err` in matching input order
For parallel GET fan-out with shared options, use hc/get-many ['http://...' 'http://...'] (hc/RequestOpts { timeout = 5s }).
6. Non-Blocking Sockets (lib/io/net.vk) & Incremental WebSockets (lib/net/websocket.vk)
lib/io/net.vk:inet/listen-nonblock addr— binds TCP listener and enables non-blocking modeinet/dial-tcp-nonblock host port— starts non-blocking TCP connectinet/set-nonblock sock enabled/inet/sock-error sockinet/try-accept ln/inet/try-read-into sock mut buf max_n/inet/try-write sock data/inet/try-write-from sock data offset
lib/net/websocket.vk:ws/try-decode-frame raw— incrementally parses RFC 6455 frames from a non-blocking receive buffer, returningFrameTry { complete = false, ... }until a full frame has arrived.
7. Running the Full End-to-End Example
See examples/29_async_reactor_http_server_and_client.vk for a complete demonstration covering cross-thread wakeups, timers, slow-client isolation, 4-way concurrent HTTP batching, secret firewall checks, and incremental WebSocket framing:
# Run on 64-bit VKO VM
veko run --vm --allow-net --allow-listen --allow-private-net examples/29_async_reactor_http_server_and_client.vk
# Compile & run natively (Win64 IOCP+WSAPoll or Linux epoll+eventfd2)
veko compile --native examples/29_async_reactor_http_server_and_client.vk -o dist/ex29.exe
./dist/ex29.exe
# Cross-compile for Windows ARM64, Linux x86_64, Linux arm64, or macOS Apple Silicon
veko compile --native --target=win-arm64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-win-arm64.exe
veko compile --native --target=linux-x64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-linux-x64
veko compile --native --target=linux-arm64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-linux-arm64
veko compile --native --target=macos-arm64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-macos-arm64