Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/server.rs

//! **Both doors on one port.** A connection speaks HTTP/1.1 or HTTP/2 (h2c); a request
//! whose `content-type` starts with `application/grpc` goes to the Flight service, every
//! other request to the HTTP door.

use std::convert::Infallible;
use std::sync::Arc;

use arrow_flight::flight_service_server::FlightServiceServer;
use http::{Request, Response, header};
use http_body_util::BodyExt;
use hyper::body::Incoming;
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto;
use tokio::net::TcpListener;
use tonic::codegen::Service;

use crate::flight::FlightDoor;
use crate::http::{self as door, Body};
use crate::source::MapSource;

/// What the server is told at start.
#[derive(Clone, Debug)]
pub struct ServerConfig {
    /// `Access-Control-Allow-Origin` on every HTTP response; `None` sends none.
    pub cors_origin: Option<String>,
    /// The row cap a query without `max` gets; `None` = no cap.
    pub default_max: Option<u64>,
    /// One stderr line per answered map query (rows, bytes, timings).
    pub log: bool,
    /// `Cache-Control: public, max-age=<s>` on the map and address replies; `None`
    /// sends no `Cache-Control` (the `ETag` is sent either way).
    pub cache_max_age: Option<u32>,
    /// The same for `/v1/regions`, which changes when a region is (re)provisioned.
    pub regions_max_age: Option<u32>,
    /// One line naming the server build, shown on the landing page.
    pub about: Option<String>,
    /// **The server build**, hashed into every map, address and region `ETag`: another
    /// build may write other bytes for the same data and query (a new encoder, a
    /// dependency bump), so it must never revalidate an older build's tag. A binary sets
    /// it to an id of its own build; the default is this crate's version.
    pub build_id: String,
    /// The files served under `/v1/files/` (none by default).
    pub files: std::sync::Arc<crate::files::FileShelf>,
    /// **Map replies computed at once.** A map reply holds a slot while its query runs
    /// and its bytes are encoded, off the async threads; a request beyond the slots waits
    /// for one holding no thread, and every other route answers meanwhile. The default
    /// is the machine's threads ([`default_work_slots`]): a reply is CPU work, and more
    /// of them at once only share the same cores while holding more memory.
    pub work_slots: Arc<tokio::sync::Semaphore>,
}

/// The default number of map replies computed at once: the machine's threads.
#[must_use]
pub fn default_work_slots() -> usize {
    std::thread::available_parallelism().map_or(4, |n| n.get())
}

impl Default for ServerConfig {
    /// The dev defaults: CORS `*`, 500 000 rows, logging on, replies cached for an hour
    /// and the region list for a minute, one map reply computed per thread.
    fn default() -> Self {
        Self {
            cors_origin: Some("*".to_string()),
            default_max: Some(500_000),
            log: true,
            cache_max_age: Some(3600),
            regions_max_age: Some(60),
            about: None,
            build_id: concat!("korp-map-wire ", env!("CARGO_PKG_VERSION")).to_string(),
            files: std::sync::Arc::default(),
            work_slots: Arc::new(tokio::sync::Semaphore::new(default_work_slots())),
        }
    }
}

fn is_grpc<B>(req: &Request<B>) -> bool {
    req.headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.starts_with("application/grpc"))
}

/// How long a failed accept waits before the next.
pub const ACCEPT_RETRY: std::time::Duration = std::time::Duration::from_millis(100);

/// The next connection on `listener`. A failed accept (out of file descriptors, a
/// connection reset before it was taken) is printed and retried: it drops nothing that
/// is being served, and the listener never takes the process down.
pub(crate) async fn accept_retrying(listener: &TcpListener) -> tokio::net::TcpStream {
    loop {
        match listener.accept().await {
            Ok((tcp, _peer)) => return tcp,
            Err(e) => {
                eprintln!("korp-map-wire: accept: {e} (retrying)");
                tokio::time::sleep(ACCEPT_RETRY).await;
            }
        }
    }
}

/// Serve `source` on `listener` until the task is dropped. Never returns on its own: a
/// failed accept is retried ([`accept_retrying`]).
pub async fn serve<S: MapSource>(listener: TcpListener, source: Arc<S>, cfg: ServerConfig) {
    let doors = Doors::new(source, cfg);
    loop {
        let stream = accept_retrying(&listener).await;
        let doors = doors.clone();
        tokio::spawn(async move { doors.serve_connection(stream).await });
    }
}

/// How long a TLS handshake may take before the connection is dropped.
#[cfg(feature = "tls")]
pub const HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// **Serve `source` over HTTPS** on `listener` until the task is dropped: each
/// connection's TLS handshake through `tls`, then the same two doors as [`serve`]
/// (HTTP/1.1, or HTTP/2 when ALPN picks `h2`, which Flight needs). A failed handshake
/// drops that connection only, and a failed accept (e.g. out of file descriptors) is
/// printed and retried: the HTTPS door never takes the process down.
#[cfg(feature = "tls")]
pub async fn serve_tls<S: MapSource, A: crate::tls::TlsAccept>(
    listener: TcpListener,
    tls: Arc<A>,
    source: Arc<S>,
    cfg: ServerConfig,
) {
    let doors = Doors::new(source, cfg);
    loop {
        let tcp = accept_retrying(&listener).await;
        let (doors, tls) = (doors.clone(), tls.clone());
        tokio::spawn(async move {
            // An ACME challenge (answered), a failed handshake, or one that took too long:
            // nothing to serve on that connection.
            if let Ok(Ok(Some(stream))) =
                tokio::time::timeout(HANDSHAKE_TIMEOUT, tls.accept(tcp)).await
            {
                doors.serve_connection(stream).await;
            }
        });
    }
}

/// The two doors over one source, shared by every connection.
struct Doors<S: MapSource> {
    source: Arc<S>,
    cfg: Arc<ServerConfig>,
    flight: FlightServiceServer<FlightDoor<S>>,
}

impl<S: MapSource> Clone for Doors<S> {
    fn clone(&self) -> Self {
        Self {
            source: self.source.clone(),
            cfg: self.cfg.clone(),
            flight: self.flight.clone(),
        }
    }
}

impl<S: MapSource> Doors<S> {
    fn new(source: Arc<S>, cfg: ServerConfig) -> Self {
        let cfg = Arc::new(cfg);
        let flight = FlightServiceServer::new(FlightDoor::new(source.clone(), cfg.clone()));
        Self {
            source,
            cfg,
            flight,
        }
    }

    /// Serve one connection (plain or TLS) until it closes.
    async fn serve_connection<IO>(self, io: IO)
    where
        IO: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
    {
        let Self {
            source,
            cfg,
            flight,
        } = self;
        let svc = hyper::service::service_fn(move |req: Request<Incoming>| {
            let (source, cfg, mut flight) = (source.clone(), cfg.clone(), flight.clone());
            async move {
                let r: Response<Body> = if is_grpc(&req) {
                    match flight.call(req).await {
                        Ok(r) => r.map(|b| b.map_err(Into::into).boxed_unsync()),
                        Err(never) => match never {},
                    }
                } else {
                    door::handle(source, cfg, req).await
                };
                Ok::<_, Infallible>(r)
            }
        });
        if let Err(e) = auto::Builder::new(TokioExecutor::new())
            .serve_connection(TokioIo::new(io), svc)
            .await
        {
            let msg = e.to_string();
            if !msg.contains("connection closed") && !msg.contains("reset") {
                eprintln!("korp-map-wire: connection: {msg}");
            }
        }
    }
}