Skip to main content

kute_cli/
http.rs

1//! A small HTTP service over the same five read-only operations as the MCP
2//! server, and through the same code: `encode`, `decode`, `inspect`,
3//! `compare`, `discover`, plus `capabilities`. Version 1 of the interface
4//! lives under `/v1/`.
5//!
6//! It is written directly on `std::net` so that every bound is in this
7//! file: one request per connection, a fixed number of workers, a fixed
8//! queue, a deadline on reading, a cap on the header block and on the body.
9//! It does not speak TLS and does not authenticate anyone, so it listens
10//! on the loopback interface unless told otherwise, and on loopback it
11//! answers only requests addressed to a loopback host name.
12
13use crate::mcp::Server;
14use serde_json::{json, Value};
15use std::io::{Read, Write};
16use std::net::{SocketAddr, TcpListener, TcpStream};
17use std::sync::mpsc::{sync_channel, Receiver, TrySendError};
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, Instant};
20
21/// The operations a POST may name.
22pub const OPERATIONS: [&str; 5] = ["encode", "decode", "inspect", "compare", "discover"];
23
24/// Most bytes of request line and headers.
25const MAX_HEAD_BYTES: usize = 16 * 1024;
26
27/// What the service may cost, apart from the per-call limits of the
28/// operations themselves.
29#[derive(Clone, Debug)]
30pub struct Options {
31    /// Requests handled at once.
32    pub workers: usize,
33    /// Accepted connections that may wait for a worker. Past it, a
34    /// connection is answered 503 and closed.
35    pub queue: usize,
36    /// A request must arrive whole within this time, and its answer must
37    /// be taken within it.
38    pub timeout: Duration,
39    /// Longest request body.
40    pub max_body_bytes: u64,
41    /// Answer requests whatever host they name. Off, only loopback names
42    /// are answered, which keeps a web page from reaching the service
43    /// through a name it controls.
44    pub any_host: bool,
45    /// Serve the Studio page under `/studio`.
46    pub studio: bool,
47    /// Give the files of the held vocabularies to whoever asks, under
48    /// `/v1/vocabularies`. Off, those paths do not exist.
49    pub registry: bool,
50    /// Answer the five operations. Off, the service is a registry and
51    /// nothing else: no caller can make it compute.
52    pub operations: bool,
53    /// Other registries to ask for a vocabulary this one does not hold.
54    pub federation: Option<Arc<Federation>>,
55    /// The status file of a peer on this machine, read for `GET /v1/peer`.
56    pub peer_status: Option<std::path::PathBuf>,
57}
58
59/// Asking other registries, and what that may cost this one.
60///
61/// A vocabulary this registry does not hold is asked for upstream, in
62/// the order the upstreams were named, checked as `kute fetch` checks
63/// one (parsed, valid, the digest recomputed, test vectors run), and
64/// kept in memory to be given again. Every bound is here: one question
65/// upstream at a time, however many callers ask; a deadline and a size
66/// limit on each; a cache of fixed size; and a short memory of digests
67/// nobody had, so that asking for them again costs nothing.
68pub struct Federation {
69    pub upstreams: Vec<String>,
70    /// Longest wait for one upstream.
71    pub timeout: Duration,
72    /// Largest file taken from an upstream.
73    pub max_bytes: u64,
74    /// Most bytes of upstream files kept. The oldest go first.
75    pub cache_bytes: u64,
76    /// What an upstream file must pass, beyond being the content its
77    /// digest names: a signature from a key this registry trusts. With
78    /// none, a file is passed on whoever signed it or nobody.
79    check: Option<UpstreamCheck>,
80    asking: Mutex<()>,
81    kept: Mutex<std::collections::VecDeque<(String, Arc<[u8]>)>>,
82    absent: Mutex<std::collections::VecDeque<(String, Instant)>>,
83    /// For each upstream, when it last failed. One that failed is not
84    /// asked again for a while, so a slow or broken upstream named
85    /// first costs its timeout once and not on every question.
86    failed: Mutex<Vec<Option<Instant>>>,
87}
88
89pub type UpstreamCheck = Box<dyn Fn(&kute::Vocabulary) -> Result<(), String> + Send + Sync>;
90
91impl std::fmt::Debug for Federation {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.debug_struct("Federation").field("upstreams", &self.upstreams).field("check", &self.check.is_some()).finish_non_exhaustive()
94    }
95}
96
97/// How long a digest that no upstream had is remembered as absent.
98const ABSENT_FOR: Duration = Duration::from_secs(60);
99/// How long an upstream that failed, stalled or sent something else is left alone.
100const REST_FOR: Duration = Duration::from_secs(30);
101/// How many such digests are remembered.
102const ABSENT_KEPT: usize = 1024;
103
104fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
105    mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
106}
107
108impl Federation {
109    pub fn new(upstreams: Vec<String>, timeout: Duration, max_bytes: u64, cache_bytes: u64, check: Option<UpstreamCheck>) -> kute::Result<Self> {
110        for upstream in &upstreams {
111            crate::registry::parse_url(upstream)?;
112        }
113        let failed = Mutex::new(vec![None; upstreams.len()]);
114        Ok(Self { upstreams, timeout, max_bytes, cache_bytes, check, asking: Mutex::new(()), kept: Default::default(), absent: Default::default(), failed })
115    }
116
117    fn cached(&self, digest: &str) -> Option<Arc<[u8]>> {
118        locked(&self.kept).iter().find(|(d, _)| d == digest).map(|(_, file)| file.clone())
119    }
120
121    /// The file with this digest from the cache or, when `ask` is set,
122    /// from the first upstream that gives it. `Ok(None)` when nobody has it.
123    fn find(&self, engine: &kute::Engine, digest: &str, ask: bool) -> Result<Option<Arc<[u8]>>, Reply> {
124        if let Some(file) = self.cached(digest) {
125            return Ok(Some(file));
126        }
127        if !ask {
128            return Ok(None);
129        }
130        {
131            let mut absent = locked(&self.absent);
132            absent.retain(|(_, when)| when.elapsed() < ABSENT_FOR);
133            if absent.iter().any(|(d, _)| d == digest) {
134                return Ok(None);
135            }
136        }
137        // One question upstream at a time. A caller who arrives meanwhile
138        // is told to come back, and its worker is free at once: callers
139        // asking for digests nobody has cannot hold every worker.
140        let _asking = match self.asking.try_lock() {
141            Ok(guard) => guard,
142            Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
143            Err(std::sync::TryLockError::WouldBlock) => return Err(problem(503, "Service Unavailable", "busy", "this registry is asking another for a vocabulary; try again")),
144        };
145        if let Some(file) = self.cached(digest) {
146            return Ok(Some(file));
147        }
148        let mut every_upstream_said_no = true;
149        for (i, upstream) in self.upstreams.iter().enumerate() {
150            if locked(&self.failed)[i].is_some_and(|when| when.elapsed() < REST_FOR) {
151                // Not asked, so it has not said no.
152                every_upstream_said_no = false;
153                continue;
154            }
155            match crate::registry::take(engine, upstream, digest, self.max_bytes, self.timeout, true) {
156                Ok(crate::registry::Taken::Found(vocabulary, _)) => {
157                    // The right content without a signature this registry
158                    // requires is not kept: the next upstream may have it signed.
159                    if self.check.as_ref().is_some_and(|check| check(&vocabulary).is_err()) {
160                        every_upstream_said_no = false;
161                        locked(&self.failed)[i] = Some(Instant::now());
162                        continue;
163                    }
164                    // Written out again here, not passed on as it came.
165                    let Ok(file) = kute::vocab::to_vec(&vocabulary) else { continue };
166                    let file: Arc<[u8]> = file.into();
167                    if file.len() as u64 <= self.cache_bytes {
168                        let mut kept = locked(&self.kept);
169                        kept.push_back((digest.to_string(), file.clone()));
170                        while kept.iter().map(|(_, f)| f.len() as u64).sum::<u64>() > self.cache_bytes {
171                            kept.pop_front();
172                        }
173                    }
174                    return Ok(Some(file));
175                }
176                Ok(crate::registry::Taken::Absent(_)) => {}
177                // An upstream that failed or sent something else is passed
178                // over, and is not taken as having said the file is absent.
179                Err(_) => {
180                    every_upstream_said_no = false;
181                    locked(&self.failed)[i] = Some(Instant::now());
182                }
183            }
184        }
185        if every_upstream_said_no {
186            let mut absent = locked(&self.absent);
187            if absent.len() >= ABSENT_KEPT {
188                absent.pop_front();
189            }
190            absent.push_back((digest.to_string(), Instant::now()));
191        }
192        Ok(None)
193    }
194}
195
196/// The Studio page: three files compiled into the binary. The page loads
197/// nothing else and calls only `/v1/` on the origin it came from.
198const STUDIO: [(&str, &str, &str); 3] = [
199    ("/studio", "text/html; charset=utf-8", include_str!("../studio/index.html")),
200    ("/studio/studio.css", "text/css; charset=utf-8", include_str!("../studio/studio.css")),
201    ("/studio/studio.js", "text/javascript; charset=utf-8", include_str!("../studio/studio.js")),
202];
203
204/// What the page may do, enforced by the browser: scripts and styles from
205/// this origin only, requests to this origin only, no frames, no forms
206/// posting elsewhere, nothing else at all.
207const STUDIO_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
208
209impl Default for Options {
210    fn default() -> Self {
211        Self { workers: 4, queue: 16, timeout: Duration::from_secs(10), max_body_bytes: 3 << 20, any_host: false, studio: false, registry: false, operations: true, federation: None, peer_status: None }
212    }
213}
214
215struct Reply {
216    status: u16,
217    reason: &'static str,
218    body: Value,
219    allow: Option<&'static str>,
220    /// A file of the Studio page, as (content type, text), sent instead of `body`.
221    page: Option<(&'static str, &'static str)>,
222    /// A vocabulary file, sent instead of `body`.
223    file: Option<Box<[u8]>>,
224}
225
226fn problem(status: u16, reason: &'static str, code: &str, message: impl Into<String>) -> Reply {
227    Reply { status, reason, body: json!({ "error": { "code": code, "message": message.into() } }), allow: None, page: None, file: None }
228}
229
230fn ok(body: Value) -> Reply {
231    Reply { status: 200, reason: "OK", body, allow: None, page: None, file: None }
232}
233
234struct Request {
235    method: String,
236    path: String,
237    host: Option<String>,
238    content_type: Option<String>,
239    body: Vec<u8>,
240    /// Another registry is asking on a caller's behalf.
241    via: bool,
242}
243
244fn loopback_name(host: &str) -> bool {
245    let name = if let Some(rest) = host.strip_prefix('[') {
246        // [::1] or [::1]:port, and nothing else after the bracket
247        match rest.split_once(']') {
248            Some((name, after)) if after.is_empty() || after.strip_prefix(':').is_some_and(|port| port.chars().all(|c| c.is_ascii_digit())) => name,
249            _ => return false,
250        }
251    } else {
252        host.rsplit_once(':').map_or(host, |(name, port)| if port.chars().all(|c| c.is_ascii_digit()) { name } else { host })
253    };
254    name.eq_ignore_ascii_case("localhost") || name.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
255}
256
257/// Read one request within the deadline and the size limits.
258fn read_request(stream: &mut TcpStream, options: &Options) -> Result<Request, Reply> {
259    let deadline = Instant::now() + options.timeout;
260    let late = || problem(408, "Request Timeout", "timeout", "the request did not arrive in time");
261    let mut buffer: Vec<u8> = Vec::with_capacity(1024);
262    let mut chunk = [0u8; 4096];
263    let head_end = loop {
264        if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
265            break at;
266        }
267        if buffer.len() > MAX_HEAD_BYTES {
268            return Err(problem(431, "Request Header Fields Too Large", "headers_too_large", format!("the request line and headers may take {MAX_HEAD_BYTES} bytes")));
269        }
270        let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(late)?;
271        stream.set_read_timeout(Some(left)).map_err(|_| late())?;
272        match stream.read(&mut chunk) {
273            Ok(0) => return Err(problem(400, "Bad Request", "bad_request", "the connection closed before the request was complete")),
274            Ok(n) => buffer.extend_from_slice(&chunk[..n]),
275            Err(_) => return Err(late()),
276        }
277    };
278    if head_end > MAX_HEAD_BYTES {
279        return Err(problem(431, "Request Header Fields Too Large", "headers_too_large", format!("the request line and headers may take {MAX_HEAD_BYTES} bytes")));
280    }
281    let bad = |what: &str| problem(400, "Bad Request", "bad_request", what.to_string());
282    let head = std::str::from_utf8(&buffer[..head_end]).map_err(|_| bad("the request line and headers are not text"))?;
283    let mut lines = head.split("\r\n");
284    let mut first = lines.next().unwrap_or("").split(' ');
285    let (method, target, version) = (first.next().unwrap_or(""), first.next().unwrap_or(""), first.next().unwrap_or(""));
286    if method.is_empty() || !target.starts_with('/') || !matches!(version, "HTTP/1.0" | "HTTP/1.1") || first.next().is_some() {
287        return Err(bad("the request line is not HTTP/1.x"));
288    }
289    let (mut host, mut content_type, mut length, mut chunked, mut via) = (None, None, None, false, false);
290    for line in lines {
291        let (name, value) = line.split_once(':').ok_or_else(|| bad("a header line has no colon"))?;
292        // A name is a token: no space before the colon, no continuation
293        // line. Something in front of this service that read such a line
294        // another way would disagree with it about where the request ends.
295        if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) {
296            return Err(bad("a header name is not a token"));
297        }
298        let value = value.trim_matches([' ', '\t']);
299        if value.bytes().any(|b| (b < 0x20 && b != b'\t') || b == 0x7f) {
300            return Err(bad("a header value holds a control character"));
301        }
302        match name.to_ascii_lowercase().as_str() {
303            "host" => {
304                if host.is_some() {
305                    return Err(bad("two Host headers"));
306                }
307                host = Some(value.to_string());
308            }
309            "content-type" => content_type = Some(value.to_ascii_lowercase()),
310            "content-length" => {
311                // Digits only: `parse` alone would take "+5".
312                let n: u64 = Some(value).filter(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit())).and_then(|v| v.parse().ok()).ok_or_else(|| bad("Content-Length is not a number"))?;
313                if length.is_some_and(|earlier| earlier != n) {
314                    return Err(bad("two different Content-Length headers"));
315                }
316                length = Some(n);
317            }
318            "transfer-encoding" => chunked = true,
319            "kute-registry-via" => via = true,
320            _ => {}
321        }
322    }
323    if chunked {
324        return Err(problem(411, "Length Required", "length_required", "send the body with Content-Length, not a transfer encoding"));
325    }
326    let path = target.split('?').next().unwrap_or("").to_string();
327    let mut body = buffer[head_end + 4..].to_vec();
328    let length = match (method, length) {
329        (_, Some(n)) => n,
330        ("POST", None) => return Err(problem(411, "Length Required", "length_required", "a POST needs Content-Length")),
331        (_, None) => 0,
332    };
333    if length > options.max_body_bytes {
334        return Err(problem(413, "Content Too Large", "too_large", format!("the body is {length} bytes; the limit is {}", options.max_body_bytes)));
335    }
336    let length = length as usize;
337    if body.len() > length {
338        return Err(bad("more bytes than Content-Length; one request per connection"));
339    }
340    while body.len() < length {
341        let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(late)?;
342        stream.set_read_timeout(Some(left)).map_err(|_| late())?;
343        let want = chunk.len().min(length - body.len());
344        match stream.read(&mut chunk[..want]) {
345            Ok(0) => return Err(bad("the connection closed before the body was complete")),
346            Ok(n) => body.extend_from_slice(&chunk[..n]),
347            Err(_) => return Err(late()),
348        }
349    }
350    Ok(Request { method: method.to_string(), path, host, content_type, body, via })
351}
352
353fn route(server: &Server, request: &Request, options: &Options) -> Reply {
354    if !options.any_host && !request.host.as_deref().is_some_and(loopback_name) {
355        return problem(403, "Forbidden", "forbidden_host", "this service answers only requests addressed to localhost");
356    }
357    if let Some((_, content_type, text)) = STUDIO.iter().find(|(path, _, _)| options.studio && *path == request.path) {
358        if request.method != "GET" {
359            return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "the page is read with GET") };
360        }
361        return Reply { page: Some((content_type, text)), ..ok(Value::Null) };
362    }
363    let operation = match request.path.strip_prefix("/v1/") {
364        Some(rest) => rest,
365        None => return problem(404, "Not Found", "not_found", "the interface is under /v1/"),
366    };
367    if operation == "capabilities" {
368        if request.method != "GET" {
369            return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "capabilities is read with GET") };
370        }
371        let mut held = match server.call("inspect", &json!({})) {
372            Ok(v) => v,
373            Err(message) => return problem(500, "Internal Server Error", "internal", message),
374        };
375        held["api"] = json!("v1");
376        held["software"] = json!(format!("kute {}", kute::KUTE_VERSION));
377        held["operations"] = if options.operations { json!(OPERATIONS) } else { json!([]) };
378        held["registry"] = json!(options.registry);
379        held["peer_status"] = json!(options.peer_status.is_some());
380        held["limits"]["max_body_bytes"] = json!(options.max_body_bytes);
381        return ok(held);
382    }
383    if operation == "peer" {
384        let Some(path) = &options.peer_status else {
385            return problem(404, "Not Found", "not_found", "this service was not told of a peer: start it with --peer-status FILE");
386        };
387        if request.method != "GET" {
388            return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "the peer's status is read with GET; nothing can be sent to the peer from here") };
389        }
390        return ok(crate::peer_status::read(path));
391    }
392    if operation == "vocabularies" || operation.starts_with("vocabularies/") {
393        // Without the option the paths do not exist, and the answer does
394        // not say what is held.
395        if !options.registry {
396            return problem(404, "Not Found", "not_found", "this service does not give vocabulary files");
397        }
398        if request.method != "GET" {
399            return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "vocabularies are read with GET; nothing can be sent to this registry") };
400        }
401        let Some(digest) = operation.strip_prefix("vocabularies/") else {
402            let mut listing = server.registry_list();
403            // Who else this registry asks. What they hold is theirs to say.
404            listing["upstreams"] = json!(options.federation.as_ref().map(|f| f.upstreams.clone()).unwrap_or_default());
405            listing["upstream_files_need_a_trusted_signature"] = json!(options.federation.as_ref().is_some_and(|f| f.check.is_some()));
406            return ok(listing);
407        };
408        // Only a digest reaches the lookup: a file is named by the hash
409        // of its content and by nothing else.
410        if !crate::registry::is_digest(digest) {
411            return problem(404, "Not Found", "not_found", "a vocabulary is asked for by its digest: sha256: and 64 lowercase hex digits");
412        }
413        return match server.registry_file(digest) {
414            Some(Ok(file)) => Reply { file: Some(file.into_boxed_slice()), ..ok(Value::Null) },
415            Some(Err(_)) => problem(500, "Internal Server Error", "internal", "the vocabulary could not be written out"),
416            None => {
417                // Not held here. A registry asking for another is answered
418                // from what is here and kept, and no further.
419                let found = match &options.federation {
420                    Some(federation) => federation.find(server.engine(), digest, !request.via),
421                    None => Ok(None),
422                };
423                match found {
424                    Ok(Some(file)) => Reply { file: Some(file.to_vec().into_boxed_slice()), ..ok(Value::Null) },
425                    Ok(None) => problem(404, "Not Found", "not_found", "no vocabulary with that digest is held here"),
426                    Err(reply) => reply,
427                }
428            }
429        };
430    }
431    if !OPERATIONS.contains(&operation) || !options.operations {
432        return problem(404, "Not Found", "not_found", format!("there is no operation {operation:?}"));
433    }
434    if request.method != "POST" {
435        return Reply { allow: Some("POST"), ..problem(405, "Method Not Allowed", "method_not_allowed", "operations are called with POST") };
436    }
437    // A JSON content type cannot be sent across origins by a web page
438    // without the browser asking first, and this service never agrees.
439    if !request.content_type.as_deref().is_some_and(|t| t == "application/json" || t.starts_with("application/json;")) {
440        return problem(415, "Unsupported Media Type", "unsupported_media_type", "send Content-Type: application/json");
441    }
442    let arguments: Value = match serde_json::from_slice(&request.body) {
443        Ok(v) => v,
444        Err(e) => return problem(400, "Bad Request", "bad_json", format!("the body is not JSON: {e}")),
445    };
446    // A panic in an operation must not end the worker: with every worker
447    // gone the service would accept connections and answer none. No input
448    // is known to cause one.
449    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| server.call(operation, &arguments))) {
450        Ok(Ok(result)) => ok(result),
451        Ok(Err(message)) => problem(422, "Unprocessable Content", "refused", message),
452        Err(_) => problem(500, "Internal Server Error", "internal", "the operation failed unexpectedly"),
453    }
454}
455
456fn answer(stream: &mut TcpStream, reply: &Reply, options: &Options) {
457    let (content_type, body) = match (reply.page, &reply.file) {
458        (Some((content_type, text)), _) => (content_type, text.as_bytes().to_vec()),
459        (None, Some(file)) => ("application/json", file.to_vec()),
460        (None, None) => ("application/json", serde_json::to_vec(&reply.body).unwrap_or_else(|_| b"{}".to_vec())),
461    };
462    let mut head = format!(
463        "HTTP/1.1 {} {}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n",
464        reply.status,
465        reply.reason,
466        body.len()
467    );
468    if reply.status == 503 {
469        head.push_str("Retry-After: 1\r\n");
470    }
471    if reply.page.is_some() {
472        head.push_str(&format!("Content-Security-Policy: {STUDIO_POLICY}\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\n"));
473    }
474    if let Some(allow) = reply.allow {
475        head.push_str(&format!("Allow: {allow}\r\n"));
476    }
477    head.push_str("\r\n");
478    let _ = stream.set_write_timeout(Some(options.timeout));
479    if stream.write_all(head.as_bytes()).is_ok() && stream.write_all(&body).is_ok() {
480        let _ = stream.flush();
481    }
482    let _ = stream.shutdown(std::net::Shutdown::Write);
483    // A request refused before it was read to its end leaves bytes
484    // unread, and closing over unread bytes resets the connection on
485    // some systems (seen on macOS), which can take the answer with it.
486    // So read what is left and throw it away: at most 1 MiB and half a
487    // second, then close whatever the client does. The answer is safe
488    // only if all of what was sent is read, so the limit is the largest
489    // unread request an answer is guaranteed to survive.
490    let started = Instant::now();
491    let _ = stream.set_read_timeout(Some(Duration::from_millis(50)));
492    let (mut scrap, mut discarded) = ([0u8; 4096], 0usize);
493    while discarded < 1_048_576 && started.elapsed() < Duration::from_millis(500) {
494        match stream.read(&mut scrap) {
495            Ok(0) | Err(_) => break,
496            Ok(n) => discarded += n,
497        }
498    }
499}
500
501fn serve_one(server: &Server, mut stream: TcpStream, options: &Options) {
502    let reply = match read_request(&mut stream, options) {
503        Ok(request) => route(server, &request, options),
504        Err(reply) => reply,
505    };
506    answer(&mut stream, &reply, options);
507}
508
509fn work(server: Arc<Server>, jobs: Arc<Mutex<Receiver<TcpStream>>>, options: Options) {
510    loop {
511        let next = jobs.lock().map(|queue| queue.recv());
512        match next {
513            Ok(Ok(stream)) => serve_one(&server, stream, &options),
514            _ => return,
515        }
516    }
517}
518
519/// Serve until the listener fails. Each connection carries one request.
520pub fn serve(server: Server, listener: TcpListener, options: Options) -> kute::Result<()> {
521    let server = Arc::new(server);
522    let (send, receive) = sync_channel::<TcpStream>(options.queue.max(1));
523    let receive = Arc::new(Mutex::new(receive));
524    for _ in 0..options.workers.max(1) {
525        let (server, receive, options) = (server.clone(), receive.clone(), options.clone());
526        std::thread::spawn(move || work(server, receive, options));
527    }
528    for stream in listener.incoming() {
529        let stream = match stream {
530            Ok(s) => s,
531            Err(_) => continue,
532        };
533        match send.try_send(stream) {
534            Ok(()) => {}
535            Err(TrySendError::Full(mut stream)) => {
536                // Answered here, without reading: reading is what a worker is for.
537                let busy = Reply { ..problem(503, "Service Unavailable", "busy", "every worker is busy and the queue is full; try again") };
538                let brief = Options { timeout: Duration::from_secs(1), ..options.clone() };
539                answer(&mut stream, &busy, &brief);
540            }
541            Err(TrySendError::Disconnected(_)) => return Err(kute::KuteError::Backend("the workers stopped".into())),
542        }
543    }
544    Ok(())
545}
546
547/// Whether an address is on the loopback interface.
548pub fn is_loopback(address: &SocketAddr) -> bool {
549    address.ip().is_loopback()
550}