littlegraph-query-api 0.2.1

Neo4j-compatible HTTP Query API for the littlegraph database
Documentation
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;

pub type Result<T> = std::result::Result<T, QueryApiError>;

#[derive(Debug, thiserror::Error)]
pub enum QueryApiError {
    #[error("invalid Query API server configuration: {0}")]
    InvalidConfiguration(String),
    #[error("Query API database error: {0}")]
    Database(String),
    #[error("Query API HTTP error: {0}")]
    Http(String),
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

#[derive(Clone, Debug)]
pub(crate) struct HttpError {
    pub(crate) status: StatusCode,
    pub(crate) code: &'static str,
    pub(crate) message: String,
    pub(crate) authenticate: bool,
}

#[derive(Serialize)]
struct ErrorEnvelope<'a> {
    errors: [ErrorBody<'a>; 1],
}

#[derive(Serialize)]
struct ErrorBody<'a> {
    code: &'a str,
    message: &'a str,
}

impl HttpError {
    pub(crate) fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
        Self {
            status,
            code,
            message: message.into(),
            authenticate: false,
        }
    }

    pub(crate) fn invalid(message: impl Into<String>) -> Self {
        Self::new(
            StatusCode::BAD_REQUEST,
            "Neo.ClientError.Request.Invalid",
            message,
        )
    }

    pub(crate) fn unauthorized(message: impl Into<String>) -> Self {
        let mut error = Self::new(
            StatusCode::UNAUTHORIZED,
            "Neo.ClientError.Security.Unauthorized",
            message,
        );
        error.authenticate = true;
        error
    }

    pub(crate) fn not_found(tx_id: &str) -> Self {
        Self::new(
            StatusCode::NOT_FOUND,
            "Neo.ClientError.Request.Invalid",
            format!(
                "Transaction with Id: \"{tx_id}\" was not found. It may have timed out and \
                 therefore rolled back or the routing header 'neo4j-cluster-affinity' was not \
                 provided."
            ),
        )
    }

    pub(crate) fn into_formatted_response(
        self,
        content_type: &'static str,
        json_lines: bool,
    ) -> Response {
        let envelope = ErrorEnvelope {
            errors: [ErrorBody {
                code: self.code,
                message: &self.message,
            }],
        };
        let mut body = if json_lines {
            serde_json::to_vec(&serde_json::json!({
                "$event": "Error",
                "_body": envelope,
            }))
        } else {
            serde_json::to_vec(&envelope)
        }
        .expect("serializing a Query API error envelope cannot fail");
        if json_lines {
            body.push(b'\n');
        }
        let mut response = (
            self.status,
            [(axum::http::header::CONTENT_TYPE, content_type)],
            body,
        )
            .into_response();
        if self.authenticate {
            response.headers_mut().insert(
                axum::http::header::WWW_AUTHENTICATE,
                axum::http::HeaderValue::from_static(
                    "Basic realm=\"Neo4j\", Bearer realm=\"Neo4j\"",
                ),
            );
        }
        response
    }
}

impl IntoResponse for HttpError {
    fn into_response(self) -> Response {
        self.into_formatted_response("application/json", false)
    }
}