Skip to main content

Crate turnloop

Crate turnloop 

Source
Expand description

Host-driven, completion-shaped I/O. No background thread turns the loop.

The host owns the thread and decides when to collect completions. Optional process-wide blocking, signal and external-wait services start only on use.

use std::time::Duration;
use turnloop::{Completions, Config, Loop, OpResult, Timeout, Token};
let mut driver = Loop::new(Config::default())?;
let deadline = driver.now() + Duration::from_millis(2);
let timer = driver.timer(deadline, None, Token(42))?;
let mut completions = Completions::default();
loop {
    driver.turn(Timeout::Until(deadline), &mut completions)?;
    if completions.iter().any(|c| c.token == Token(42) && matches!(c.result, OpResult::Timer)) {
        break;
    }
}
// Run host callbacks only after turn has returned.
driver.close(timer, Token(43))?;
driver.turn(Timeout::Now, &mut completions)?;
assert!(!driver.alive());

Blocking work declares how long it will hold its worker. Occupancy::Bounded is the fixed, queued, backpressured set that short CPU-bound jobs belong on; Occupancy::Long is a separately accounted, on-demand set for work that holds a thread for a connection’s lifetime. Neither class can exhaust the other, and pool_stats reports both without taking a lock.

Enable the executor feature for executor::LocalExecutor and futures-io adapters. Each loop/executor belongs to its creating thread; its notifier and poster may be cloned onto other threads.

Re-exports§

pub use backend::unix::Detached;

Modules§

backend
Internal platform contract, revision 2 (empty-wait instrumentation and native services).

Structs§

AcceptDefaults
Options a listener applies to every connection it accepts.
AccessMode
access(2) checks. All false tests existence only.
BufLease
Owns the buffer until explicitly dropped/released. May safely survive turns. Keeping all leases applies backpressure; it never allocates a new pool buffer.
BufferPool
Fixed reusable read storage; leases return buffers when explicitly released or dropped.
Cancellation
The cooperative stop signal of a running pool job.
ChildFd
One additional child descriptor beyond stdin, stdout and stderr.
Completion
One host-visible operation result, carrying its original routing token.
Completions
Fixed-capacity output. Each turn clears old completions and fills at most this capacity. Retained completions remain in the driver, providing backpressure.
Config
Fixed loop capacities and shared blocking-pool configuration.
DirEntries
Iterate (type, name) directory records from a FsResult::Directory page. Names are native bytes on Unix, WTF-8 on Windows and UTF-8 on WASI.
DnsRequest
Owned hostname and port for a pool-backed native address lookup.
Driver
A driver belongs to its constructing thread. Backend is an internal extension point used by platform lanes and the common contract suite.
Error
Portable error kind with an optional original operating-system code.
ExitStatus
Child termination status, preserving exit codes and signal termination.
FileMetadata
Metadata for Node Stats and watchFile snapshots. A field the platform does not report is None; values are never invented. Windows mode follows libuv’s attribute mapping: type bits plus 0o666, or 0o444 when read-only.
FileOptions
Open options covering Node’s string and numeric open flags.
FileTime
Wall-clock timestamp relative to the Unix epoch, with nanoseconds retained.
FsPath
A validated, prepared pathname. Preparing converts once; cloning never allocates.
Handle
Loop-scoped generational identity; stale or foreign IDs never address a reused resource.
Instant
A measurement of a monotonically nondecreasing clock. Opaque and useful only with Duration.
IoBuf
A stable, initialized, immutable byte region. Does not own the memory.
IoBufMut
A stable, exclusively writable region. Does not own the memory.
KeepAlive
TCP keep-alive probe schedule. Each None keeps the platform default.
ListenOpts
Listener backlog, kernel reuse-port configuration and accepted-socket defaults.
Metadata
Metadata result held in reusable per-loop storage; dereferences to FileMetadata. Dropping it returns the storage, so steady-state stat requests allocate nothing once the loop has served one. Copy the value out to keep it beyond the completion.
MulticastGroup
A multicast group and the local interface that should carry it.
Notifier
Thread-safe, cloneable wake endpoint using the loop parking handshake.
OpId
Loop-scoped generational identity; stale or foreign IDs never address a reused resource.
PipeName
Local IPC address: a filesystem socket path on Unix or named-pipe name on Windows. Unix callers own removal of the socket path after closing the listener.
PoolConfig
Configuration fixed by the first process-wide blocking-pool submission.
PoolStats
A snapshot of the process-wide pool, as it looked at some point during the call (issue #44).
PostError
Posting failure with ownership returned only when the payload was not accepted.
Poster
Bounded thread-safe payload queue routed to exactly one owning loop.
Process
Owned child identity and optional parent pipe handles, all belonging to one loop.
ProcessSpec
Child launch options. Arguments exclude argv[0], which is the program name. Environment entries override inherited values unless env_clear is true.
TcpOpts
Connect-time options for Loop::tcp_connect.
Token
Opaque host routing value, returned unchanged with its completions.
TurnInfo
Completed turn statistics and current reference-counted liveness.
UdpOpts
UDP binding options. Reuse is bind-time only and stays here, not in SocketOption; everything changeable on a live socket is an option.
WaitCondition
Shared host wait condition. Hosts may provide their own atomic storage and call notify after changing it. No predicate callback runs inside a loop turn.
WatchEvents
Iterate (kind, name) records of an OpResult::Watch batch, in native order. Names are relative to the watched directory using native separators; an event on the watched root (or a watched file) carries the root’s final component.
WatchOptions
Filesystem watch options.
WindowSize
Terminal dimensions in character cells.
WriteVectored
Up to MAX_IOV owned or provided segments stored inline.

Enums§

ChildFdSource
Child-side configuration of one extra descriptor.
ErrorKind
Portable error categories independent of native numeric error codes.
FileType
Native file type; also the record tag of directory entries.
FsRequest
One typed request, submitted with Loop::fs. Operations on the same handle run FIFO. A cancelled mutation that already started is not rolled back.
FsResult
Successful typed results. Failures use OpResult::Err.
FsTarget
A metadata operation’s subject: a path or an open handle.
Integration
The fd/event is borrowed from the driver; it must never be closed by the host.
Occupancy
How long a submitted job will hold the worker thread that runs it.
OpResult
Host-visible I/O, timer, process, service and lifecycle results.
Open
Backend-neutral resource creation requests; unsupported kinds must fail explicitly.
Payload
Common small posts need no box/allocation. Larger host results can own bytes or a Send Rust value; the driver never invokes a function from this payload.
ProcessStdio
Child-side standard-stream configuration.
RawTransport
The native identity of a transport, for host reporting and for a descriptor the host has taken ownership of (DESIGN §5a).
ReadBuf
Choose host-provided memory or an explicitly released pool lease for a read.
ReusePort
What a second bind of the same address is allowed to do.
Signal
Portable signal names. Unsupported mappings return an error.
SocketOption
A socket option that can be changed after the socket exists.
SocketOptionKind
Names a readable socket option for Loop::get_option.
Stdio
Standard stream to duplicate into a loop. Closing it does not close the host fd.
SymlinkKind
Windows symbolic-link flavour; ignored elsewhere.
TimeChange
Timestamp update for SetTimes.
Timeout
Exact timeout budget for one host-driven turn.
TtyMode
Terminal input/output mode, restored when the owning handle closes or drops.
WaitResult
Why an external wait completed.
WatchKind
Node fs.watch event type.
WriteBuf
Stable write data, either borrowed under an unsafe lifetime contract or owned.

Constants§

BACKEND_NAME
Backend selected from the compilation target, independently of Cargo features.
MAX_CHILD_FD
Highest child descriptor number an extra ChildFd may use.
MAX_IOV
Fixed upper bound keeps writev descriptors inline in the operation table.
RECORD_HEADER
Size of a record header: tag, reserved zero, little-endian u16 name length.

Functions§

pool_stats
Read the process-wide pool’s PoolStats. Never blocks and never fails; reports zeros before the first submission has started the pool.

Type Aliases§

BlockingResult
Result returned by a host blocking job.
Loop
The platform driver selected for the compilation target; owned by one agent.
Result
A fallible turnloop operation preserving portable and native error information.