artifactize-core 0.27.1

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Listener options shared across operating systems.
use std::{io, net::SocketAddr};

use socket2::{Domain, Protocol, Socket, Type};
use tokio::net::TcpListener;

/// The HTTP server owns its address on every OS and can serve IPv4 on an IPv6 wildcard.
pub(crate) fn http_listener(address: SocketAddr) -> io::Result<TcpListener> {
    // Keep Tokio's normal server accept queue size for bursts of requests.
    const HTTP_BACKLOG: i32 = 1024;
    listen(address, HTTP_BACKLOG)
}

fn listen(address: SocketAddr, backlog: i32) -> io::Result<TcpListener> {
    let socket = Socket::new(
        Domain::for_address(address),
        Type::STREAM,
        Some(Protocol::TCP),
    )?;
    if address.is_ipv6() {
        socket.set_only_v6(false)?;
    }
    #[cfg(windows)]
    exclusive(&socket)?;
    socket.bind(&address.into())?;
    socket.listen(backlog)?;
    socket.set_nonblocking(true)?;
    TcpListener::from_std(socket.into())
}

#[cfg(windows)]
fn exclusive(socket: &Socket) -> io::Result<()> {
    use std::os::windows::io::AsRawSocket;
    use windows_sys::Win32::Networking::WinSock::{
        SO_EXCLUSIVEADDRUSE, SOCKET_ERROR, SOL_SOCKET, WSAGetLastError, setsockopt,
    };
    let enabled: i32 = 1;
    // SAFETY: the socket is live; the pointer and length describe an initialized BOOL
    // for the duration of this synchronous Winsock call, which does not retain it.
    let result = unsafe {
        setsockopt(
            socket.as_raw_socket() as _,
            SOL_SOCKET,
            SO_EXCLUSIVEADDRUSE,
            (&enabled as *const i32).cast(),
            std::mem::size_of_val(&enabled) as i32,
        )
    };
    if result == SOCKET_ERROR {
        // SAFETY: WSAGetLastError has no preconditions; read immediately after failure.
        Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }))
    } else {
        Ok(())
    }
}