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/flight.rs

//! **The Arrow Flight door** (native clients).
//!
//! * `DoGet`: ticket = JSON `{"region","bbox":[minlon,minlat,maxlon,maxlat],"lod","kind","max"}`
//!   (`max` optional) → the same schema and batches the HTTP door sends. Batches are never
//!   split for gRPC size, so a client sees the same batch boundaries; a client sets its
//!   decoding limit (`max_decoding_message_size`) to what one batch can weigh.
//! * `ListFlights`: one `FlightInfo` per region; descriptor path `[name]`, `app_metadata` =
//!   the region's `/v1/regions` JSON object.
//!
//! The other Flight methods are not in the contract and answer `korp-map-112`.

use std::sync::Arc;

use arrow_array::RecordBatch;
use arrow_flight::encode::FlightDataEncoderBuilder;
use arrow_flight::error::FlightError;
use arrow_flight::flight_service_server::FlightService;
use arrow_flight::{
    Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo,
    HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket,
};
use futures::stream::{self, BoxStream, StreamExt};
use tokio::sync::mpsc;
use tonic::{Request, Response, Status, Streaming};

use crate::error::{Code, WireError};
use crate::server::ServerConfig;
use crate::source::{MapQuery, MapSource};

/// The Flight service over a [`MapSource`].
pub struct FlightDoor<S> {
    source: Arc<S>,
    cfg: Arc<ServerConfig>,
}

impl<S> FlightDoor<S> {
    /// A door over `source`.
    pub fn new(source: Arc<S>, cfg: Arc<ServerConfig>) -> Self {
        Self { source, cfg }
    }
}

/// The query a ticket names, with the server's default `max` applied.
pub fn query_from_ticket(ticket: &[u8], cfg: &ServerConfig) -> Result<MapQuery, WireError> {
    let mut q: MapQuery = serde_json::from_slice(ticket).map_err(|e| {
        WireError::new(
            Code::BadTicket,
            format!("ticket is not the map query JSON: {e}"),
        )
    })?;
    if q.max.is_none() {
        q.max = cfg.default_max;
    }
    q.validate()?;
    Ok(q)
}

fn unimplemented(what: &str) -> Status {
    WireError::new(
        Code::Unimplemented,
        format!("Flight {what} is not part of the map wire"),
    )
    .to_status()
}

#[tonic::async_trait]
impl<S: MapSource> FlightService for FlightDoor<S> {
    type HandshakeStream = BoxStream<'static, Result<HandshakeResponse, Status>>;
    type ListFlightsStream = BoxStream<'static, Result<FlightInfo, Status>>;
    type DoGetStream = BoxStream<'static, Result<FlightData, Status>>;
    type DoPutStream = BoxStream<'static, Result<PutResult, Status>>;
    type DoActionStream = BoxStream<'static, Result<arrow_flight::Result, Status>>;
    type ListActionsStream = BoxStream<'static, Result<ActionType, Status>>;
    type DoExchangeStream = BoxStream<'static, Result<FlightData, Status>>;

    async fn list_flights(
        &self,
        _r: Request<Criteria>,
    ) -> Result<Response<Self::ListFlightsStream>, Status> {
        let s = self.source.clone();
        let regions = tokio::task::spawn_blocking(move || s.regions())
            .await
            .map_err(|e| WireError::new(Code::SourceFailed, format!("regions task: {e}")))??;
        let mut infos = Vec::with_capacity(regions.len());
        for r in regions {
            let md = serde_json::to_vec(&r)
                .map_err(|e| WireError::new(Code::EncodeFailed, format!("region json: {e}")))?;
            infos.push(Ok(FlightInfo::new()
                .with_descriptor(FlightDescriptor::new_path(vec![r.name.clone()]))
                .with_app_metadata(md)));
        }
        Ok(Response::new(stream::iter(infos).boxed()))
    }

    async fn do_get(&self, r: Request<Ticket>) -> Result<Response<Self::DoGetStream>, Status> {
        let q = query_from_ticket(&r.get_ref().ticket, &self.cfg)?;
        let s = self.source.clone();
        let qq = q.clone();
        let reply = tokio::task::spawn_blocking(move || s.query(&qq))
            .await
            .map_err(|e| WireError::new(Code::SourceFailed, format!("query task: {e}")))??;
        let (schema, _meta, batches) = reply.into_parts();
        let (tx, rx) = mpsc::channel::<Result<RecordBatch, FlightError>>(4);
        tokio::task::spawn_blocking(move || {
            for b in batches {
                let item = b.map_err(|e| FlightError::Tonic(Box::new(e.to_status())));
                let stop = item.is_err();
                if tx.blocking_send(item).is_err() || stop {
                    return;
                }
            }
        });
        let input = stream::unfold(rx, |mut rx| async move { rx.recv().await.map(|v| (v, rx)) });
        let out = FlightDataEncoderBuilder::new()
            .with_schema(schema)
            .with_max_flight_data_size(usize::MAX)
            .build(input)
            .map(|r| r.map_err(Status::from));
        Ok(Response::new(out.boxed()))
    }

    async fn handshake(
        &self,
        _r: Request<Streaming<HandshakeRequest>>,
    ) -> Result<Response<Self::HandshakeStream>, Status> {
        Err(unimplemented("Handshake"))
    }
    async fn get_flight_info(
        &self,
        _r: Request<FlightDescriptor>,
    ) -> Result<Response<FlightInfo>, Status> {
        Err(unimplemented("GetFlightInfo"))
    }
    async fn poll_flight_info(
        &self,
        _r: Request<FlightDescriptor>,
    ) -> Result<Response<PollInfo>, Status> {
        Err(unimplemented("PollFlightInfo"))
    }
    async fn get_schema(
        &self,
        _r: Request<FlightDescriptor>,
    ) -> Result<Response<SchemaResult>, Status> {
        Err(unimplemented("GetSchema"))
    }
    async fn do_put(
        &self,
        _r: Request<Streaming<FlightData>>,
    ) -> Result<Response<Self::DoPutStream>, Status> {
        Err(unimplemented("DoPut"))
    }
    async fn do_action(
        &self,
        _r: Request<Action>,
    ) -> Result<Response<Self::DoActionStream>, Status> {
        Err(unimplemented("DoAction"))
    }
    async fn list_actions(
        &self,
        _r: Request<Empty>,
    ) -> Result<Response<Self::ListActionsStream>, Status> {
        Err(unimplemented("ListActions"))
    }
    async fn do_exchange(
        &self,
        _r: Request<Streaming<FlightData>>,
    ) -> Result<Response<Self::DoExchangeStream>, Status> {
        Err(unimplemented("DoExchange"))
    }
}