summaryrefslogtreecommitdiffstats
path: root/src/http/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/http/mod.rs')
-rw-r--r--src/http/mod.rs69
1 files changed, 62 insertions, 7 deletions
diff --git a/src/http/mod.rs b/src/http/mod.rs
index 65bf2c4..7ca4875 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -13,6 +13,7 @@ mod auth;
mod forms;
mod render;
mod routes;
+pub mod sse;
use std::sync::Arc;
@@ -33,6 +34,9 @@ pub struct Req {
pub body: String,
pub cookies: Vec<(String, String)>,
pub query_pairs: Vec<(String, String)>,
+ /// Whether the client said it can take gzip. Used to decide whether to hand
+ /// out the precompressed static asset.
+ pub accept_gzip: bool,
}
impl Req {
@@ -56,14 +60,34 @@ pub struct Res {
pub content_type: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
+ /// When set, the response body is produced by reading this to EOF instead of
+ /// `body`. Used for the log tail (ยง13), which must stream bytes as a build
+ /// appends them rather than buffering a response that never finishes.
+ pub stream: Option<Box<dyn std::io::Read + Send>>,
+ /// Length of `stream` when it is known up front, so the response can carry a
+ /// Content-Length instead of chunked transfer encoding.
+ pub stream_len: Option<usize>,
}
impl Res {
pub fn html(status: u16, body: String) -> Self {
- Self { status, content_type: "text/html; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new() }
+ Self { status, content_type: "text/html; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None }
}
pub fn text(status: u16, body: String) -> Self {
- Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new() }
+ Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None }
+ }
+ /// A streamed response. `known_len` lets a static file be sent with a
+ /// Content-Length instead of chunked, which is what a browser wants for a
+ /// file it already knows the size of.
+ pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self {
+ Self {
+ status: 200,
+ content_type: content_type.into(),
+ body: Vec::new(),
+ headers: Vec::new(),
+ stream: Some(Box::new(reader)),
+ stream_len: known_len,
+ }
}
pub fn redirect(location: &str) -> Self {
Self {
@@ -71,6 +95,8 @@ impl Res {
content_type: "text/plain".into(),
body: b"redirecting".to_vec(),
headers: vec![("Location".into(), location.into())],
+ stream: None,
+ stream_len: None,
}
}
pub fn found(&self) -> bool {
@@ -128,6 +154,12 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
.find(|h| h.field.equiv("Cookie"))
.map(|h| auth::parse_cookies(h.value.as_str()))
.unwrap_or_default();
+ let accept_gzip = request
+ .headers()
+ .iter()
+ .find(|h| h.field.equiv("Accept-Encoding"))
+ .map(|h| h.value.as_str().contains("gzip"))
+ .unwrap_or(false);
let req = Req {
method: request.method().as_str().to_string(),
path: percent_decode(&path),
@@ -135,6 +167,7 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
body,
cookies,
query_pairs: forms::parse(&query),
+ accept_gzip,
};
let mut res = dispatch(&state, &req);
@@ -143,15 +176,37 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
res.headers.retain(|(k, _)| k != "X-New-Session");
res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict"));
}
- let mut builder = tiny_http::Response::from_data(std::mem::take(&mut res.body))
- .with_status_code(tiny_http::StatusCode(res.status));
+ let mut headers = Vec::new();
if let Ok(h) = tiny_http::Header::from_bytes(b"Content-Type", res.content_type.as_bytes()) {
- builder = builder.with_header(h);
+ headers.push(h);
}
for (k, v) in &res.headers {
if let Ok(h) = tiny_http::Header::from_bytes(k.as_bytes(), v.as_bytes()) {
- builder = builder.with_header(h);
+ headers.push(h);
+ }
+ }
+ // A streamed response is chunked and stays open until the reader returns
+ // EOF; that is the whole point for the log tail.
+ if let Some(reader) = res.stream.take() {
+ let mut resp = tiny_http::Response::new(
+ tiny_http::StatusCode(res.status),
+ headers,
+ reader,
+ res.stream_len,
+ None,
+ );
+ // tiny_http switches to chunked above 32 KB by default. For a file whose
+ // length we know, a Content-Length is what a browser wants; the log tail
+ // has no known length and stays chunked, which is what it needs.
+ if res.stream_len.is_some() {
+ resp = resp.with_chunked_threshold(usize::MAX);
}
+ return request.respond(resp);
+ }
+ let mut builder = tiny_http::Response::from_data(std::mem::take(&mut res.body))
+ .with_status_code(tiny_http::StatusCode(res.status));
+ for h in headers {
+ builder = builder.with_header(h);
}
request.respond(builder)
}
@@ -164,7 +219,7 @@ fn dispatch(state: &State, req: &Req) -> Res {
// Static assets and the login page are reachable without a session.
match (req.method.as_str(), seg.as_slice()) {
- ("GET", ["static", name]) => return render::static_asset(name),
+ ("GET", ["static", name]) => return render::static_asset(name, req.accept_gzip),
("GET", ["login"]) => return routes::login_form(state, req),
("POST", ["login"]) => return routes::login(state, req),
("GET", ["healthz"]) => return Res::text(200, "ok\n".into()),