1mod dict;
2mod guard;
3
4use std::net::SocketAddr;
5use std::sync::Arc;
6use std::time::Duration;
7
8use axum::Json;
9use axum::Router;
10use axum::body::Bytes;
11use axum::extract::connect_info::ConnectInfo;
12use axum::extract::rejection::{BytesRejection, FailedToBufferBody};
13use axum::extract::{DefaultBodyLimit, Query, Request, State};
14use axum::http::{HeaderValue, StatusCode, header};
15use axum::middleware::{self, Next};
16use axum::response::{IntoResponse, Response};
17use axum::routing::{get, post};
18use bengali_spell_checker::SpellChecker;
19use serde::Deserialize;
20use serde::Serialize;
21use serde_json::{Map, Number, Value};
22use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
23use tracing::Level;
24
25pub use dict::load_checker;
26pub use guard::ServerConfig;
27
28const MAX_TEXT_LENGTH: usize = 100_000;
29const MAX_WORD_UTF16: usize = 1_000;
30const DEFAULT_LIMIT: usize = 5;
31const BLOCKING_CHARS: usize = 10_000;
32const LIMIT_ERROR: &str = "limit must be an integer from 1 to 20";
33
34pub struct Config {
35 pub host: String,
36 pub port: u16,
37 pub dict: std::path::PathBuf,
38}
39
40impl Config {
41 pub fn from_env() -> Result<Self, String> {
42 Ok(Self {
43 host: host_from_env()?,
44 port: port_from_env()?,
45 dict: dict::dict_dir()?,
46 })
47 }
48}
49
50pub fn router(checker: Arc<SpellChecker>) -> Router {
51 router_with(checker, ServerConfig::default())
52}
53
54pub fn router_with(checker: Arc<SpellChecker>, server: ServerConfig) -> Router {
55 let timeout = server.request_timeout;
56 let limiter = server.rate_limiter();
57 let max_body_bytes = server.max_body_bytes;
58 Router::new()
59 .route("/health", get(health))
60 .route("/api/health", get(health))
61 .route("/api/check", post(check))
62 .route("/api/suggest", get(suggest))
63 .layer(DefaultBodyLimit::max(max_body_bytes))
64 .layer(middleware::from_fn(move |req: Request, next: Next| {
65 let timeout = timeout;
66 async move { apply_timeout(req, next, timeout).await }
67 }))
68 .layer(middleware::from_fn(move |req: Request, next: Next| {
69 let limiter = limiter.clone();
70 async move {
71 let peer = req
72 .extensions()
73 .get::<ConnectInfo<SocketAddr>>()
74 .map(|info| info.0.ip());
75 if let Err(retry_after) = limiter.check(req.uri().path(), req.headers(), peer) {
76 let mut response = error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
77 if let Ok(value) = HeaderValue::from_str(&retry_after.to_string()) {
78 response.headers_mut().insert(header::RETRY_AFTER, value);
79 }
80 return response;
81 }
82 next.run(req).await
83 }
84 }))
85 .layer(server.cors_layer())
86 .layer(
87 TraceLayer::new_for_http()
88 .make_span_with(DefaultMakeSpan::new().level(Level::INFO))
89 .on_request(())
90 .on_response(DefaultOnResponse::new().level(Level::INFO))
91 .on_body_chunk(())
92 .on_eos(())
93 .on_failure(()),
94 )
95 .with_state(AppState {
96 checker,
97 max_body_bytes,
98 })
99}
100
101async fn apply_timeout(req: Request, next: Next, timeout: Duration) -> Response {
102 match tokio::time::timeout(timeout, next.run(req)).await {
103 Ok(response) => response,
104 Err(_) => error(StatusCode::REQUEST_TIMEOUT, "request timed out"),
105 }
106}
107
108#[derive(Clone)]
109struct AppState {
110 checker: Arc<SpellChecker>,
111 max_body_bytes: usize,
112}
113
114#[derive(Serialize)]
115struct Health {
116 ready: bool,
117}
118
119#[derive(Serialize)]
120struct ErrorBody {
121 error: String,
122}
123
124#[derive(Serialize)]
125struct CheckResponse {
126 misspellings: Vec<Misspelling>,
127}
128
129#[derive(Serialize)]
130struct Misspelling {
131 word: String,
132 start: usize,
133 end: usize,
134 #[serde(skip_serializing_if = "Option::is_none")]
135 suggestions: Option<Vec<String>>,
136}
137
138#[derive(Serialize)]
139struct SuggestResponse {
140 word: String,
141 correct: bool,
142 suggestions: Vec<String>,
143}
144
145#[derive(Deserialize)]
146struct SuggestQuery {
147 word: Option<String>,
148 limit: Option<String>,
149 strict: Option<String>,
150}
151
152async fn health() -> Json<Health> {
153 Json(Health { ready: true })
154}
155
156async fn check(State(state): State<AppState>, body: Result<Bytes, BytesRejection>) -> Response {
157 let body = match body {
158 Ok(body) => body,
159 Err(rejection) => return buffer_error(rejection, state.max_body_bytes),
160 };
161 let value: Value = match serde_json::from_slice(&body) {
162 Ok(value) => value,
163 Err(_) => return error(StatusCode::BAD_REQUEST, "Invalid JSON"),
164 };
165 let Some(body) = value.as_object() else {
166 return error(StatusCode::BAD_REQUEST, "text must be a string");
167 };
168 let Some(text) = body.get("text").and_then(Value::as_str) else {
169 return error(StatusCode::BAD_REQUEST, "text must be a string");
170 };
171 let lengths = text_lengths(text);
172 if lengths.utf16 > MAX_TEXT_LENGTH {
174 return error(
175 StatusCode::PAYLOAD_TOO_LARGE,
176 "text must be at most 100000 characters",
177 );
178 }
179 let include_suggestions = match body.get("suggestions") {
180 None => true,
181 Some(Value::Bool(value)) => *value,
182 Some(_) => return error(StatusCode::BAD_REQUEST, "suggestions must be a boolean"),
183 };
184 let Ok(strict) = json_bool(body, "strict") else {
185 return error(StatusCode::BAD_REQUEST, "strict must be a boolean");
186 };
187 let Ok(limit) = json_limit(body) else {
188 return error(StatusCode::BAD_REQUEST, LIMIT_ERROR);
189 };
190
191 let text = text.to_owned();
192 let misspellings = if lengths.chars > BLOCKING_CHARS {
193 let checker = Arc::clone(&state.checker);
194 match tokio::task::spawn_blocking(move || {
195 misspellings_for(&checker, &text, include_suggestions, limit, strict)
196 })
197 .await
198 {
199 Ok(misspellings) => misspellings,
200 Err(_) => return error(StatusCode::INTERNAL_SERVER_ERROR, "internal error"),
201 }
202 } else {
203 misspellings_for(&state.checker, &text, include_suggestions, limit, strict)
204 };
205 Json(CheckResponse { misspellings }).into_response()
206}
207
208async fn suggest(State(state): State<AppState>, Query(params): Query<SuggestQuery>) -> Response {
209 let Some(word) = params.word.filter(|word| !word.is_empty()) else {
210 return error(StatusCode::BAD_REQUEST, "word is required");
211 };
212 if text_lengths(&word).utf16 > MAX_WORD_UTF16 {
213 return error(
214 StatusCode::UNPROCESSABLE_ENTITY,
215 "word must be at most 1000 characters",
216 );
217 }
218 let Ok(limit) = query_limit(params.limit.as_deref()) else {
219 return error(StatusCode::BAD_REQUEST, LIMIT_ERROR);
220 };
221 let Ok(strict) = query_bool(params.strict.as_deref()) else {
222 return error(StatusCode::BAD_REQUEST, "strict must be a boolean");
223 };
224 let correct = state.checker.correct_with(&word, strict);
225 let suggestions = if correct {
226 Vec::new()
227 } else {
228 state.checker.suggest_with(&word, limit, strict)
229 };
230 Json(SuggestResponse {
231 word,
232 correct,
233 suggestions,
234 })
235 .into_response()
236}
237
238fn misspellings_for(
239 checker: &SpellChecker,
240 text: &str,
241 include_suggestions: bool,
242 limit: usize,
243 strict: bool,
244) -> Vec<Misspelling> {
245 checker
246 .check_with(text, strict)
247 .into_iter()
248 .map(|token| {
249 let suggestions =
250 include_suggestions.then(|| checker.suggest_with(&token.word, limit, strict));
251 Misspelling {
252 word: token.word,
253 start: token.start_utf16,
254 end: token.end_utf16,
255 suggestions,
256 }
257 })
258 .collect()
259}
260
261fn text_lengths(text: &str) -> TextLengths {
262 let mut chars = 0;
263 let mut utf16 = 0;
264 for ch in text.chars() {
265 chars += 1;
266 utf16 += ch.len_utf16();
267 }
268 TextLengths { chars, utf16 }
269}
270
271struct TextLengths {
272 chars: usize,
273 utf16: usize,
274}
275
276fn json_bool(body: &Map<String, Value>, key: &str) -> Result<bool, ()> {
277 match body.get(key) {
278 None => Ok(false),
279 Some(Value::Bool(value)) => Ok(*value),
280 Some(_) => Err(()),
281 }
282}
283
284fn query_bool(value: Option<&str>) -> Result<bool, ()> {
285 match value {
286 None => Ok(false),
287 Some("true") => Ok(true),
288 Some("false") => Ok(false),
289 Some(_) => Err(()),
290 }
291}
292
293fn json_limit(body: &Map<String, Value>) -> Result<usize, ()> {
294 match body.get("limit") {
295 None => Ok(DEFAULT_LIMIT),
296 Some(Value::Number(number)) => integer_limit(number),
297 Some(_) => Err(()),
298 }
299}
300
301fn integer_limit(number: &Number) -> Result<usize, ()> {
302 if let Some(value) = number.as_u64() {
303 return limit_in_range(value);
304 }
305 let Some(value) = number.as_f64() else {
306 return Err(());
307 };
308 if value.fract() == 0.0 && (1.0..=20.0).contains(&value) {
309 Ok(value as usize)
310 } else {
311 Err(())
312 }
313}
314
315fn query_limit(value: Option<&str>) -> Result<usize, ()> {
316 let Some(value) = value else {
317 return Ok(DEFAULT_LIMIT);
318 };
319 if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
320 return Err(());
321 }
322 let Ok(parsed) = value.parse::<u64>() else {
323 return Err(());
324 };
325 limit_in_range(parsed)
326}
327
328fn limit_in_range(value: u64) -> Result<usize, ()> {
329 if (1..=20).contains(&value) {
330 Ok(value as usize)
331 } else {
332 Err(())
333 }
334}
335
336fn buffer_error(rejection: BytesRejection, max_body_bytes: usize) -> Response {
337 match rejection {
338 BytesRejection::FailedToBufferBody(FailedToBufferBody::LengthLimitError(_)) => error(
339 StatusCode::PAYLOAD_TOO_LARGE,
340 format!("request body must be at most {max_body_bytes} bytes"),
341 ),
342 BytesRejection::FailedToBufferBody(FailedToBufferBody::UnknownBodyError(_)) => {
343 error(StatusCode::BAD_REQUEST, "failed to read request body")
344 }
345 _ => error(StatusCode::BAD_REQUEST, "failed to read request body"),
347 }
348}
349
350fn error(status: StatusCode, message: impl Into<String>) -> Response {
351 (
352 status,
353 Json(ErrorBody {
354 error: message.into(),
355 }),
356 )
357 .into_response()
358}
359
360fn host_from_env() -> Result<String, String> {
361 match std::env::var("HOST") {
362 Err(std::env::VarError::NotPresent) => Ok("0.0.0.0".to_string()),
363 Err(std::env::VarError::NotUnicode(_)) => Err("HOST is not valid Unicode".to_string()),
364 Ok(value) if value.is_empty() => Ok("0.0.0.0".to_string()),
365 Ok(value) => Ok(value),
366 }
367}
368
369fn port_from_env() -> Result<u16, String> {
370 match std::env::var("PORT") {
371 Err(std::env::VarError::NotPresent) => Ok(8787),
372 Err(std::env::VarError::NotUnicode(_)) => Err("PORT is not valid Unicode".to_string()),
373 Ok(value) => value
374 .parse::<u16>()
375 .map_err(|_| format!("invalid PORT: {value}")),
376 }
377}
378
379#[cfg(test)]
380mod tests;