Networking, WinterTC Web Platform & Async Event Loop Architecture
This document details Slice’s multi-worker HTTP/1.1 server (slice serve in crates/slice-cli/src/server/mod.rs), 3-level asynchronous concurrency model, outbound HTTPS/TLS 1.3 client (outbound_http.rs), deterministic time-travel event loop (event_loop.rs), RFC 6455 WebSocket engine (websocket.rs), raw TCP/TLS/UDP sockets (sockets.rs), and WinterTC + Node Core Tier-1 API surface.
1. Multi-Tenant slice serve & 3-Level Asynchronous Concurrency Architecture
Section titled “1. Multi-Tenant slice serve & 3-Level Asynchronous Concurrency Architecture”+---------------------------------------------------------------------------------------------------+| Slice (Nexus-JS) 3-Level Concurrency Architecture || || Level 1: Multi-Worker Shared-Nothing HTTP Server (`slice serve --workers=N`) || +-----------------------------+ +-----------------------------+ +---------------------------+ || | Worker Thread #0 | | Worker Thread #1 | | Worker Thread #N-1 | || | - Pre-allocated 64KB/4KB | | - Pre-allocated 64KB/4KB | | - Pre-allocated 64KB/4KB | || | - WarmBoaRealm (__slice_rc) | | - WarmBoaRealm (__slice_rc) | | - WarmBoaRealm | || | - In-place reset_for_request| | - In-place reset_for_request| | - In-place reset | || +--------------+--------------+ +--------------+--------------+ +-------------+-------------+ || | | | || Level 2: Per-Isolate Deterministic Event Loop (`crates/slice-engine/src/runtime/event_loop.rs`) || +--------------+--------------------------------+-------------------------------+-------------+ || | - Zero-Cost Sync Fast-Path (`ACTIVE_ASYNC_ITEMS == 0` -> 0.00 ns scheduler overhead) | || | - Priority Queue: Sync -> `process.nextTick` -> `Promise.then`/`queueMicrotask` | || | -> `setImmediate` -> `setTimeout`/`setInterval` Slab Timer Wheel | || | - Virtual Time-Warp (`--deterministic` / `slice test` warps timer deadlines in 0 ns) | || +--------------+--------------------------------+-------------------------------+-------------+ || | || Level 3: Background I/O & Compute Fan-Out Pools || +--------------+-----------------------------------------+------------------------------------+ || | - `Promise.all([fetch(...)])` Multiplexer -> `SHARED_OUTBOUND_CONN_POOL` (TLS 1.3 KeepAlive)| || | - `IDLE_WORKER_POOL` (`workers.rs`) -> Attenuated MicroVM `Worker` / `worker_threads` | || +---------------------------------------------------------------------------------------------+ |+---------------------------------------------------------------------------------------------------+- Zero-Allocation Stack HTTP/1.1 Parser & Vectorized Pipelined Flushing (
server/mod.rs&serve_connection_keep_alive):- Each worker thread in the
--workers=Nshared-nothing pool pre-allocates a reusable64 KBsocket read buffer (read_buf) and4 KBwrite buffer (write_buf). - Incoming HTTP/1.1 requests are scanned incrementally via
find_http_header_end_from(LazyLock<memmem::Finder>) with zero heapStringallocations, extracting up to 16 headers into a stack-allocated[(&str, &str); 16]array (headers_stack), while inboundContent-Length(<= 64 KiBstack slice or> 64 KiBheap buffer) andTransfer-Encoding: chunked(ChunkedBodyDecoder) payloads pass raw&[u8]directly intoHttpRequestContext::body_bytes(__slice_http_body_bytes) with zero UTF-8 coercion or binary corruption. - Non-pipelined and large static assets stream directly from the zero-copy
mmappayload slice without copying intowrite_buf, while pipelined HTTP/1.1 requests (has_more_pipelined) coalesce intowrite_buf(with automaticshrink_to(16 KB)after spikes above64 KB).
- Each worker thread in the
- In-Place Isolate Reset (
SliceIsolate::reset_for_request) & DirectJsObject::call:- Each worker resets its
SliceIsolatein place, rebinding itsHardwareProtectionDomain(WRPKRUregister switch on PKU-capable Linuxx86_64) and resetting CPU fuel and memory counters in nanoseconds. - On warm
SLICEBC\x01/SLICEBOAhits,WarmBoaRealm::loaded_bundlesstores the compiledboa_engine::JsObjectentrypoint function handle and invokesfn_obj.call(...)directly in Rust, completely bypassing JS source lexing andctx.eval.
- Each worker resets its
- WinterTC Request/Response, Static Assets (
ETag),Response.sse, & Post-ResponseSlice.waitUntil(fn):- Supports both
export default { async fetch(request, env, ctx) }andSlice.request()/Slice.respond(...). - In-memory static asset table serves
304 Not ModifiedBLAKE3ETaghits in< 2 us. - Deferred
ctx.waitUntil/Slice.waitUntilcallbacks are drained viadrain_wait_until_tasksafter the HTTP response bytes have been flushed to the client socket, while still charging CPU fuel to the tenant’s compartment budget.
- Supports both
2. Outbound HTTP/1.1 & HTTPS TLS 1.3 (outbound_http.rs)
Section titled “2. Outbound HTTP/1.1 & HTTPS TLS 1.3 (outbound_http.rs)”- Zero-Cost Lazy TLS 1.3 Engine (
get_tls_client_config): Usesrustls(v0.23,ringcrypto provider) and Mozilla’swebpki-rootswrapped in aOnceLock<Arc<rustls::ClientConfig>>with 256-session in-memory TLS 1.3 session ticket resumption, plus a BLAKE3-keyed custom-CArustls::ClientConfigcache (CUSTOM_TLS_CLIENT_CONFIGS) for--ca-cert/NODE_EXTRA_CA_CERTS. Pure-compute and HTTP workloads pay0 bytesof TLS root-store memory and0.00 nscold-start overhead. - Keep-Alive Connection Pool (
OUTBOUND_CONN_POOL&SHARED_OUTBOUND_CONN_POOL), Lock-Free 64 KB Thread-Local Read Staging (FETCH_READ_BUF), & O(N) HTTP/1.1 Framing (perform_single_hop_fetch): Caches warm TCP or TLS 1.3 connections partitioned by(tenant_id, scheme, host, port)(30sidle eviction), stages socket reads through lock-free boundedFetchSlabSlotGuardslots and thread-local64 KBbuffers, skips interim1xxinformational headers (100 Continue,103 Early Hints), and frames raw binaryVec<u8>bodies in linear $O(N)$ time viaContent-Lengthin-place reuse or incrementalChunkedBodyDecoderwithout waiting for TCP EOF, while enforcingMAX_OUTBOUND_HEADER_BYTES(64 KB),MAX_OUTBOUND_BODY_BYTES(16 MB), and RFC 9110tchar/CRLF header validation. - Zero-Trust Hop-by-Hop Redirect Guard (
execute_outbound_fetch_with_redirects): Re-evaluates OCap host allowlist, Pre-Connect DNS Resolved-IP SSRF, and Egress DLP on every301/302/303/307/308redirect hop (up to 5 hops), automatically stripsAuthorization,Cookie, andProxy-Authorizationheaders on cross-origin redirects, and supportsredirect: "follow" | "manual" | "error",res.redirected, andres.url.
3. Deterministic Time-Travel Event Loop (event_loop.rs)
Section titled “3. Deterministic Time-Travel Event Loop (event_loop.rs)”- Zero-Cost Synchronous Fast-Path (
ACTIVE_ASYNC_ITEMS): Synchronous scripts and synchronous HTTP handlers bypass the event loop scheduler completely (0.00 nsoverhead,4.0 KBper-tenant compartment footprint). - Slab Timer Wheel,
setImmediate, & Speculative On-DemandPromise.prototype.thenMicrotask Priority Hierarchy:- Enforces strict Node.js / WinterTC priority ordering (
sync -> process.nextTick -> Promise.then / queueMicrotask -> setImmediate -> setTimeout(0)), fires macrotask timers in deterministic(deadline_ms, !is_immediate, id)order with live cancellation/deadline re-verification before each callback, drainsnextTickand microtasks after every macrotask turn, and enforcesMAX_ACTIVE_TIMERS = 1024andMAX_EVENT_LOOP_TICKS = 4096(SandboxViolation::CpuFuelExhausted). - By default,
Promise.prototype.thenremains bound directly toBoa’s native Rust implementation (__origThen) with zero JS closure allocation overhead perawait/.then(), and is only wrapped via__slice_set_next_tick_hook(true)when a script references or invokesprocess.nextTick.
- Enforces strict Node.js / WinterTC priority ordering (
- Virtual Time-Warp (
virtual_time_warped_ms): WhenBOA_DET_STATEis active (--deterministicorslice test) and no live network sockets are in flight, the event loop warps the deterministic clock directly to the next timer’sdeadline_msin0 nswithout callingstd::thread::sleep, executing 66-second exponential backoff test suites in< 50 ms. - Concurrent
Promise.all([fetch(...), ...])Fan-Out via BoundedFetchReactorPool(MAX_FETCH_REACTOR_WORKERS = 16) &AbortSignal.timeout(ms): Executes single un-racedfetch()calls inline on the isolate thread, and dispatches concurrentPromise.all([fetch(...), ...])batches onto a lazily-initialized, boundedFetchReactorPool(OnceLock<Arc<FetchReactorPool>>, up to 16 reusable worker threads sharingSHARED_OUTBOUND_CONN_POOLandslice-io::RegisteredBufferPool64 KB slabs) while racing timer deadlines (AbortController,AbortSignal.abort(),AbortSignal.timeout(ms)).
4. RFC 6455 WebSocket Engine (websocket.rs) & 5-Ring Raw TCP/TLS/UDP Sockets (sockets.rs)
Section titled “4. RFC 6455 WebSocket Engine (websocket.rs) & 5-Ring Raw TCP/TLS/UDP Sockets (sockets.rs)”- RFC 6455 WebSockets (
crates/slice-engine/src/net/websocket.rs):- Zero-dependency RFC 6455 engine (
compute_websocket_accept_key, 4-byteu32XOR maskingapply_websocket_mask_in_place,encode_websocket_frame,decode_websocket_frame,read_websocket_message_from_streamwith fragmented continuation reassembly and automaticPing/Pongheartbeats, clientws:///wss://sessions, server101 Switching Protocolsupgrade viaSlice.upgradeWebSocket,Slice.mockWebSocket, and per-frame Outbound Egress Secret DLP).
- Zero-dependency RFC 6455 engine (
- Zero-Trust OCap TCP/TLS/UDP Sockets (
crates/slice-engine/src/net/sockets.rs):- Powers WinterTC
Slice.connect/import { connect } from "cloudflare:sockets",node:net,node:tls(includingstartTls()), andnode:dgramunder all 5 security rings (NetCap, Pre-Connect DNS SSRF, Egress Secret DLP, CPU Fuel, and Memory Cage), plus deterministicSlice.mockSocket/Slice.mockUdpSocket.
- Powers WinterTC
5. WinterTC Minimum Common Web Platform API & Uint8Array-Backed Buffer + Node Core Tier-1
Section titled “5. WinterTC Minimum Common Web Platform API & Uint8Array-Backed Buffer + Node Core Tier-1”- WinterTC Web Platform API (
crates/slice-engine/src/preludes/js_preludes.rs):URL(__FastUrl/FastUrlProto1-hop zero-parse HTTP(S) fast path acrossnew URL(input)andnew URL(input, base)with strict WHATWG invalid-baseTypeErrorparity, unifiedURL.prototypecomponent accessors + read-onlyorigin+[SameObject]searchParamssynchronization,canParse),URLPattern(CreateDataPropertygroups),URLSearchParams(zero-_ensureP()get/getAll/hasraw query scans, inline insertionsort, &%IteratorPrototype%Web IDL pair iterators),Headers(RFC 9110tchar+ inlinecharCodeAtCTL validation,for..inmap initialization,getSetCookie, & sorted uncombinedSet-Cookie%IteratorPrototype%pair iterators),Request(__FastReq1-hopRequest.prototypefast path for both string andURLinputs),Response(__FastRes1-hopResponse.prototypefast path with iterable/Mapheader fallback,200..=599status validation, eagerResponse.jsonvalidation/serialization, single authoritativeHeadersContent-Type, lossless binary_u8bodies, single-pass closed-streamResponse.text()/json()/bytes()/arrayBuffer()draining over_closed || _closeRequestedReadableStreambodies, WHATWGBodysingle-use disturbance/lock tracking,Response.sse),fetch,EventSource,TextEncoder(encode,encodeIntowith WHATWGU+FFFDsurrogate replacement),TextDecoder(utf-8streaming{ stream: true },ascii,iso-8859-1,fatal: true),btoa/atob(InvalidCharacterErrorDOMException),crypto.randomUUID,crypto.getRandomValues,crypto.subtle(SHA-1/256/384/512,HMAC,AES-GCMwith32..=128-bit tags /AES-CBC,Ed25519,ECDSA,RSASSA-PKCS1-v1_5/RSA-PSS,X25519,PBKDF2/HKDF,timingSafeEqual, JWK/PKCS#8/SPKI/raw),DOMException,Event,CustomEvent,EventTarget(capture-aware deduplication + live removed-listener flag),AbortController,AbortSignal(subclass ofEventTarget,timeout,any,abort),Blob(W3C File API printable-ASCIItypesanitization),File,FormData(%IteratorPrototype%pair iterators, 128-bit collision-free CSPRNG/deterministic multipart boundaries, native Rustmemchr::memmem::FinderSIMD RFC 7578 binary multipart parser__slice_multipart_parse+application/x-www-form-urlencoded),structuredClone(CreateDataPropertyown properties,Map-memoized sharedArrayBuffer&SharedArrayBufferidentity, resizableArrayBuffer&autolength-tracking views, array string expandos,{ transfer }resizability,DataCloneError),ReadableStream(sync-closed/pull-free zero-microtask start fast path, WHATWG asyncpullstate machine,reader.closed,tee, bidirectionalpipeTo/pipeThroughwithAbortSignal, pull-on-demandReadableStream.fromwithiterator.returnclosing),WritableStream,TransformStream,TextEncoderStream,TextDecoderStream,CompressionStream,DecompressionStream,Intl(DateTimeFormat,NumberFormat,Collator,PluralRules,Segmenter),navigator,location, andWebAssembly(shared per-isolatewasmi::Store, liveMemory/Global/Table,ResetMemoryBufferdetachment, post-trap memory sync, andToBigInt64). - Real
Uint8Array-BackedBuffer(Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)): TrueUint8Arraysubclass (b instanceof Uint8Array === true,Buffer.isBuffer(b) === true) withDataView-accelerated wire-protocol integer readers/writers (readUInt8/16/32BE/LE,readBigUInt64BE/LE,writeUInt8/16/32BE/LE,writeBigUInt64BE/LE). - Lazy IIFE-Isolated
node:*Core Modules (crates/slice-engine/src/preludes/node_builtins.rs):node:events,node:path(posix/win32),node:crypto,node:fs&node:fs/promises,node:util&node:util/types,node:assert/node:assert/strict,node:timers&node:timers/promises,node:os,node:url,node:buffer,node:stream&node:stream/web,node:http&node:https,node:zlib,node:async_hooks,node:string_decoder,node:querystring,node:net,node:tls,node:dgram,node:dns,node:vm,node:child_process, andnode:worker_threads.