karmaio 0.1.0

A modern, fast, share-nothing asynchronous runtime for Rust
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! Typed shared ownership of an OS resource for completion-based I/O.
//!
//! [`SharedIoHandle<T>`] keeps a cloneable (`Rc`) handle so in-flight ops can pin
//! the resource until their CQEs complete. Prefer [`SharedIoHandle::close`] over
//! drop when close errors matter; drop still sync-closes when the last unique
//! owner remains.
//!
//! Resource identity is preserved in `T` (`socket2::Socket`, `std::fs::File`,
//! `OwnedFd`, …). Submit and close paths extract a copyable [`OsRawHandle`] via
//! [`AsRawOsHandle`] / [`IntoRawOsHandle`].

use std::{cell::RefCell, future::poll_fn, io, mem, ops::Deref, rc::Rc, task::Waker};

#[cfg(unix)]
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{
    AsRawHandle, AsRawSocket, FromRawHandle, FromRawSocket, IntoRawHandle, IntoRawSocket, OwnedHandle, OwnedSocket,
    RawHandle, RawSocket,
};
#[cfg(windows)]
use windows_sys::Win32::Foundation::HANDLE;

use crate::driver::ops::Op;

// ---------------------------------------------------------------------------
// SharedIoHandle<T>
// ---------------------------------------------------------------------------

/// Shared ownership of an OS resource for completion-based I/O.
///
/// Clones are cheap (`Rc`). In-flight ops hold clones so the resource cannot be
/// closed until those ops complete. Prefer `close().await` over drop when close
/// errors matter.
///
/// Note: `Clone` is implemented manually so it does **not** require `T: Clone` —
/// only the `Rc` is cloned; `T` is shared, not duplicated.
pub(crate) struct SharedIoHandle<T> {
    inner: Rc<Inner<T>>,
}

impl<T> Clone for SharedIoHandle<T> {
    fn clone(&self) -> Self {
        Self {
            inner: Rc::clone(&self.inner),
        }
    }
}

impl<T> SharedIoHandle<T> {
    /// Create a new shared handle owning `resource`.
    pub(crate) fn new(resource: T) -> Self {
        Self {
            inner: Rc::new(Inner {
                resource: Some(resource),
                state: RefCell::new(State::Init),
                #[cfg(windows)]
                association: Rc::new(RefCell::new(AssociationState::Unassociated)),
            }),
        }
    }

    /// Access the owned resource. Panics if used after close transferred ownership.
    pub(crate) fn with_resource<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        f(self
            .inner
            .resource
            .as_ref()
            .expect("SharedIoHandle used after close transferred ownership"))
    }

    /// Whether both handles refer to the same underlying resource.
    pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.inner, &other.inner)
    }

    /// Number of strong references to the underlying resource.
    ///
    /// Clones held by in-flight operations and by application owners each
    /// increment this count. A count of 1 means this handle is exclusive.
    pub(crate) fn strong_count(&self) -> usize {
        Rc::strong_count(&self.inner)
    }

    /// Try to unwrap the owned resource if this is the unique strong reference.
    /// Does not close the resource.
    #[allow(dead_code)]
    pub(crate) fn try_unwrap(self) -> Result<T, Self> {
        // Avoid running `Drop for SharedIoHandle` while we move out of `self`.
        let this = mem::ManuallyDrop::new(self);
        // Safety: `this` is not dropped; we take ownership of `inner` exactly once.
        let inner = unsafe { std::ptr::read(&this.inner) };
        match Rc::try_unwrap(inner) {
            Ok(inner) => {
                // Avoid running `Drop for Inner` (which would drop/close `T`).
                let mut inner = mem::ManuallyDrop::new(inner);
                let resource = inner.resource.take().expect("resource already taken by close");
                // Drop state without dropping the resource.
                unsafe {
                    std::ptr::drop_in_place(&mut inner.state);
                    #[cfg(windows)]
                    std::ptr::drop_in_place(&mut inner.association);
                }
                Ok(resource)
            }
            Err(inner) => Err(Self { inner }),
        }
    }

    /// Wait until this is the unique strong reference, then take the owned
    /// resource without closing it. Returns `None` if already closed.
    pub(crate) async fn take(mut self) -> Option<T> {
        loop {
            if let Some(inner) = Rc::get_mut(&mut self.inner) {
                return inner.take_owned();
            }
            self.is_unique().await;
        }
    }

    /// Completes when the strong `Rc` count is 1.
    /// Polled again whenever a clone is dropped (see `Drop`).
    async fn is_unique(&self) {
        use std::task::Poll;

        poll_fn(|cx| {
            if Rc::<Inner<T>>::strong_count(&self.inner) == 1 {
                return Poll::Ready(());
            }

            let mut state = self.inner.state.borrow_mut();

            match &mut *state {
                State::Init => {
                    *state = State::Waiting(cx.waker().clone());
                    Poll::Pending
                }
                State::Waiting(waker) => {
                    if !waker.will_wake(cx.waker()) {
                        waker.clone_from(cx.waker());
                    }
                    Poll::Pending
                }
                State::Closed => Poll::Ready(()),
            }
        })
        .await;
    }
}

impl<T: IntoRawOsHandle> SharedIoHandle<T> {
    /// Wait for all in-flight operations to complete, then close the resource
    /// through the driver (or sync-close if submit fails).
    ///
    /// Prefer this over dropping when possible so close errors are returned and
    /// the OS resource is released promptly.
    pub(crate) async fn close(self) -> io::Result<()> {
        match self.take().await {
            Some(resource) => {
                let raw = resource.into_raw_os_handle();
                match Op::close(raw) {
                    Ok(op) => op.await,
                    Err(e) => {
                        // Submit failed: reclaim ownership and close synchronously.
                        // Safety: `raw` is open and not owned elsewhere; we just
                        // extracted it from `T` and failed to hand it to the driver.
                        unsafe { drop_raw_os_handle(raw) };
                        Err(e)
                    }
                }
            }
            // Already closed (e.g. double close).
            None => Ok(()),
        }
    }
}

impl<T: AsRawOsHandle> SharedIoHandle<T> {
    /// Returns the copyable raw OS value for kernel submission.
    #[allow(dead_code)] // available for submit paths; many ops use raw_fd/raw_handle helpers instead
    pub(crate) fn as_raw_os_handle(&self) -> OsRawHandle {
        self.with_resource(|r| r.as_raw_os_handle())
    }

    /// Windows-only alias used by existing ops.
    #[cfg(windows)]
    #[allow(dead_code)] // Convenience alias; no op calls it yet.
    pub(crate) fn raw_os_handle(&self) -> OsRawHandle {
        self.as_raw_os_handle()
    }
}

#[cfg(unix)]
impl<T: AsRawFd> SharedIoHandle<T> {
    /// Returns the underlying `RawFd`.
    pub(crate) fn raw_fd(&self) -> RawFd {
        self.with_resource(|r| r.as_raw_fd())
    }
}

#[cfg(windows)]
impl<T: AsRawHandle> SharedIoHandle<T> {
    /// Returns the underlying Win32 file handle (not a socket).
    #[allow(dead_code)]
    pub(crate) fn raw_handle(&self) -> RawHandle {
        self.with_resource(|r| r.as_raw_handle())
    }

    /// Returns the shared state used to associate this file handle with IOCP.
    #[cfg(windows)]
    pub(crate) fn handle_registration(&self) -> HandleRegistration {
        HandleRegistration {
            association: Rc::clone(&self.inner.association),
            raw: WindowsRawHandle::Handle(self.raw_handle()),
        }
    }
}

#[cfg(windows)]
impl<T: AsRawSocket> SharedIoHandle<T> {
    /// Returns the underlying Win32 socket.
    pub(crate) fn raw_socket(&self) -> RawSocket {
        self.with_resource(|r| r.as_raw_socket())
    }

    /// Returns the shared state used to associate this socket with IOCP.
    #[cfg(windows)]
    pub(crate) fn socket_registration(&self) -> HandleRegistration {
        HandleRegistration {
            association: Rc::clone(&self.inner.association),
            raw: WindowsRawHandle::Socket(self.raw_socket()),
        }
    }
}

impl<T> Deref for SharedIoHandle<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.inner
            .resource
            .as_ref()
            .expect("SharedIoHandle used after close transferred ownership")
    }
}

// Wake any task waiting for uniqueness when a clone is dropped.
// Without this, `close().await` / `take().await` can hang forever after
// in-flight ops complete.
impl<T> Drop for SharedIoHandle<T> {
    fn drop(&mut self) {
        let mut state = self.inner.state.borrow_mut();
        if let State::Waiting(_) = *state
            && let State::Waiting(waker) = mem::replace(&mut *state, State::Init)
        {
            // Wake the task wanting to take/close this handle and let it try again.
            // If it finds there are no more outstanding clones, it will succeed.
            // Otherwise it will start a new Future, waiting for another drop.
            waker.wake();
        }
    }
}

#[cfg(unix)]
impl<T: AsRawFd> AsRawFd for SharedIoHandle<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.raw_fd()
    }
}

#[cfg(unix)]
impl<T: AsFd> AsFd for SharedIoHandle<T> {
    fn as_fd(&self) -> BorrowedFd<'_> {
        // Borrow from the stored resource; lifetime is tied to `&self`.
        self.inner
            .resource
            .as_ref()
            .expect("SharedIoHandle used after close transferred ownership")
            .as_fd()
    }
}

// ---------------------------------------------------------------------------
// Raw / owned extraction traits
// ---------------------------------------------------------------------------

/// Extract a copyable raw OS value for kernel submission.
/// Implemented for the owned resource types we wrap.
#[allow(dead_code)] // available for submit paths; many ops use AsRawFd/AsRawHandle helpers instead
pub(crate) trait AsRawOsHandle {
    fn as_raw_os_handle(&self) -> OsRawHandle;
}

/// Consume into a raw value for exclusive close (no Drop of the OS resource).
pub(crate) trait IntoRawOsHandle {
    fn into_raw_os_handle(self) -> OsRawHandle;
}

// Platform-specific raw handle (file descriptor on Unix, file handle or socket on Windows).
// Copyable form used when submitting operations to the kernel.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum OsRawHandle {
    #[cfg(unix)]
    Fd(RawFd),
    #[cfg(windows)]
    Handle(RawHandle),
    #[cfg(windows)]
    Socket(RawSocket),
}

/// Shared exact-once association state for a Windows handle or socket.
///
/// The state is shared by all `SharedIoHandle` clones. A successful association
/// is idempotent for the same IOCP, while an attempt to use the resource with a
/// different runtime is rejected.
#[cfg(windows)]
#[derive(Clone)]
pub(crate) struct HandleRegistration {
    association: Rc<RefCell<AssociationState>>,
    raw: WindowsRawHandle,
}

#[cfg(windows)]
#[derive(Clone, Copy)]
enum WindowsRawHandle {
    Handle(RawHandle),
    Socket(RawSocket),
}

#[cfg(windows)]
enum AssociationState {
    Unassociated,
    Associated(usize),
}

#[cfg(windows)]
impl HandleRegistration {
    /// Associate the resource once, leaving it retryable if registration fails.
    pub(crate) fn associate(
        &self,
        registrar: usize,
        register: impl FnOnce(HANDLE) -> io::Result<()>,
    ) -> io::Result<()> {
        let mut state = self.association.borrow_mut();
        match *state {
            AssociationState::Associated(current) if current == registrar => return Ok(()),
            AssociationState::Associated(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    "I/O handle is already associated with another karmaio driver",
                ));
            }
            AssociationState::Unassociated => {}
        }

        register(self.raw.as_handle())?;
        *state = AssociationState::Associated(registrar);
        Ok(())
    }
}

#[cfg(windows)]
impl WindowsRawHandle {
    #[inline]
    fn as_handle(self) -> HANDLE {
        match self {
            Self::Handle(handle) => handle as HANDLE,
            Self::Socket(socket) => socket as HANDLE,
        }
    }
}

/// Rebuild an owned OS resource from a raw value and drop it (closes the resource).
///
/// Used when close submit fails and we must reclaim + sync-close.
///
/// # Safety
/// `raw` must be open and not owned elsewhere.
pub(crate) unsafe fn drop_raw_os_handle(raw: OsRawHandle) {
    match raw {
        #[cfg(unix)]
        OsRawHandle::Fd(fd) => drop(unsafe { OwnedFd::from_raw_fd(fd) }),
        #[cfg(windows)]
        OsRawHandle::Handle(h) => drop(unsafe { OwnedHandle::from_raw_handle(h) }),
        #[cfg(windows)]
        OsRawHandle::Socket(s) => drop(unsafe { OwnedSocket::from_raw_socket(s) }),
    }
}

// --- Unix: OwnedFd ---------------------------------------------------------

#[cfg(unix)]
impl AsRawOsHandle for OwnedFd {
    fn as_raw_os_handle(&self) -> OsRawHandle {
        OsRawHandle::Fd(self.as_raw_fd())
    }
}

#[cfg(unix)]
impl IntoRawOsHandle for OwnedFd {
    fn into_raw_os_handle(self) -> OsRawHandle {
        OsRawHandle::Fd(self.into_raw_fd())
    }
}

// --- std::fs::File ---------------------------------------------------------

impl AsRawOsHandle for std::fs::File {
    fn as_raw_os_handle(&self) -> OsRawHandle {
        #[cfg(unix)]
        {
            OsRawHandle::Fd(self.as_raw_fd())
        }
        #[cfg(windows)]
        {
            OsRawHandle::Handle(self.as_raw_handle())
        }
    }
}

impl IntoRawOsHandle for std::fs::File {
    fn into_raw_os_handle(self) -> OsRawHandle {
        #[cfg(unix)]
        {
            OsRawHandle::Fd(self.into_raw_fd())
        }
        #[cfg(windows)]
        {
            OsRawHandle::Handle(self.into_raw_handle())
        }
    }
}

// --- socket2::Socket (net feature) -----------------------------------------

#[cfg(feature = "net")]
impl AsRawOsHandle for socket2::Socket {
    fn as_raw_os_handle(&self) -> OsRawHandle {
        #[cfg(unix)]
        {
            OsRawHandle::Fd(self.as_raw_fd())
        }
        #[cfg(windows)]
        {
            OsRawHandle::Socket(self.as_raw_socket())
        }
    }
}

#[cfg(feature = "net")]
impl IntoRawOsHandle for socket2::Socket {
    fn into_raw_os_handle(self) -> OsRawHandle {
        #[cfg(unix)]
        {
            OsRawHandle::Fd(self.into_raw_fd())
        }
        #[cfg(windows)]
        {
            OsRawHandle::Socket(self.into_raw_socket())
        }
    }
}

// --- Windows: OwnedHandle / OwnedSocket ------------------------------------

#[cfg(windows)]
impl AsRawOsHandle for OwnedHandle {
    fn as_raw_os_handle(&self) -> OsRawHandle {
        OsRawHandle::Handle(self.as_raw_handle())
    }
}

#[cfg(windows)]
impl IntoRawOsHandle for OwnedHandle {
    fn into_raw_os_handle(self) -> OsRawHandle {
        OsRawHandle::Handle(self.into_raw_handle())
    }
}

#[cfg(windows)]
impl AsRawOsHandle for OwnedSocket {
    fn as_raw_os_handle(&self) -> OsRawHandle {
        OsRawHandle::Socket(self.as_raw_socket())
    }
}

#[cfg(windows)]
impl IntoRawOsHandle for OwnedSocket {
    fn into_raw_os_handle(self) -> OsRawHandle {
        OsRawHandle::Socket(self.into_raw_socket())
    }
}

// ---------------------------------------------------------------------------
// Inner storage
// ---------------------------------------------------------------------------

struct Inner<T> {
    // Open resource. `None` after ownership was transferred to an async close/take.
    // Only mutated when this Inner is uniquely owned (`Rc::get_mut`) or on Drop of T.
    resource: Option<T>,

    // Track the sharing state of the handle:
    // normal, being waited on to allow a close by the parent's owner, or already closed.
    state: RefCell<State>,

    /// Shared across every clone so successful IOCP registration happens once.
    #[cfg(windows)]
    association: Rc<RefCell<AssociationState>>,
}

impl<T> Inner<T> {
    // Take ownership of the resource, marking state Closed so Drop does not close again.
    fn take_owned(&mut self) -> Option<T> {
        {
            let state = RefCell::get_mut(&mut self.state);
            if let State::Closed = *state {
                return None;
            }
            *state = State::Closed;
        }
        self.resource.take()
    }
}

// Drop of `Inner<T>` drops any remaining `T`, which closes the OS resource
// (File / Socket / OwnedFd / OwnedHandle / OwnedSocket). After explicit
// `close`/`take`, `resource` is `None` so Drop is a no-op for the OS handle.

enum State {
    // Initial state
    Init,

    // Waiting for all in-flight operations to complete.
    // Waits for the number of strong Rc pointers to drop to 1.
    Waiting(Waker),

    // The close has been triggered by the parent owner (explicit close/take).
    Closed,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(windows)]
    use std::cell::Cell;
    #[cfg(unix)]
    use std::task::Poll;

    #[cfg(windows)]
    fn test_registration(raw: WindowsRawHandle) -> HandleRegistration {
        HandleRegistration {
            association: Rc::new(RefCell::new(AssociationState::Unassociated)),
            raw,
        }
    }

    #[cfg(windows)]
    #[test]
    fn registration_associates_once_and_rejects_another_driver() {
        let registration = test_registration(WindowsRawHandle::Handle(1usize as RawHandle));
        let calls = Cell::new(0);

        registration
            .associate(7, |_| {
                calls.set(calls.get() + 1);
                Ok(())
            })
            .expect("first registration");
        registration
            .associate(7, |_| {
                calls.set(calls.get() + 1);
                Ok(())
            })
            .expect("same driver registration is idempotent");

        assert_eq!(calls.get(), 1);
        assert_eq!(
            registration
                .associate(8, |_| Ok(()))
                .expect_err("another driver must be rejected")
                .kind(),
            io::ErrorKind::AlreadyExists
        );
    }

    #[cfg(windows)]
    #[test]
    fn failed_registration_can_be_retried() {
        let raw = usize::MAX as RawSocket;
        let registration = test_registration(WindowsRawHandle::Socket(raw));
        let seen = Cell::new(0usize);

        assert_eq!(
            registration
                .associate(3, |handle| {
                    seen.set(handle as usize);
                    Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected"))
                })
                .expect_err("injected registration failure")
                .kind(),
            io::ErrorKind::PermissionDenied
        );
        assert_eq!(seen.get(), raw as usize);

        registration
            .associate(3, |_| Ok(()))
            .expect("failed registration must remain retryable");
    }

    #[cfg(unix)]
    fn dev_null_handle() -> SharedIoHandle<std::fs::File> {
        let file = std::fs::File::open("/dev/null").expect("/dev/null");
        SharedIoHandle::new(file)
    }

    #[cfg(unix)]
    #[test]
    fn try_unwrap_succeeds_when_unique() {
        let handle = dev_null_handle();
        let owned = match handle.try_unwrap() {
            Ok(owned) => owned,
            Err(_) => panic!("unique handle should unwrap"),
        };
        // Dropping owned closes the fd.
        drop(owned);
    }

    #[cfg(unix)]
    #[test]
    fn try_unwrap_fails_when_shared() {
        let handle = dev_null_handle();
        let clone = handle.clone();
        let err = match handle.try_unwrap() {
            Err(handle) => handle,
            Ok(_) => panic!("shared handle must not unwrap"),
        };
        drop(clone);
        // Recover uniqueness and close via drop.
        drop(err);
    }

    #[cfg(unix)]
    #[test]
    fn close_waits_for_in_flight_clone() {
        use crate::runtime::local::Runtime;

        let mut runtime = Runtime::new().expect("runtime should start");

        let handle = dev_null_handle();
        let inflight = handle.clone();

        // Close must wait until the in-flight clone is dropped.
        let close_jh = runtime.spawn(async move {
            handle.close().await.expect("close should succeed");
        });

        // Yield once so the close task can park on uniqueness, then drop the clone.
        let drop_jh = runtime.spawn(async move {
            let mut yielded = false;
            std::future::poll_fn(|cx| {
                if !yielded {
                    yielded = true;
                    cx.waker().wake_by_ref();
                    Poll::Pending
                } else {
                    Poll::Ready(())
                }
            })
            .await;
            drop(inflight);
        });

        runtime.block_on(async {
            drop_jh.await.expect("drop task");
            close_jh.await.expect("close task");
        });
    }

    #[cfg(unix)]
    #[test]
    fn close_when_already_unique() {
        use crate::runtime::local::Runtime;

        let mut runtime = Runtime::new().expect("runtime should start");
        let handle = dev_null_handle();

        runtime.block_on(async move {
            handle.close().await.expect("close should succeed");
        });
    }

    #[cfg(unix)]
    #[test]
    fn take_returns_owned_when_unique() {
        use crate::runtime::local::Runtime;

        let mut runtime = Runtime::new().expect("runtime should start");
        let handle = dev_null_handle();

        runtime.block_on(async move {
            let owned = handle.take().await.expect("take should return owned handle");
            // Caller owns the file; drop closes it.
            drop(owned);
        });
    }

    #[cfg(unix)]
    #[test]
    fn take_waits_for_in_flight_clone() {
        use crate::runtime::local::Runtime;

        let mut runtime = Runtime::new().expect("runtime should start");
        let handle = dev_null_handle();
        let inflight = handle.clone();

        let take_jh = runtime.spawn(async move { handle.take().await.expect("take should succeed after clone drops") });

        let drop_jh = runtime.spawn(async move {
            let mut yielded = false;
            std::future::poll_fn(|cx| {
                if !yielded {
                    yielded = true;
                    cx.waker().wake_by_ref();
                    Poll::Pending
                } else {
                    Poll::Ready(())
                }
            })
            .await;
            drop(inflight);
        });

        runtime.block_on(async {
            drop_jh.await.expect("drop task");
            let owned = take_jh.await.expect("take task");
            drop(owned);
        });
    }

    #[cfg(unix)]
    #[test]
    fn drop_closes_synchronously_without_explicit_close() {
        // last ref Drop closes via File / OwnedFd Drop.
        let handle = dev_null_handle();
        drop(handle);
    }

    #[cfg(unix)]
    #[test]
    fn take_after_prior_take_is_none_via_closed_state() {
        // take() marks Closed before returning; a second exclusive take on a
        // reconstructed handle is not possible through the public API. Instead
        // verify take_owned semantics: after take, Inner is Closed with no resource.
        use crate::runtime::local::Runtime;

        let mut runtime = Runtime::new().expect("runtime should start");
        let handle = dev_null_handle();

        runtime.block_on(async move {
            let owned = handle.take().await.expect("first take");
            drop(owned);
        });
    }

    #[cfg(unix)]
    #[test]
    fn as_raw_os_handle_matches_as_raw_fd() {
        let handle = dev_null_handle();
        let raw = handle.as_raw_os_handle();
        match raw {
            OsRawHandle::Fd(fd) => assert_eq!(fd, handle.as_raw_fd()),
        }
    }

    #[cfg(unix)]
    #[test]
    fn try_unwrap_owned_fd_variant() {
        let file = std::fs::File::open("/dev/null").expect("/dev/null");
        let handle = SharedIoHandle::new(OwnedFd::from(file));
        let owned = match handle.try_unwrap() {
            Ok(owned) => owned,
            Err(_) => panic!("unique handle should unwrap"),
        };
        drop(owned);
    }

    #[cfg(unix)]
    #[test]
    fn deref_exposes_resource() {
        let handle = dev_null_handle();
        // Deref to File — metadata is a smoke check that we have a live File.
        let _ = handle.metadata().expect("metadata");
    }
}