dope-uring 0.76.0

Owned io_uring backend for dope
Documentation
use std::{env, fs, io, mem, num::NonZero, pin::Pin, time::Duration};

use dope::{
    core::{
        Errno,
        driver::{
            route::KeyTag,
            settings::{self, claim::Needs},
            storage::Resident,
        },
        executor::{session::Session, task::Task},
    },
    manifold::file::read::{self, Operation},
};
use dope_test::harness::Executor;
use dope_test::{fibers, reclaim::Events};
use o3::{
    buffer::{resident, storage::Owned},
    mem::{Lease, Rejected},
};

#[test]
fn terminal_masks() {
    use dope_sys::io::file::{raw::Directory, watch::Event};
    use dope_uring::Backend;

    let watch = <Backend as Directory>::Watch::try_new(c".").expect("native watch");

    const HEADER: usize = mem::size_of::<libc::inotify_event>();
    let masks = [
        libc::IN_Q_OVERFLOW,
        libc::IN_MOVE_SELF,
        libc::IN_UNMOUNT | libc::IN_ISDIR,
    ];
    let mut bytes = [0; 1 + HEADER * 3];
    for (index, mask) in masks.into_iter().enumerate() {
        let offset = 1 + index * HEADER + mem::offset_of!(libc::inotify_event, mask);
        bytes[offset..offset + 4].copy_from_slice(&mask.to_ne_bytes());
    }
    // SAFETY: each complete initialized header has zero name length and a nonzero mask.
    let mut events = unsafe { <Backend as Directory>::watch_events(&watch, &bytes[1..]) };
    assert_eq!(events.next(), Some(Event::Overflow));
    for mask in &masks[1..] {
        assert_eq!(
            events.next(),
            Some(Event::Invalidated(NonZero::new(*mask).expect("mask")))
        );
    }
    assert_eq!(events.next(), None);
}

#[test]
fn watch_registration() -> io::Result<()> {
    use dope::core::{
        Backend,
        dope_sys::io::file::{raw::Directory, watch::Event},
        executor::drive,
    };
    use dope_test::harness::support::file;

    const LIMIT: Duration = Duration::from_secs(5);
    const CONFIG: settings::Config = settings::Config::new(
        settings::QueueLayout::fixed::<64, 128>(),
        settings::Schedule::fixed::<16, 1>(),
        settings::FileSlots::fixed::<0, 256>(),
        settings::Receive::fixed::<2, 4096>(),
        settings::Domain::ONE,
        settings::Progress::BatchedWhenSupported,
    );
    let dir = file::Directory::try_with(&env::temp_dir(), "fiber_file_watch", |result| {
        result.expect("remove fixture")
    })
    .expect("file fixture");
    fs::write(dir.path().join("data"), b"abc")?;
    let native = <Backend as Directory>::Watch::try_new(dir.as_ref()).expect("watch admission");
    fs::rename(dir.path().join("data"), dir.path().join("first")).expect("bootstrap event");
    let layout = read::Layout::<KeyTag<43>>::try_new(NonZero::<u32>::MIN).expect("one request");
    let mut reports = Events::default();
    Executor(
        (),
        Needs::from_tree(&layout)
            .and_then(|needs| needs.apply_to(CONFIG))
            .expect("watch layout"),
    )
    .try_run(&mut reports, |core| {
        let port = layout
            .try_port::<read::Release<Owned<resident::Budget<'_>>>>()
            .expect("request slots");
        let reader = read::Reader::<KeyTag<43>>::try_new(&port, core.driver()).expect("reader");
        let budget = core
            .driver()
            .storage()
            .budget(Resident::bytes(512))
            .expect("resident budget");
        let output = Owned::try_allocate(&budget, 8).expect("small output");
        let request =
            read::Read::try_new(native, Lease::open(read::Release::default(), output), ())
                .map_err(Rejected::discard)
                .expect("nonempty read");
        Session::run_for(core, reader, LIMIT, |app| {
            let result = app
                .drive_on(LIMIT, Operation::new(&port, request))
                .expect("small read")
                .map_err(Rejected::discard)
                .expect("read admission");
            let (request, cause) = result.err().expect("small record").into_parts();
            assert_eq!(cause, read::Error::System(Errno::INVALID_ARGUMENT));
            let (native, output, ()) = request.into_parts();
            drop(output);
            let output = Owned::try_allocate(&budget, 512).expect("record buffer");
            let address = output.as_ref().as_ptr();
            let mut request =
                read::Read::try_new(native, Lease::open(read::Release::default(), output), ())
                    .map_err(Rejected::discard)
                    .expect("record capacity");
            for name in [c"first", c"second"] {
                let mut op = Task::new(Operation::new(&port, request));
                if name == c"second" {
                    assert!(
                        app.drive_on(LIMIT, fibers::TEST.poll_once(Pin::new(&mut op)),)
                            .expect("empty read admitted")
                            .is_none()
                    );
                    assert!(matches!(
                        app.run(Duration::from_millis(1)),
                        Err(drive::Error::Timeout)
                    ));
                    fs::rename(dir.path().join("first"), dir.path().join("second"))
                        .expect("rename");
                }
                let batch = app
                    .drive_on(LIMIT, Pin::new(&mut op))
                    .expect("watch completes")
                    .map_err(Rejected::discard)
                    .expect("read admission")
                    .map_err(Rejected::discard)
                    .expect("native records");
                let mut events = batch.events();
                assert!(matches!(
                    events.next(),
                    Some(Event::MovedIn(bytes)) if bytes.starts_with(name.to_bytes_with_nul())
                ));
                assert_eq!(events.next(), None);
                request = batch.into_read();
                assert_eq!(request.output().as_ref().as_ptr(), address);
            }
            let moved = dir.path().with_extension("moved");
            fs::rename(dir.path(), &moved).expect("move parent");
            fs::rename(&moved, dir.path()).expect("restore fixture");
            let batch = app
                .drive_on(LIMIT, Operation::new(&port, request))
                .expect("parent event")
                .map_err(Rejected::discard)
                .expect("read admission")
                .map_err(Rejected::discard)
                .expect("native records");
            assert_eq!(
                batch.events().next(),
                Some(Event::Invalidated(
                    NonZero::new(libc::IN_MOVE_SELF).expect("mask"),
                ))
            );
            let (native, output, ()) = batch.into_read().into_parts();
            drop(native);
            let native =
                <Backend as Directory>::Watch::try_new(dir.as_ref()).expect("new registration");
            let request = read::Read::try_new(native, output, ())
                .map_err(Rejected::discard)
                .expect("reuse buffer");
            let mut op = Task::new(Operation::new(&port, request));
            assert!(
                app.drive_on(LIMIT, fibers::TEST.poll_once(Pin::new(&mut op)),)
                    .expect("empty read admitted")
                    .is_none()
            );
            assert!(matches!(
                app.run(Duration::from_millis(1)),
                Err(drive::Error::Timeout)
            ));
            drop(op);
            assert_eq!(budget.resident(), 512);
        })
        .expect("native quiescence");
        assert_eq!(budget.resident(), 0);
    })
    .expect("native lifecycle");
    assert!(
        reports.0.is_empty(),
        "unexpected reclaimed operations: {:?}",
        reports.0
    );
    fs::remove_file(dir.path().join("second")).expect("fixture cleanup");
    Ok(())
}