Skip to main content

turnloop/backend/
mod.rs

1//! Internal platform contract, revision 2 (empty-wait instrumentation and native services).
2//!
3//! Public only so the contract runner and independently developed backends can use
4//! it; not a stable end-user extension API. All identifiers and buffers are core
5//! types. No raw fd, OVERLAPPED pointer, pollable or browser object crosses here,
6//! with one deliberate exception: `raw_transport` reports a `RawTransport` the core
7//! passes straight through to the host and never acts on (§5a handle transfer).
8//! Ownership still leaves through `detach`/`Detached`, never through that value.
9//!
10//! # Ownership and completion rules (D1–D4)
11//!
12//! * `open`/`attach` bind a resource to the supplied generational Handle. On error
13//!   they retain nothing. Open::Tcp creates an unconnected resource; the Connect
14//!   request performs the connection. Once validated/accepted, even a synchronous
15//!   I/O error is queued as a terminal Event. Submit errors reject before acceptance
16//!   (unsupported/invalid operation, capacity/resource setup failure).
17//!   `submit` accepts ownership of a Request only on Ok; on
18//!   Err it must have stopped all access to its buffers before returning.
19//! * Every accepted Request yields one terminal Event, including cancellation and
20//!   errors. Multishot accepts/reads may yield preceding nonterminal Events. Their
21//!   terminal Event acknowledges that buffers and native op storage are quiescent.
22//! * Native completions carry the **full OpId**, never a token or a reusable index
23//!   alone. Delayed kernel events must not complete a later generation. IOCP must
24//!   keep OVERLAPPED storage pinned until the final kernel acknowledgement.
25//! * `cancel` initiates cancellation, never frees native buffers prematurely. It
26//!   must eventually emit a terminal event even when cancel races with success.
27//!   The core arbitrates the result and emits Cancelled if cancellation won.
28//! * `prepare_close` starts nonblocking teardown before cancellation. Process
29//!   backends terminate the owned child and retain its exit operation until reaped,
30//!   including when cancellation is already pending. Other resources need no hook.
31//! * The core calls `release` only after every associated operation terminated
32//!   and the Closed completion was appended to host output. Drop must synchronously
33//!   quiesce any remaining I/O before freeing buffers (native completion draining
34//!   may be necessary). The driver never invokes user callbacks.
35//!
36//! # Turn and boundedness (D5–D7)
37//!
38//! * `poll` appends at most `events.capacity() - events.len()` Events; never grows
39//!   the vector. A full buffer retains work for the next turn, without losing an
40//!   edge. At most one OS wait is allowed (DESIGN §10 rule 3). Queued work
41//!   prohibits blocking waits: the driver passes a zero timeout, and calls poll
42//!   for that one discovery poll only with native operations pending and native
43//!   output reserve. With no native operation pending, the driver skips poll for
44//!   queued work, whatever `has_work` reports (web, whose poll never
45//!   enters the OS, keeps draining cached host work). `None` means an unbounded
46//!   wait. Durations must retain sub-millisecond precision.
47//! * `Budget::accepts` bounds the connections multishot accepts deliver in one
48//!   poll: nonterminal `Accepted`/`PipeAccepted` events (turnloop#77). It is the
49//!   number of handles the core can still house for them, so each one past it
50//!   would be accepted from the kernel and then destroyed. It throttles only
51//!   those operations: every other source, single-shot accepts included, fills
52//!   the vector exactly as before (DESIGN §10 rule 3 fairness). A multishot
53//!   accept held back by it takes nothing further from the kernel (a readiness
54//!   backend leaves the connection in the listener's backlog; a completion
55//!   backend does not re-arm, and keeps an already completed one in its
56//!   operation storage), and is neither runnable work for `has_work` nor a
57//!   reason to end the wait early (rule 4a): the operation is resumed by the
58//!   first poll whose budget is positive again.
59//! * Readiness backends execute I/O in poll, cache readiness until EAGAIN, and
60//!   requeue partially processed work fairly. Completion backends drain native
61//!   completions. WASI 0.2 polls pollables; 0.3 drives a waitable set; web drains
62//!   callback results and rejects blocking waits on the main thread.
63//! * EINTR ends this poll early; it must not restart the timeout. `PollInfo.waits`
64//!   counts positive-timeout/infinite waits; `discovery_polls` counts zero-time
65//!   native polls. Their sum is at most one. `zero_event_waits`
66//!   counts raw empty calls across both counters, including EINTR.
67//!   Private timeout events count as zero-event waits, just like a timed OS wait
68//!   returning zero; never infer this from user completions. Every backend that
69//!   implements its timeout with a private wakeup source normalizes it: epoll's
70//!   timerfd, the IOCP deadline packet, the WASI 0.2 deadline pollable and the
71//!   WASI 0.3 deadline subtask. Real I/O or notifier events arriving in the same
72//!   call still make it non-empty.
73//! * Cached readiness ending in EAGAIN with no completion must retain the original
74//!   timeout for the one permitted OS wait. It must not force a zero-timeout turn.
75//! * `has_work` covers queued completions and cached runnable I/O. `wake` is called
76//!   only after the notifier observed PARKED. It must be safe after loop drop:
77//!   the wake object owns its native resource or detects closure, never uses a
78//!   possibly reused raw handle. Errors cannot silently lose a wake.
79//! * `integration` opts into external waiting. The core then leaves its notifier
80//!   PARKED between turns; hosts call it again only while preparing external waits.
81//!   This reconciles a readable integration fd with zero syscalls while RUNNING.
82//!
83//! # Transfer and platform constraints (§5a, §7)
84//!
85//! * `detach` is called only when all operations are quiescent. It unregisters the
86//!   source loop before returning an owning Send transport. `attach` re-registers
87//!   on the destination. Unsupported resources return Unsupported. For asynchronous
88//!   cancellation, public detach can return WouldBlock while cancellation drains;
89//!   the caller turns the source loop and retries. No blocking wait is hidden here.
90//! * `Detached` may be an enum, not an integer: IOCP socket migration may require
91//!   duplication; WASI/browser objects need not support transfer. `Resource` is
92//!   intentionally absent: each backend owns its native tables keyed by Handle.
93//! * A `Detached` is also how a descriptor leaves turnloop for good: the platform
94//!   types expose `into_fd`/`into_socket`/`into_handle`, which restore whatever
95//!   the backend changed on adoption (status flags, terminal or console mode) and
96//!   then release ownership. Because `detach` already proved quiescence, the loop
97//!   has no operation, buffer or registration left for that transport.
98//! * `Wake` is Send + Sync on every target, but single-thread WASI/web may implement
99//!   it as a flag/host scheduler token. No backend creates a loop-driving thread.
100//!   Windows' explicitly requested Integration::Event helper is the D7 exception.
101//! * Unsupported platforms/capabilities return errors; no fake successful I/O.
102//!
103//! # Socket options (§7.7)
104//!
105//! * `set_option`/`get_option` are synchronous and produce no Event. They run
106//!   entirely inside the call, touch no operation storage, and must not allocate.
107//! * A backend reports `Unsupported` for an option its platform lacks. It must
108//!   never accept and ignore one: a host reads a lie back from `get_option`, and
109//!   "the option is on" is a security- and latency-relevant claim.
110//! * `ListenOpts::accept_defaults` is applied by the accepting backend to each
111//!   accepted transport before its `Accepted`/`PipeAccepted` Outcome is produced,
112//!   so the core hands the host an already-configured connection. A backend that
113//!   cannot apply a requested default rejects the listener in `open`.
114//!
115//! # Filesystem (§7.6 Files)
116//!
117//! * `FILESYSTEM` selects where typed `FsRequest`s run. `Pool` (native default):
118//!   the core runs them on the shared blocking pool and never calls the backend.
119//!   `Backend` (WASI): `fs` accepts them under the ordinary Request rules, with a
120//!   FIFO per handle, and yields `Outcome::Fs`. A request that opens binds its
121//!   native object to the supplied new handle only on success; after a failed or
122//!   cancelled open the core calls `release` for that never-visible handle.
123//! * `fs_watch` binds a native watch to a new handle; the core then submits one
124//!   multishot `Operation::WatchFs`. Each nonterminal `Outcome::Watch` carries a
125//!   pooled lease of records (see `WatchEvents`). Pool exhaustion retains events
126//!   in bounded per-watch storage; lost events set `overflow`. No backend thread
127//!   is created: native watch sources are registered with the loop's own wait,
128//!   except where the OS delivers on its own threads (FSEvents dispatch queues).
129pub use crate::fs::FsOutput;
130use crate::{
131    BufLease, BufferPool, Config, Error, Handle, Integration, OpId, Open, ReadBuf, Result,
132    WriteBuf, WriteVectored,
133};
134use std::{net::SocketAddr, sync::Arc, time::Duration};
135
136/// Only the notifier calls this method; implementations should expose syscall
137/// counts here, counting attempts (including failures), not guessed notifications.
138pub trait Wake: Send + Sync + 'static {
139    /// Wake the native wait primitive; the notifier calls this only after observing PARKED.
140    fn wake(&self) -> Result<()>;
141    /// Return the number of native wake syscall attempts, including failures.
142    fn syscall_count(&self) -> u64;
143}
144
145#[derive(Debug)]
146/// One accepted backend operation, keyed by a full generational operation ID.
147pub struct Request {
148    /// Full generational operation identity, including its owning loop.
149    pub op: OpId,
150    /// Resource identity belonging to the submitting or receiving loop.
151    pub handle: Handle,
152    /// Requested operation and any memory it retains.
153    pub operation: Operation,
154}
155#[derive(Debug)]
156/// Backend requests with completion-shaped ownership and cancellation semantics.
157pub enum Operation {
158    /// Observe this process until its exit has been reaped.
159    ProcessExit,
160    /// Multishot subscription to this signal resource.
161    WatchSignal,
162    /// Duplicate a transport into the receiving process. The backend retains an
163    /// independent native reference until its send completes or is cancelled.
164    SendHandle(Handle),
165    /// Receive one transport over a local IPC stream.
166    RecvHandle,
167    /// Establish the connection configured when the stream was opened.
168    Connect,
169    /// Accept one or repeatedly accept incoming stream connections.
170    Accept {
171        /// Continue producing nonterminal results until stopped, cancelled, EOF or error.
172        multishot: bool,
173    },
174    /// Read bytes, with a byte count and optional pooled lease in the completion.
175    Read {
176        /// The owned/provided buffer for this operation.
177        buf: ReadBuf,
178        /// Continue producing nonterminal results until stopped, cancelled, EOF or error.
179        multishot: bool,
180    },
181    /// Write the complete supplied byte buffer, permitting native partial writes internally.
182    Write(WriteBuf),
183    /// Write all inline segments in order.
184    Writev(WriteVectored),
185    /// Send one UDP datagram to the specified destination.
186    SendTo {
187        /// The owned/provided buffer for this operation.
188        buf: WriteBuf,
189        /// Destination UDP endpoint.
190        to: SocketAddr,
191    },
192    /// Receive one UDP datagram and report its source address.
193    RecvFrom(ReadBuf),
194    /// Complete a stream write-side shutdown after preceding queued writes.
195    Shutdown,
196    /// Multishot delivery of the filesystem watch bound by `Backend::fs_watch`.
197    WatchFs,
198}
199#[derive(Debug)]
200/// Backend completion awaiting translation into a host-visible completion.
201pub struct Event<D> {
202    /// Full generational operation identity, including its owning loop.
203    pub op: OpId,
204    /// True once this operation will produce no further results or native buffer accesses.
205    pub terminal: bool,
206    /// The operation outcome or its original error.
207    pub result: std::result::Result<Outcome<D>, Error>,
208}
209#[derive(Debug)]
210/// Successful backend outcomes; accepted transports remain owned until attached.
211pub enum Outcome<D> {
212    /// Addresses from an asynchronous host resolver.
213    Resolved(Vec<SocketAddr>),
214    /// Reaped child termination.
215    Exited(crate::ExitStatus),
216    /// Coalesced signal delivery.
217    Signal(crate::Signal),
218    /// Accepted local connection (has no IP peer address).
219    PipeAccepted(D),
220    /// Received independent transport ownership.
221    HandleReceived(D),
222    /// One transport was passed successfully.
223    HandleSent,
224    /// The connection is established and ready for stream operations.
225    Connected,
226    /// An incoming TCP connection with its peer address.
227    Accepted {
228        /// Exclusive ownership of an unregistered accepted resource.
229        transport: D,
230        /// Remote TCP peer endpoint.
231        peer: SocketAddr,
232    },
233    /// Read bytes, with a byte count and optional pooled lease in the completion.
234    Read {
235        /// Number of bytes transferred by this completion.
236        n: usize,
237        /// Owned pooled read bytes, present only when a pooled buffer was used.
238        lease: Option<BufLease>,
239    },
240    /// The peer or file reached the end of its readable stream.
241    Eof,
242    /// Number of bytes successfully written.
243    Wrote(usize),
244    /// Receive one UDP datagram and report its source address.
245    RecvFrom {
246        /// Number of bytes transferred by this completion.
247        n: usize,
248        /// Source endpoint of the received datagram.
249        from: SocketAddr,
250        /// Owned pooled read bytes, present only when a pooled buffer was used.
251        lease: Option<BufLease>,
252    },
253    /// Complete a stream write-side shutdown after preceding queued writes.
254    Shutdown,
255    /// A batch of filesystem watch records.
256    Watch {
257        /// Initialized `WatchEvents` records.
258        events: BufLease,
259        /// Native events were lost before this batch; rescan the watched scope.
260        overflow: bool,
261    },
262    /// A typed filesystem result from a `Filesystem::Backend` backend.
263    Fs {
264        /// The typed result; `Opened` refers to the request's new handle.
265        output: FsOutput,
266        /// The pooled lease holding result bytes, when one was requested.
267        lease: Option<BufLease>,
268    },
269    /// The operation was cancelled and its native buffer access has ended.
270    Cancelled,
271}
272#[derive(Clone, Copy, Debug, Eq, PartialEq)]
273/// Where typed filesystem requests execute (see the module documentation).
274pub enum Filesystem {
275    /// The core runs them on the shared native blocking pool.
276    Pool,
277    /// The backend accepts them through `Backend::fs`.
278    Backend,
279    /// No filesystem: `Loop::fs` returns Unsupported.
280    Unsupported,
281}
282#[derive(Clone, Copy, Debug, Eq, PartialEq)]
283/// What the core can house from one `poll` (see the module documentation).
284pub struct Budget {
285    /// Connections multishot accepts may deliver in this poll: the handle
286    /// slots the core holds for them, which each such event spends.
287    pub accepts: usize,
288}
289impl Budget {
290    /// No limit on any source. For backend-level tests that bypass the core.
291    pub const UNLIMITED: Self = Self {
292        accepts: usize::MAX,
293    };
294    /// Whether this operation's deliveries are counted against `accepts`.
295    pub fn throttles(operation: &Operation) -> bool {
296        matches!(operation, Operation::Accept { multishot: true })
297    }
298    /// Whether this event spent one of `accepts`.
299    pub fn spends<D>(event: &Event<D>) -> bool {
300        !event.terminal
301            && matches!(
302                event.result,
303                Ok(Outcome::Accepted { .. } | Outcome::PipeAccepted(_))
304            )
305    }
306}
307#[derive(Clone, Copy, Debug, Default)]
308/// Instrumentation for the single bounded backend wait.
309pub struct PollInfo {
310    /// Blocking native wait invocations (positive timeout or infinite).
311    pub waits: u32,
312    /// Nonblocking native discovery invocations (zero timeout).
313    /// `waits + discovery_polls` is at most one per poll.
314    pub discovery_polls: u32,
315    /// Native wait/discovery invocations with no I/O or notifier events, including EINTR.
316    /// Bounded by `waits + discovery_polls`; retains revision-2 raw empty-poll accounting.
317    /// Private timeout events are not native work: epoll's timerfd, the IOCP
318    /// deadline packet, the WASI 0.2 deadline pollable and the WASI 0.3 deadline
319    /// subtask all count as zero-event calls, while simultaneous I/O or notifier
320    /// events keep the call non-empty.
321    pub zero_event_waits: u32,
322}
323
324#[cfg(any(
325    turnloop_backend = "epoll",
326    turnloop_backend = "kqueue",
327    turnloop_backend = "iocp",
328    turnloop_backend = "wasi_p2",
329    all(turnloop_backend = "wasi_p3", feature = "wasi-p3-experimental")
330))]
331impl PollInfo {
332    /// Record one native wait/discovery call using its effective timeout.
333    pub(crate) fn native(timeout: Option<Duration>, empty: bool) -> Self {
334        let discovery = timeout == Some(Duration::ZERO);
335        Self {
336            waits: u32::from(!discovery),
337            discovery_polls: u32::from(discovery),
338            zero_event_waits: u32::from(empty),
339        }
340    }
341}
342
343/// # Safety
344/// Implementers must uphold the buffer-lifetime and native-quiescence guarantees
345/// above: no native I/O may access a buffer after its terminal Event or Drop.
346/// Core lifetime and handle-release safety relies on those guarantees.
347pub unsafe trait Backend: Sized + 'static {
348    /// Thread-safe native wake endpoint type.
349    type Wake: Wake;
350    /// Owning transferable representation of an unregistered resource.
351    type Detached: Send + 'static;
352    /// Where typed filesystem requests run for this backend.
353    const FILESYSTEM: Filesystem = if cfg!(target_arch = "wasm32") {
354        Filesystem::Unsupported
355    } else {
356        Filesystem::Pool
357    };
358    /// Construct backend storage and native wait resources with the supplied shared read pool.
359    fn new(config: &Config, pool: BufferPool) -> Result<Self>;
360    /// Adopt an exclusively owned, bound but unconnected TCP transport and
361    /// configure its peer before a Connect request. Preserve the local binding
362    /// and existing socket options; apply nodelay when requested. On error,
363    /// retain no resource or native registration. Backends without native
364    /// transport adoption return Unsupported.
365    fn open_bound_tcp(
366        &mut self,
367        _handle: Handle,
368        _transport: Self::Detached,
369        _peer: SocketAddr,
370        _opts: crate::TcpOpts,
371    ) -> Result<()> {
372        Err(Error::new(crate::ErrorKind::Unsupported))
373    }
374    /// Accept a typed filesystem request (only with `Filesystem::Backend`). `handle`
375    /// is the request's file handle, or the new handle for an open.
376    fn fs(&mut self, _op: OpId, _handle: Option<Handle>, _request: crate::FsRequest) -> Result<()> {
377        Err(Error::new(crate::ErrorKind::Unsupported))
378    }
379    /// Bind a native filesystem watch to a new handle, retaining nothing on error.
380    fn fs_watch(
381        &mut self,
382        _handle: Handle,
383        _path: &crate::FsPath,
384        _options: crate::WatchOptions,
385    ) -> Result<()> {
386        Err(Error::new(crate::ErrorKind::Unsupported))
387    }
388    /// Give process-wide services this loop's parking-aware notification endpoint.
389    fn set_notifier(&mut self, _notifier: crate::Notifier) {}
390    /// Spawn and bind the child and requested parent pipe handles atomically.
391    /// Failure must release all supplied handles and reap any created child.
392    ///
393    /// `extra` is parallel to `spec.extra`: a handle is supplied for every entry
394    /// whose source has a parent end, and `None` for the rest. The core has
395    /// already checked descriptor numbers and duplicates.
396    fn spawn(
397        &mut self,
398        _handle: Handle,
399        _pipes: [Option<Handle>; 3],
400        _extra: &[Option<Handle>],
401        _spec: &crate::ProcessSpec,
402    ) -> Result<u32> {
403        Err(Error::new(crate::ErrorKind::Unsupported))
404    }
405    /// Begin nonblocking resource teardown before the core cancels its operations.
406    /// Process backends terminate the owned child/tree here and defer its terminal
407    /// acknowledgement until exit/reaping, so release never blocks a normal turn.
408    /// Other resources need no action. An error leaves the core handle open.
409    fn prepare_close(&mut self, _handle: Handle) -> Result<()> {
410        Ok(())
411    }
412    /// Signal an owned child, or its explicitly isolated process group.
413    fn kill(&mut self, _handle: Handle, _signal: crate::Signal, _group: bool) -> Result<()> {
414        Err(Error::new(crate::ErrorKind::Unsupported))
415    }
416    /// Bind a process-wide signal subscription to a new core handle.
417    fn signal(&mut self, _handle: Handle, _signal: crate::Signal) -> Result<()> {
418        Err(Error::new(crate::ErrorKind::Unsupported))
419    }
420    /// Set a terminal mode, retaining the original settings until release/drop.
421    fn tty_set_mode(&mut self, _handle: Handle, _mode: crate::TtyMode) -> Result<()> {
422        Err(Error::new(crate::ErrorKind::Unsupported))
423    }
424    /// Apply one socket option to a live resource, synchronously, through the OS.
425    /// No Request is accepted and no Event is produced. A platform without an
426    /// equivalent returns Unsupported; silently ignoring an option is forbidden,
427    /// because a host cannot tell an ignored option from an applied one.
428    fn set_option(&mut self, _handle: Handle, _option: crate::SocketOption) -> Result<()> {
429        Err(Error::new(crate::ErrorKind::Unsupported))
430    }
431    /// Synchronously request native receive-side shutdown without closing the
432    /// send direction. Existing accepted requests retain their normal buffer
433    /// ownership and terminal acknowledgement requirements. Unsupported transports
434    /// must fail without changing either direction.
435    fn shutdown_receive(&mut self, _handle: Handle) -> Result<()> {
436        Err(Error::new(crate::ErrorKind::Unsupported))
437    }
438    /// Read one socket option from the OS. Backends never answer from a cache of
439    /// what was set: the kernel may round, clamp or double a request, and the
440    /// caller is entitled to the value the kernel actually holds.
441    fn get_option(
442        &self,
443        _handle: Handle,
444        _kind: crate::SocketOptionKind,
445    ) -> Result<crate::SocketOption> {
446        Err(Error::new(crate::ErrorKind::Unsupported))
447    }
448    /// Set TCP keep-alive timing without changing SO_KEEPALIVE.
449    fn set_keepalive_parameters(
450        &mut self,
451        _handle: Handle,
452        _value: crate::KeepAlive,
453    ) -> Result<()> {
454        Err(Error::new(crate::ErrorKind::Unsupported))
455    }
456    /// Query TCP keep-alive timing even while SO_KEEPALIVE is disabled.
457    fn keepalive_parameters(&self, _handle: Handle) -> Result<crate::KeepAlive> {
458        Err(Error::new(crate::ErrorKind::Unsupported))
459    }
460    /// Change an already-listening TCP socket's backlog.
461    fn set_listen_backlog(&mut self, _handle: Handle, _backlog: u32) -> Result<()> {
462        Err(Error::new(crate::ErrorKind::Unsupported))
463    }
464    /// Shut down receive after read operations have been acknowledged.
465    /// Pending writes remain valid. A pending receive returns WouldBlock.
466    fn shutdown_read(&mut self, _handle: Handle) -> Result<()> {
467        Err(Error::new(crate::ErrorKind::Unsupported))
468    }
469    /// Report the native identity of a live transport, for the host only.
470    ///
471    /// The core never acts on the value and never stores it: it reads it out of
472    /// the backend's own table and returns it, so a host can implement Node's
473    /// `socket._handle.fd`. Backends return Unsupported for a resource with no
474    /// descriptor identity of its own (timers, processes, signals, watches, and
475    /// every WASI/web resource). See `Driver::raw_transport` for the host rules.
476    fn raw_transport(&self, _handle: Handle) -> Result<crate::RawTransport> {
477        Err(Error::new(crate::ErrorKind::Unsupported))
478    }
479    /// Query current terminal dimensions.
480    fn tty_window_size(&self, _handle: Handle) -> Result<crate::WindowSize> {
481        Err(Error::new(crate::ErrorKind::Unsupported))
482    }
483    /// Monotonic, nondecreasing time in a consistent domain across calls. Native
484    /// adapters return std::time::Instant::now(). Web adapters construct
485    /// crate::Instant::from_duration from their monotonic host clock. This method
486    /// must not schedule work, block, or invoke a user callback.
487    fn now(&self) -> crate::Instant;
488    /// Validate the original request even when queued completions eliminate the
489    /// effective wait. Browser main-thread adapters reject every timeout but Now;
490    /// a worker adapter may support blocking. Native adapters use this default.
491    fn validate_timeout(&self, _timeout: crate::Timeout) -> Result<()> {
492        Ok(())
493    }
494    /// The core owns timer semantics. Callback-driven adapters arm one host timer
495    /// for this earliest deadline, whose callback schedules a turn. None disarms
496    /// it. Native pollers need no action: poll receives the effective timeout.
497    /// This is a scheduling import, never a user callback. If host scheduling
498    /// fails, preserve the failure and return it from poll; never fake expiry.
499    fn deadline_changed(&mut self, _deadline: Option<crate::Instant>) {}
500    /// Clone the lifetime-safe native wake endpoint for this backend.
501    fn waker(&self) -> Arc<Self::Wake>;
502    /// Bind a new resource to the supplied handle, retaining nothing on error.
503    fn open(&mut self, handle: Handle, spec: Open) -> Result<()>;
504    /// Return the local IP endpoint of a bound socket.
505    fn local_addr(&self, handle: Handle) -> Result<SocketAddr>;
506    /// Accept one operation or reject it before retaining native buffer access.
507    fn submit(&mut self, request: Request) -> Result<()>;
508    /// Start a handle-free host name lookup. The default uses no resources and
509    /// lets the core fall back to its native blocking pool. Accepted requests
510    /// obey the same terminal/cancellation and no-spin rules as socket I/O.
511    fn resolve(&mut self, _op: OpId, _request: &crate::DnsRequest) -> Result<()> {
512        Err(Error::new(crate::ErrorKind::Unsupported))
513    }
514    /// Request cancellation; terminal acknowledgement must precede memory reuse.
515    fn cancel(&mut self, op: OpId) -> Result<()>;
516    /// Whether completions or immediately runnable cached operations are available.
517    fn has_work(&self) -> bool;
518    /// Append bounded completions, performing at most one OS wait with the
519    /// supplied exact timeout, and delivering no more multishot connections
520    /// than `budget` allows.
521    fn poll(
522        &mut self,
523        timeout: Option<Duration>,
524        budget: Budget,
525        events: &mut Vec<Event<Self::Detached>>,
526    ) -> Result<PollInfo>;
527    /// Release a quiescent resource after Closed was appended to host output.
528    fn release(&mut self, handle: Handle);
529    /// Unregister a quiescent resource and return its owning transferable representation.
530    fn detach(&mut self, handle: Handle) -> Result<Self::Detached>;
531    /// Register an owning transport on this loop; failure drops the rejected transport.
532    fn attach(&mut self, handle: Handle, transport: Self::Detached) -> Result<()>;
533    /// Adopt an explicitly bound TCP socket and install its connection destination.
534    /// No connection is initiated here; the subsequent Connect request owns it.
535    /// Reject non-TCP, already connected, unbound, or mismatched-family sockets.
536    /// On failure retain nothing and drop the rejected transport.
537    fn attach_tcp_connect(
538        &mut self,
539        _handle: Handle,
540        _transport: Self::Detached,
541        _destination: SocketAddr,
542    ) -> Result<()> {
543        Err(Error::new(crate::ErrorKind::Unsupported))
544    }
545    /// Adopt an unbound TCP socket and install its connection destination.
546    /// Unix must not bind before Connect; Windows binds inside adoption for
547    /// ConnectEx. Reject bound/non-TCP/mismatched-family transports and retain
548    /// nothing on failure. Subsequent Connect owns completion and cancellation.
549    fn attach_tcp_connect_unbound(
550        &mut self,
551        _handle: Handle,
552        _transport: Self::Detached,
553        _destination: SocketAddr,
554    ) -> Result<()> {
555        Err(Error::new(crate::ErrorKind::Unsupported))
556    }
557    /// Opt into external host waiting and return the borrowed integration primitive.
558    fn integration(&mut self) -> Result<Integration>;
559}
560
561#[cfg(turnloop_backend = "epoll")]
562mod epoll;
563#[cfg(turnloop_backend = "kqueue")]
564mod kqueue;
565#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
566mod poller;
567#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
568mod socket;
569#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
570mod sockopt;
571#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
572pub mod unix;
573#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
574pub use unix::Unix as Platform;
575
576#[cfg(turnloop_backend = "iocp")]
577pub mod iocp;
578#[cfg(turnloop_backend = "iocp")]
579pub use iocp::Iocp as Platform;
580
581#[cfg(any(
582    turnloop_backend = "wasi_p2",
583    all(turnloop_backend = "wasi_p3", feature = "wasi-p3-experimental")
584))]
585mod wasi_fs;
586#[cfg(turnloop_backend = "wasi_p2")]
587pub mod wasi_p2;
588#[cfg(turnloop_backend = "wasi_p2")]
589pub use wasi_p2::WasiP2 as Platform;
590
591#[cfg(turnloop_backend = "web")]
592pub mod web;
593#[cfg(turnloop_backend = "web")]
594pub use web::Web as Platform;
595
596#[cfg(all(turnloop_backend = "wasi_p3", feature = "wasi-p3-experimental"))]
597pub mod wasi_p3;
598#[cfg(all(turnloop_backend = "wasi_p3", feature = "wasi-p3-experimental"))]
599pub use wasi_p3::WasiP3 as Platform;
600#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
601mod ipc;
602#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
603mod process;
604#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
605mod stdio;
606
607#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
608mod services;
609#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
610mod signals;
611
612#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
613mod files;
614#[cfg(any(turnloop_backend = "kqueue", turnloop_backend = "epoll"))]
615mod watch;