laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::serve::Listener;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

/// A listener that accepts a connection only while fewer than its limit are open.
///
/// Connections past the limit wait in the operating system's accept queue, where they cost the
/// process no memory, until an open connection closes.
pub(super) struct LimitedListener {
    listener: TcpListener,
    open: Option<Arc<Semaphore>>,
}

impl LimitedListener {
    /// Accept at most `max` connections at once, or any number when `max` is `0`.
    pub(super) fn new(listener: TcpListener, max: usize) -> Self {
        Self {
            listener,
            open: (max > 0).then(|| Arc::new(Semaphore::new(max.min(Semaphore::MAX_PERMITS)))),
        }
    }
}

impl Listener for LimitedListener {
    type Io = Connection;
    type Addr = SocketAddr;

    async fn accept(&mut self) -> (Connection, SocketAddr) {
        // The semaphore is never closed, so acquiring only waits...
        let permit = match &self.open {
            Some(open) => Arc::clone(open).acquire_owned().await.ok(),
            None => None,
        };
        let (stream, address) = Listener::accept(&mut self.listener).await;

        (
            Connection {
                stream,
                _permit: permit,
            },
            address,
        )
    }

    fn local_addr(&self) -> io::Result<SocketAddr> {
        self.listener.local_addr()
    }
}

/// An accepted connection, which frees its place under the limit when hyper drops it, including
/// after an upgrade or a streamed response.
pub(super) struct Connection {
    stream: TcpStream,
    _permit: Option<OwnedSemaphorePermit>,
}

impl AsyncRead for Connection {
    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.stream).poll_read(cx, buf)
    }
}

impl AsyncWrite for Connection {
    fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.stream).poll_write(cx, buf)
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.stream).poll_write_vectored(cx, bufs)
    }

    fn is_write_vectored(&self) -> bool {
        self.stream.is_write_vectored()
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.stream).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.stream).poll_shutdown(cx)
    }
}