second-brain-api 0.13.2

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
use std::io;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raised {
    pub from: libc::rlim_t,
    pub to: libc::rlim_t,
}

/// Raises the soft `RLIMIT_NOFILE` to the hard limit, never lowering it.
/// launchd starts the daemon at 256 and systemd at 1024, while every tantivy
/// segment keeps its files open, so two indexes alone can exhaust 256.
pub fn raise_open_file_limit() -> io::Result<Raised> {
    let mut limit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
        return Err(io::Error::last_os_error());
    }
    let from = limit.rlim_cur;
    let to = ceiling(limit.rlim_max)?;
    if to <= from {
        return Ok(Raised { from, to: from });
    }
    limit.rlim_cur = to;
    if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) } != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(Raised { from, to })
}

/// macOS rejects a soft limit above `kern.maxfilesperproc` even when the
/// hard limit is unlimited.
#[cfg(target_vendor = "apple")]
fn ceiling(hard: libc::rlim_t) -> io::Result<libc::rlim_t> {
    let mut per_process: libc::c_int = 0;
    let mut size = std::mem::size_of::<libc::c_int>();
    let found = unsafe {
        libc::sysctlbyname(
            c"kern.maxfilesperproc".as_ptr(),
            (&mut per_process as *mut libc::c_int).cast(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if found != 0 {
        return Err(io::Error::last_os_error());
    }
    let per_process = libc::rlim_t::try_from(per_process)
        .map_err(|_| io::Error::other(format!("kern.maxfilesperproc is {per_process}")))?;
    Ok(hard.min(per_process))
}

#[cfg(not(target_vendor = "apple"))]
fn ceiling(hard: libc::rlim_t) -> io::Result<libc::rlim_t> {
    Ok(hard)
}