veko-lang.org
Download Free EPUB 3.0

Part II · Standard Library, PQC, Networking, Async, Durable State & Desktop UI

Chapter 9

Non-Blocking Async I/O, Structured Scope & the Readiness Reactor

Multiplexing sockets over epoll, kqueue, IOCP+WSAPoll, WASI net-poll, and conc/scope without colored async functions

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

NON-BLOCKING ASYNC I/O

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.

OS KERNEL READINESS POLLERS 11 net/poll-* & net/try-* PAL ops LIB/REACTOR.VK EVENT LOOP Sockets + Min-Heap Timers + Waker HIGH-CONCURRENCY CONSUMERS Server & Batch Client Ready tokens .would_block Next deadline Accept / Read / Write Parallel sockets Kernel PALOS Kernel Poller Backendsepoll / kqueue / IOCP+WSAPoll Zero-Alloc I/ONon-Blocking Socket Opstry-accept / try-read-into / try-write Event LoopReactor Loop & Dispatchregister / modify / step / run SchedulingMin-Heap Timers & Wakerafter / every + poll-wake Async Serverweb/serve-reactorKeep-Alive HTTP Multiplexer Async Clientnet/client/request-batchParallel Outbound Fan-Out
Component & ModuleArchitectural Role
OS Kernel Poller Backends
native_pal4.vk + arm64_pal2.vk
Maps net/poll-new, net/poll-ctl, and net/poll-wait directly to each OS's readiness facility.
Non-Blocking Socket Ops
lib/io/net.vk
Returns .would_block cleanly instead of blocking the OS thread when buffers aren't ready.
Reactor Loop & Dispatch
lib/reactor.vk
Multiplexes READABLE and WRITABLE readiness tokens alongside scheduled deadlines.
Min-Heap Timers & Waker
lib/reactor.vk
Combines O(log n) monotonic timers with cross-thread spawn wakeup notifications.
web/serve-reactor
lib/web.vk
Serves concurrent HTTP/1.1 keep-alive connections and slow clients on a single reactor.
net/client/request-batch
lib/net/client.vk
Executes dozens of concurrent HTTP requests in parallel over one readiness reactor.

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 PlatformUnderlying Kernel / Sandbox MechanismCross-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) + WSAPollPostQueuedCompletionStatus + loopback UDP wake
64-bit VKO VM (--vm)Delegates directly to host OS native reactorHost OS native wakeup
Wasm 3.0 Sandbox (--wasm)wasi:sockets@0.3.0 net-poll + wasi:clocks@0.3.0In-sandbox wake flag

Why Readiness (not pinned overlapped buffers)? Readiness notifications keep Veko's single-owner ORO memory model 100% safe: no user bytes slab is ever pinned across a kernel asynchronous lifetime, eliminating cancellation use-after-free bugs on Windows and POSIX alike.


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):

BuiltinArityReturnDescription
net/poll-new0i64Allocates a new OS readiness poller handle.
net/poll-ctl5enum(poller, op, fd, events, token) — op: 1=ADD, 2=MOD, 3=DEL; events: 1=READ, 2=WRITE.
net/poll-wait2block(poller, timeout_dur) — returns a block of [token mask] pairs (1=READ, 2=WRITE, 4=ERR, 8=HUP).
net/poll-wake1enum(poller) — thread-safe wakeup of a thread blocked in net/poll-wait.
net/poll-close1enum(poller) — closes OS poller handles and releases internal slabs (idempotent).
net/set-nonblock2enum(sock, enabled bool) — toggles O_NONBLOCK / FIONBIO.
net/connect-tcp/nonblock2i64(host, port) — initiates non-blocking TCP connect (EINPROGRESS / WSAEWOULDBLOCK succeeds).
net/sock-error1i64(sock) — queries SO_ERROR via getsockopt (0 = connected/healthy).
net/try-accept1i64(listener) — returns client socket >= 0, -1 if would-block, or err.
net/try-read-into3i64(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-write2i64(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:

VEKO
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? ev
  • reactor/register mut r fd events -> token
  • reactor/modify mut r token events -> .ok
  • reactor/unregister mut r token -> .ok
  • reactor/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:

VEKO
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:

VEKO
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 mode
    • inet/dial-tcp-nonblock host port — starts non-blocking TCP connect
    • inet/set-nonblock sock enabled / inet/sock-error sock
    • inet/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, returning FrameTry { 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:

POWERSHELL
# 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