bnspell-api 0.1.0

HTTP API for the Bengali spell checker
Documentation
mod dict;
mod guard;

use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use axum::Json;
use axum::Router;
use axum::body::Bytes;
use axum::extract::connect_info::ConnectInfo;
use axum::extract::rejection::{BytesRejection, FailedToBufferBody};
use axum::extract::{DefaultBodyLimit, Query, Request, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use bengali_spell_checker::SpellChecker;
use serde::Deserialize;
use serde::Serialize;
use serde_json::{Map, Number, Value};
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
use tracing::Level;

pub use dict::load_checker;
pub use guard::ServerConfig;

const MAX_TEXT_LENGTH: usize = 100_000;
const MAX_WORD_UTF16: usize = 1_000;
const DEFAULT_LIMIT: usize = 5;
const BLOCKING_CHARS: usize = 10_000;
const LIMIT_ERROR: &str = "limit must be an integer from 1 to 20";

pub struct Config {
    pub host: String,
    pub port: u16,
    pub dict: std::path::PathBuf,
}

impl Config {
    pub fn from_env() -> Result<Self, String> {
        Ok(Self {
            host: host_from_env()?,
            port: port_from_env()?,
            dict: dict::dict_dir()?,
        })
    }
}

pub fn router(checker: Arc<SpellChecker>) -> Router {
    router_with(checker, ServerConfig::default())
}

pub fn router_with(checker: Arc<SpellChecker>, server: ServerConfig) -> Router {
    let timeout = server.request_timeout;
    let limiter = server.rate_limiter();
    let max_body_bytes = server.max_body_bytes;
    Router::new()
        .route("/health", get(health))
        .route("/api/health", get(health))
        .route("/api/check", post(check))
        .route("/api/suggest", get(suggest))
        .layer(DefaultBodyLimit::max(max_body_bytes))
        .layer(middleware::from_fn(move |req: Request, next: Next| {
            let timeout = timeout;
            async move { apply_timeout(req, next, timeout).await }
        }))
        .layer(middleware::from_fn(move |req: Request, next: Next| {
            let limiter = limiter.clone();
            async move {
                let peer = req
                    .extensions()
                    .get::<ConnectInfo<SocketAddr>>()
                    .map(|info| info.0.ip());
                if let Err(retry_after) = limiter.check(req.uri().path(), req.headers(), peer) {
                    let mut response = error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
                    if let Ok(value) = HeaderValue::from_str(&retry_after.to_string()) {
                        response.headers_mut().insert(header::RETRY_AFTER, value);
                    }
                    return response;
                }
                next.run(req).await
            }
        }))
        .layer(server.cors_layer())
        .layer(
            TraceLayer::new_for_http()
                .make_span_with(DefaultMakeSpan::new().level(Level::INFO))
                .on_request(())
                .on_response(DefaultOnResponse::new().level(Level::INFO))
                .on_body_chunk(())
                .on_eos(())
                .on_failure(()),
        )
        .with_state(AppState {
            checker,
            max_body_bytes,
        })
}

async fn apply_timeout(req: Request, next: Next, timeout: Duration) -> Response {
    match tokio::time::timeout(timeout, next.run(req)).await {
        Ok(response) => response,
        Err(_) => error(StatusCode::REQUEST_TIMEOUT, "request timed out"),
    }
}

#[derive(Clone)]
struct AppState {
    checker: Arc<SpellChecker>,
    max_body_bytes: usize,
}

#[derive(Serialize)]
struct Health {
    ready: bool,
}

#[derive(Serialize)]
struct ErrorBody {
    error: String,
}

#[derive(Serialize)]
struct CheckResponse {
    misspellings: Vec<Misspelling>,
}

#[derive(Serialize)]
struct Misspelling {
    word: String,
    start: usize,
    end: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    suggestions: Option<Vec<String>>,
}

#[derive(Serialize)]
struct SuggestResponse {
    word: String,
    correct: bool,
    suggestions: Vec<String>,
}

#[derive(Deserialize)]
struct SuggestQuery {
    word: Option<String>,
    limit: Option<String>,
    strict: Option<String>,
}

async fn health() -> Json<Health> {
    Json(Health { ready: true })
}

async fn check(State(state): State<AppState>, body: Result<Bytes, BytesRejection>) -> Response {
    let body = match body {
        Ok(body) => body,
        Err(rejection) => return buffer_error(rejection, state.max_body_bytes),
    };
    let value: Value = match serde_json::from_slice(&body) {
        Ok(value) => value,
        Err(_) => return error(StatusCode::BAD_REQUEST, "Invalid JSON"),
    };
    let Some(body) = value.as_object() else {
        return error(StatusCode::BAD_REQUEST, "text must be a string");
    };
    let Some(text) = body.get("text").and_then(Value::as_str) else {
        return error(StatusCode::BAD_REQUEST, "text must be a string");
    };
    let lengths = text_lengths(text);
    // JavaScript `String.length` counts UTF-16 code units.
    if lengths.utf16 > MAX_TEXT_LENGTH {
        return error(
            StatusCode::PAYLOAD_TOO_LARGE,
            "text must be at most 100000 characters",
        );
    }
    let include_suggestions = match body.get("suggestions") {
        None => true,
        Some(Value::Bool(value)) => *value,
        Some(_) => return error(StatusCode::BAD_REQUEST, "suggestions must be a boolean"),
    };
    let Ok(strict) = json_bool(body, "strict") else {
        return error(StatusCode::BAD_REQUEST, "strict must be a boolean");
    };
    let Ok(limit) = json_limit(body) else {
        return error(StatusCode::BAD_REQUEST, LIMIT_ERROR);
    };

    let text = text.to_owned();
    let misspellings = if lengths.chars > BLOCKING_CHARS {
        let checker = Arc::clone(&state.checker);
        match tokio::task::spawn_blocking(move || {
            misspellings_for(&checker, &text, include_suggestions, limit, strict)
        })
        .await
        {
            Ok(misspellings) => misspellings,
            Err(_) => return error(StatusCode::INTERNAL_SERVER_ERROR, "internal error"),
        }
    } else {
        misspellings_for(&state.checker, &text, include_suggestions, limit, strict)
    };
    Json(CheckResponse { misspellings }).into_response()
}

async fn suggest(State(state): State<AppState>, Query(params): Query<SuggestQuery>) -> Response {
    let Some(word) = params.word.filter(|word| !word.is_empty()) else {
        return error(StatusCode::BAD_REQUEST, "word is required");
    };
    if text_lengths(&word).utf16 > MAX_WORD_UTF16 {
        return error(
            StatusCode::UNPROCESSABLE_ENTITY,
            "word must be at most 1000 characters",
        );
    }
    let Ok(limit) = query_limit(params.limit.as_deref()) else {
        return error(StatusCode::BAD_REQUEST, LIMIT_ERROR);
    };
    let Ok(strict) = query_bool(params.strict.as_deref()) else {
        return error(StatusCode::BAD_REQUEST, "strict must be a boolean");
    };
    let correct = state.checker.correct_with(&word, strict);
    let suggestions = if correct {
        Vec::new()
    } else {
        state.checker.suggest_with(&word, limit, strict)
    };
    Json(SuggestResponse {
        word,
        correct,
        suggestions,
    })
    .into_response()
}

fn misspellings_for(
    checker: &SpellChecker,
    text: &str,
    include_suggestions: bool,
    limit: usize,
    strict: bool,
) -> Vec<Misspelling> {
    checker
        .check_with(text, strict)
        .into_iter()
        .map(|token| {
            let suggestions =
                include_suggestions.then(|| checker.suggest_with(&token.word, limit, strict));
            Misspelling {
                word: token.word,
                start: token.start_utf16,
                end: token.end_utf16,
                suggestions,
            }
        })
        .collect()
}

fn text_lengths(text: &str) -> TextLengths {
    let mut chars = 0;
    let mut utf16 = 0;
    for ch in text.chars() {
        chars += 1;
        utf16 += ch.len_utf16();
    }
    TextLengths { chars, utf16 }
}

struct TextLengths {
    chars: usize,
    utf16: usize,
}

fn json_bool(body: &Map<String, Value>, key: &str) -> Result<bool, ()> {
    match body.get(key) {
        None => Ok(false),
        Some(Value::Bool(value)) => Ok(*value),
        Some(_) => Err(()),
    }
}

fn query_bool(value: Option<&str>) -> Result<bool, ()> {
    match value {
        None => Ok(false),
        Some("true") => Ok(true),
        Some("false") => Ok(false),
        Some(_) => Err(()),
    }
}

fn json_limit(body: &Map<String, Value>) -> Result<usize, ()> {
    match body.get("limit") {
        None => Ok(DEFAULT_LIMIT),
        Some(Value::Number(number)) => integer_limit(number),
        Some(_) => Err(()),
    }
}

fn integer_limit(number: &Number) -> Result<usize, ()> {
    if let Some(value) = number.as_u64() {
        return limit_in_range(value);
    }
    let Some(value) = number.as_f64() else {
        return Err(());
    };
    if value.fract() == 0.0 && (1.0..=20.0).contains(&value) {
        Ok(value as usize)
    } else {
        Err(())
    }
}

fn query_limit(value: Option<&str>) -> Result<usize, ()> {
    let Some(value) = value else {
        return Ok(DEFAULT_LIMIT);
    };
    if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(());
    }
    let Ok(parsed) = value.parse::<u64>() else {
        return Err(());
    };
    limit_in_range(parsed)
}

fn limit_in_range(value: u64) -> Result<usize, ()> {
    if (1..=20).contains(&value) {
        Ok(value as usize)
    } else {
        Err(())
    }
}

fn buffer_error(rejection: BytesRejection, max_body_bytes: usize) -> Response {
    match rejection {
        BytesRejection::FailedToBufferBody(FailedToBufferBody::LengthLimitError(_)) => error(
            StatusCode::PAYLOAD_TOO_LARGE,
            format!("request body must be at most {max_body_bytes} bytes"),
        ),
        BytesRejection::FailedToBufferBody(FailedToBufferBody::UnknownBodyError(_)) => {
            error(StatusCode::BAD_REQUEST, "failed to read request body")
        }
        // axum marks the rejection enum non-exhaustive.
        _ => error(StatusCode::BAD_REQUEST, "failed to read request body"),
    }
}

fn error(status: StatusCode, message: impl Into<String>) -> Response {
    (
        status,
        Json(ErrorBody {
            error: message.into(),
        }),
    )
        .into_response()
}

fn host_from_env() -> Result<String, String> {
    match std::env::var("HOST") {
        Err(std::env::VarError::NotPresent) => Ok("0.0.0.0".to_string()),
        Err(std::env::VarError::NotUnicode(_)) => Err("HOST is not valid Unicode".to_string()),
        Ok(value) if value.is_empty() => Ok("0.0.0.0".to_string()),
        Ok(value) => Ok(value),
    }
}

fn port_from_env() -> Result<u16, String> {
    match std::env::var("PORT") {
        Err(std::env::VarError::NotPresent) => Ok(8787),
        Err(std::env::VarError::NotUnicode(_)) => Err("PORT is not valid Unicode".to_string()),
        Ok(value) => value
            .parse::<u16>()
            .map_err(|_| format!("invalid PORT: {value}")),
    }
}

#[cfg(test)]
mod tests;