nexio 0.1.0

A thread-per-core io_uring async runtime for Linux with owned-buffer I/O and a cancellation-safety layer checked by Miri and Kani
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! `Op<B>` and specialized futures representing in-flight io_uring operations.
//!
//! Ownership flow:
//!   - Buffer lives in `Op::buf` (ManuallyDrop) while in-flight.
//!   - On `Poll::Ready`: take buf, return to caller via BufResult.
//!   - On `Drop` while in-flight: take buf, move into slab as Ignored.
//!     Slab drops buf when the real CQE arrives.
//!
//! This is the "leak-until-real-completion" pattern. No double-free, no
//! blocking Drop, no use-after-free.

use std::{
    future::Future,
    io,
    mem::ManuallyDrop,
    os::unix::io::RawFd,
    pin::Pin,
    task::{Context, Poll},
};

use super::{
    slab::{ErasedBox, ErasedBuf, SlabKey},
    REACTOR,
};
use crate::buf::BufResult;

/// Lifecycle state for an in-flight operation future.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum OpLifecycle {
    InFlight,
    Complete(i32),
}

/// A `Future` wrapping one in-flight io_uring operation with an owned buffer.
///
/// `!Send` by construction: reactor is thread-local and the buffer pointer
/// registered with the kernel must not migrate threads.
pub struct Op<B: Unpin + Send + 'static> {
    key: SlabKey,
    buf: ManuallyDrop<B>,
    lifecycle: OpLifecycle,
}

impl<B: Unpin + Send + 'static> Op<B> {
    /// Create a new in-flight operation from a submitted key and buffer.
    ///
    /// # Safety
    /// Caller must have submitted an SQE with `user_data = key.as_u64()` and
    /// transferred ownership of `buf`'s backing memory to the kernel.
    pub unsafe fn new(key: SlabKey, buf: B) -> Self {
        Self {
            key,
            buf: ManuallyDrop::new(buf),
            lifecycle: OpLifecycle::InFlight,
        }
    }

    /// Returns the key associated with this operation.
    pub fn key(&self) -> SlabKey {
        self.key
    }
}

impl<B: Unpin + Send + 'static> Future for Op<B> {
    type Output = BufResult<usize, B>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let OpLifecycle::Complete(_) = self.lifecycle {
            panic!("Op polled after completion");
        }

        let key = self.key;
        // Check if reactor already completed this op and consume slot in one borrow.
        let result = REACTOR.with(|r| r.borrow_mut().slab.poll_and_consume(key, cx.waker()));

        match result {
            None => Poll::Pending,
            Some(raw) => {
                let this = self.get_mut();
                // SAFETY: this branch runs exactly once; ManuallyDrop::take
                // leaves buf logically uninitialised, which is fine — Drop
                // won't run on it again because we're in the Complete branch.
                let buf = unsafe { ManuallyDrop::take(&mut this.buf) };
                this.lifecycle = OpLifecycle::Complete(raw);

                let io_result = if raw >= 0 {
                    Ok(raw as usize)
                } else {
                    Err(io::Error::from_raw_os_error(-raw))
                };

                Poll::Ready((io_result, buf))
            }
        }
    }
}

impl<B: Unpin + Send + 'static> Drop for Op<B> {
    fn drop(&mut self) {
        if self.lifecycle == OpLifecycle::InFlight {
            // Kernel still has a pointer into our buffer.
            // 1. Take buf out of ManuallyDrop.
            // 2. Move it into the slab as Ignored.
            // 3. Submit best-effort ASYNC_CANCEL if still in flight.
            let buf = unsafe { ManuallyDrop::take(&mut self.buf) };
            let boxed: Box<dyn ErasedBuf> = Box::new(ErasedBox(buf));

            REACTOR.with(|r| {
                let mut reactor = r.borrow_mut();
                if reactor.slab.ignore(self.key, boxed) {
                    let _ = reactor.submit_cancel(self.key);
                }
            });
        }
        // If Complete, buf was already taken in poll(). ManuallyDrop: no-op.
    }
}

enum LazyPhase<F> {
    Pending(Option<F>),
    InFlight(SlabKey),
    Complete,
}

/// A `Future` that submits an `io_uring` op and registers the waker in a single
/// reactor borrow on its first poll, preserving full cancel-on-drop safety.
pub struct LazyOp<B: Unpin + Send + 'static, F> {
    buf: ManuallyDrop<B>,
    phase: LazyPhase<F>,
}

impl<B, F> LazyOp<B, F>
where
    B: Unpin + Send + 'static,
    F: FnOnce(&mut super::Reactor, &mut B, std::task::Waker) -> io::Result<SlabKey> + Unpin,
{
    /// Create a new `LazyOp` owning `buf` and a submission closure `submit`.
    pub fn new(buf: B, submit: F) -> Self {
        Self {
            buf: ManuallyDrop::new(buf),
            phase: LazyPhase::Pending(Some(submit)),
        }
    }
}

impl<B, F> Future for LazyOp<B, F>
where
    B: Unpin + Send + 'static,
    F: FnOnce(&mut super::Reactor, &mut B, std::task::Waker) -> io::Result<SlabKey> + Unpin,
{
    type Output = BufResult<usize, B>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        match &mut this.phase {
            LazyPhase::Pending(submit) => {
                let submit_fn = submit.take().expect("LazyOp missing submit closure");
                let buf_ref = &mut *this.buf;
                let res = REACTOR.with(|r| {
                    let mut reactor = r.borrow_mut();
                    submit_fn(&mut reactor, buf_ref, cx.waker().clone())
                });
                match res {
                    Ok(key) => {
                        this.phase = LazyPhase::InFlight(key);
                        Poll::Pending
                    }
                    Err(e) => {
                        let taken = unsafe { ManuallyDrop::take(&mut this.buf) };
                        this.phase = LazyPhase::Complete;
                        Poll::Ready((Err(e), taken))
                    }
                }
            }
            LazyPhase::InFlight(key) => {
                let k = *key;
                let result = REACTOR.with(|r| r.borrow_mut().slab.poll_and_consume(k, cx.waker()));
                match result {
                    None => Poll::Pending,
                    Some(raw) => {
                        let taken = unsafe { ManuallyDrop::take(&mut this.buf) };
                        this.phase = LazyPhase::Complete;
                        let io_result = if raw >= 0 {
                            Ok(raw as usize)
                        } else {
                            Err(io::Error::from_raw_os_error(-raw))
                        };
                        Poll::Ready((io_result, taken))
                    }
                }
            }
            LazyPhase::Complete => panic!("LazyOp polled after completion"),
        }
    }
}

impl<B: Unpin + Send + 'static, F> Drop for LazyOp<B, F> {
    fn drop(&mut self) {
        match self.phase {
            LazyPhase::Pending(_) => {
                // Never submitted to kernel; drop buffer directly.
                unsafe { ManuallyDrop::drop(&mut self.buf) };
            }
            LazyPhase::InFlight(key) => {
                let taken = unsafe { ManuallyDrop::take(&mut self.buf) };
                let boxed: Box<dyn ErasedBuf> = Box::new(ErasedBox(taken));
                REACTOR.with(|r| {
                    let mut reactor = r.borrow_mut();
                    if reactor.slab.ignore(key, boxed) {
                        let _ = reactor.submit_cancel(key);
                    }
                });
            }
            LazyPhase::Complete => {}
        }
    }
}

/// A future representing an in-flight operation returning a bare `i32` result.
pub struct SimpleOp {
    key: SlabKey,
    lifecycle: OpLifecycle,
}

impl SimpleOp {
    /// Create a new `SimpleOp` wrapping `key`.
    pub fn new(key: SlabKey) -> Self {
        Self {
            key,
            lifecycle: OpLifecycle::InFlight,
        }
    }

    /// Return the slab key.
    pub fn key(&self) -> SlabKey {
        self.key
    }
}

impl Future for SimpleOp {
    type Output = io::Result<i32>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let OpLifecycle::Complete(_) = self.lifecycle {
            panic!("SimpleOp polled after completion");
        }

        let key = self.key;
        let this = self.get_mut();
        REACTOR.with(|r| {
            let mut reactor = r.borrow_mut();
            match reactor.slab.poll_and_consume(key, cx.waker()) {
                None => Poll::Pending,
                Some(result) => {
                    this.lifecycle = OpLifecycle::Complete(result);
                    if result >= 0 {
                        Poll::Ready(Ok(result))
                    } else if result == -libc::ETIME {
                        // Timer expired without error
                        Poll::Ready(Ok(0))
                    } else {
                        Poll::Ready(Err(io::Error::from_raw_os_error(-result)))
                    }
                }
            }
        })
    }
}

impl Drop for SimpleOp {
    fn drop(&mut self) {
        if self.lifecycle == OpLifecycle::InFlight {
            REACTOR.with(|r| {
                let mut reactor = r.borrow_mut();
                if reactor.slab.ignore_simple(self.key) {
                    let _ = reactor.submit_cancel(self.key);
                }
            });
        }
    }
}

/// A future representing an in-flight TCP Accept operation.
pub struct AcceptOp {
    key: SlabKey,
    lifecycle: OpLifecycle,
}

impl AcceptOp {
    /// Create a new `AcceptOp` wrapping `key`.
    pub fn new(key: SlabKey) -> Self {
        Self {
            key,
            lifecycle: OpLifecycle::InFlight,
        }
    }

    /// Return the slab key.
    pub fn key(&self) -> SlabKey {
        self.key
    }
}

impl Future for AcceptOp {
    type Output = io::Result<RawFd>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let OpLifecycle::Complete(_) = self.lifecycle {
            panic!("AcceptOp polled after completion");
        }

        let key = self.key;
        let this = self.get_mut();
        REACTOR.with(|r| {
            let mut reactor = r.borrow_mut();
            match reactor.slab.poll_and_consume(key, cx.waker()) {
                None => Poll::Pending,
                Some(result) => {
                    this.lifecycle = OpLifecycle::Complete(result);
                    if result >= 0 {
                        Poll::Ready(Ok(result as RawFd))
                    } else {
                        Poll::Ready(Err(io::Error::from_raw_os_error(-result)))
                    }
                }
            }
        })
    }
}

impl Drop for AcceptOp {
    fn drop(&mut self) {
        if self.lifecycle == OpLifecycle::InFlight {
            REACTOR.with(|r| {
                let mut reactor = r.borrow_mut();
                if reactor.slab.ignore_accept(self.key) {
                    let _ = reactor.submit_cancel(self.key);
                }
            });
        }
    }
}

/// A future representing an in-flight TCP Connect operation.
pub struct ConnectOp {
    key: SlabKey,
    lifecycle: OpLifecycle,
}

impl ConnectOp {
    /// Create a new `ConnectOp` wrapping `key`.
    pub fn new(key: SlabKey) -> Self {
        Self {
            key,
            lifecycle: OpLifecycle::InFlight,
        }
    }

    /// Return the slab key.
    pub fn key(&self) -> SlabKey {
        self.key
    }
}

impl Future for ConnectOp {
    type Output = io::Result<()>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let OpLifecycle::Complete(_) = self.lifecycle {
            panic!("ConnectOp polled after completion");
        }

        let key = self.key;
        let this = self.get_mut();
        REACTOR.with(|r| {
            let mut reactor = r.borrow_mut();
            match reactor.slab.poll_and_consume(key, cx.waker()) {
                None => Poll::Pending,
                Some(result) => {
                    this.lifecycle = OpLifecycle::Complete(result);
                    if result >= 0 {
                        Poll::Ready(Ok(()))
                    } else {
                        Poll::Ready(Err(io::Error::from_raw_os_error(-result)))
                    }
                }
            }
        })
    }
}

impl Drop for ConnectOp {
    fn drop(&mut self) {
        if self.lifecycle == OpLifecycle::InFlight {
            REACTOR.with(|r| {
                let mut reactor = r.borrow_mut();
                if reactor.slab.ignore_simple(self.key) {
                    let _ = reactor.submit_cancel(self.key);
                }
            });
        }
    }
}