summaryrefslogtreecommitdiffstats
path: root/src/http
diff options
context:
space:
mode:
Diffstat (limited to 'src/http')
-rw-r--r--src/http/mod.rs69
-rw-r--r--src/http/render.rs42
-rw-r--r--src/http/routes.rs38
-rw-r--r--src/http/sse.rs163
4 files changed, 296 insertions, 16 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()),
diff --git a/src/http/render.rs b/src/http/render.rs
index d715a71..057ea14 100644
--- a/src/http/render.rs
+++ b/src/http/render.rs
@@ -290,6 +290,16 @@ pub struct Builds {
pub recent: Vec<BuildRow>,
}
+/// The same table on its own, for the htmx fragment refresh. Same fields, so
+/// the include in builds.html and this standalone render cannot drift apart.
+#[derive(Template)]
+#[template(path = "builds_table.html")]
+pub struct BuildsTable {
+ pub page: Page,
+ pub rows: Vec<BuildRow>,
+ pub recent: Vec<BuildRow>,
+}
+
#[derive(Debug, Clone)]
pub struct BuildLite {
pub id: String,
@@ -375,16 +385,40 @@ pub struct SettingRow {
/// Vendored static assets. htmx arrives in P3; until then this serves the
/// favicon and refuses everything else rather than walking the filesystem.
-pub fn static_asset(name: &str) -> crate::http::Res {
+/// Static assets. Two files, both vendored, both served from `include_bytes!`
+/// so the binary is self-contained and there is no install step and no bundler
+/// (§13). htmx is the only JavaScript this app ships; it is served precompressed
+/// because the raw file is 48 KB and the gzip is 15 KB, and the budget that
+/// matters is what a browser actually downloads.
+pub fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res {
use crate::http::Res;
match name {
- "htmx.min.js" => Res::text(404, "htmx is vendored in P3\n".into()),
"app.css" => {
- let s = std::include_str!("../../static/app.css");
- let mut r = Res::text(200, s.to_string());
+ let mut r = Res::text(200, std::include_str!("../../static/app.css").to_string());
r.content_type = "text/css".into();
r
}
+ "htmx.min.js" => {
+ if accept_gzip {
+ let gz: &[u8] = std::include_bytes!("../../static/htmx.min.js.gz");
+ let mut r = Res::stream(
+ "text/javascript",
+ std::io::Cursor::new(gz.to_vec()),
+ Some(gz.len()),
+ );
+ r.header("Content-Encoding", "gzip");
+ r.header("Cache-Control", "public, max-age=86400");
+ return r;
+ }
+ let raw: &[u8] = std::include_bytes!("../../static/htmx.min.js");
+ let mut r = Res::stream(
+ "text/javascript",
+ std::io::Cursor::new(raw.to_vec()),
+ Some(raw.len()),
+ );
+ r.header("Cache-Control", "public, max-age=86400");
+ r
+ }
_ => Res::text(404, "not found\n".into()),
}
}
diff --git a/src/http/routes.rs b/src/http/routes.rs
index 6b01611..177ffcd 100644
--- a/src/http/routes.rs
+++ b/src/http/routes.rs
@@ -10,7 +10,7 @@ use crate::{pipeline, time};
use super::auth;
use super::render::*;
-use super::{Req, Res, State};
+use super::{sse, Req, Res, State};
/// Redirect an unauthenticated visitor to the login page.
pub fn gate(state: &State, req: &Req) -> Option<Res> {
@@ -76,6 +76,7 @@ pub fn route(state: &State, req: &Req, seg: &[&str]) -> Res {
("GET", ["builds"]) => builds_page(state, req),
("GET", ["builds", id]) => build_detail(state, req, id),
("GET", ["builds", id, "log.txt"]) => build_log(state, id),
+ ("GET", ["builds", id, "log.stream"]) => build_log_stream(state, req, id),
("POST", ["builds", id, "cancel"]) => build_cancel(state, req, id),
("POST", ["builds", id, "requeue"]) => build_retry(state, req, id),
("GET", ["audit"]) => audit(state, req),
@@ -841,11 +842,19 @@ fn build_rows(state: &State) -> Vec<BuildRow> {
fn builds_page(state: &State, req: &Req) -> Res {
let page = chrome(state, req, "Builds", "nav_builds");
+ // htmx asks for the fragment; a browser with JavaScript off never does and
+ // gets the whole page either way (§13).
+ if req.query_get("fragment").as_deref() == Some("1") {
+ return page_to_res(
+ BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) },
+ 200,
+ );
+ }
builds_with(state, req, page)
}
-fn builds_with(state: &State, _req: &Req, page: Page) -> Res {
- let recent: Vec<BuildRow> = builds::list(&state.db, &[build_state::FAILED, build_state::SUCCEEDED], 10)
+fn recent_rows(state: &State) -> Vec<BuildRow> {
+ builds::list(&state.db, &[build_state::FAILED, build_state::SUCCEEDED], 10)
.unwrap_or_default()
.into_iter()
.map(|b| {
@@ -864,8 +873,11 @@ fn builds_with(state: &State, _req: &Req, page: Page) -> Res {
error: b.error.unwrap_or_default(),
}
})
- .collect();
- page_to_res(Builds { page, rows: build_rows(state), recent }, 200)
+ .collect()
+}
+
+fn builds_with(state: &State, _req: &Req, page: Page) -> Res {
+ page_to_res(Builds { page, rows: build_rows(state), recent: recent_rows(state) }, 200)
}
fn build_detail(state: &State, req: &Req, id: &str) -> Res {
@@ -920,6 +932,22 @@ fn build_log(state: &State, id: &str) -> Res {
Res::text(200, body)
}
+/// The live tail (§13). Server-sent events from a blocking reader: the pipeline
+/// appends to a file and never learns this connection exists, so a viewer that
+/// hangs up, stalls or never shows up cannot slow a build.
+fn build_log_stream(state: &State, req: &Req, id: &str) -> Res {
+ if builds::get(&state.db, id).unwrap_or(None).is_none() {
+ return not_found(state, req);
+ }
+ let tail = sse::LogTail::new(&state.cfg, state.db.clone(), id);
+ let mut res = Res::stream("text/event-stream", tail, None);
+ // No caching, and no proxy buffering: a buffered event stream is a log tail
+ // that arrives all at once, which is the thing we are trying to avoid.
+ res.header("Cache-Control", "no-cache");
+ res.header("X-Accel-Buffering", "no");
+ res
+}
+
fn build_cancel(state: &State, req: &Req, id: &str) -> Res {
let _ = builds::request_cancel(&state.db, id);
let mut page = chrome(state, req, "Builds", "nav_builds");
diff --git a/src/http/sse.rs b/src/http/sse.rs
new file mode 100644
index 0000000..e141926
--- /dev/null
+++ b/src/http/sse.rs
@@ -0,0 +1,163 @@
+//! The live log tail (§13): `GET /builds/:id/log.stream` as server-sent events.
+//!
+//! This is a blocking `std::io::Read` polled by the connection's thread, which is
+//! exactly the shape §14 asks for — no async runtime, no timer wheel. The
+//! pipeline appends to a plain file, so "streaming the log" means noticing that
+//! the file grew and forwarding the new bytes. Nothing in the build path knows
+//! this reader exists, which is what makes it safe to have at all: a client that
+//! disconnects, hangs or never connects cannot slow a build by a microsecond.
+//!
+//! The stream ends when the build reaches a terminal state and the file has no
+//! more bytes, so a browser tab does not hold a connection open forever.
+
+use std::io::{self, Read};
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+
+use crate::db::builds;
+use crate::db::model::build_state;
+
+/// How long a tail will wait for a build that never finishes. A viewer that
+/// outlives this gets a clean end and can reconnect.
+const MAX_LIFETIME: Duration = Duration::from_secs(30 * 60);
+/// Silence between keepalives. Proxies drop idle streams well before this.
+const KEEPALIVE: Duration = Duration::from_secs(10);
+const POLL: Duration = Duration::from_millis(200);
+
+pub struct LogTail {
+ path: PathBuf,
+ build_id: String,
+ db: crate::db::Db,
+ /// Bytes of the file already forwarded.
+ offset: u64,
+ /// SSE frames waiting to be handed to the caller.
+ out: std::collections::VecDeque<u8>,
+ started: Instant,
+ since_keepalive: Duration,
+ ended: bool,
+}
+
+impl LogTail {
+ pub fn new(cfg: &crate::config::Config, db: crate::db::Db, build_id: &str) -> Self {
+ Self {
+ path: cfg.build_log_path(build_id),
+ build_id: build_id.to_string(),
+ db,
+ offset: 0,
+ out: std::collections::VecDeque::new(),
+ started: Instant::now(),
+ since_keepalive: Duration::ZERO,
+ ended: false,
+ }
+ }
+
+ fn terminal(&self) -> bool {
+ match builds::get(&self.db, &self.build_id) {
+ Ok(Some(b)) => matches!(
+ b.state.as_str(),
+ build_state::SUCCEEDED | build_state::FAILED | build_state::CANCELLED
+ ),
+ // A build row that vanished is not going to produce more output.
+ Ok(None) => true,
+ // A database hiccup should not end the stream; the next poll tries
+ // again and the lifetime cap bounds the damage.
+ Err(_) => false,
+ }
+ }
+
+ /// Pull whatever the build appended since the last poll and frame it as SSE.
+ fn pump(&mut self) {
+ let (bytes, grew) = read_from(&self.path, self.offset);
+ if grew {
+ self.offset += bytes.len() as u64;
+ for line in String::from_utf8_lossy(&bytes).lines() {
+ // SSE: every line of payload needs its own `data:` prefix.
+ self.out.extend(format!("data: {line}\n\n").as_bytes());
+ }
+ self.since_keepalive = Duration::ZERO;
+ }
+ }
+
+ fn finish(&mut self) {
+ if self.ended {
+ return;
+ }
+ self.ended = true;
+ self.out.extend(b"event: end\ndata: done\n\n");
+ }
+}
+
+impl Read for LogTail {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ loop {
+ if !self.out.is_empty() {
+ let n = buf.len().min(self.out.len());
+ for (i, b) in self.out.drain(..n).enumerate() {
+ buf[i] = b;
+ }
+ return Ok(n);
+ }
+ if self.ended {
+ return Ok(0);
+ }
+ self.pump();
+ if !self.out.is_empty() {
+ continue;
+ }
+ if self.terminal() {
+ // One more pump in case the last lines landed with the state
+ // change; a race here would silently drop the end of a log.
+ self.pump();
+ if self.out.is_empty() {
+ self.finish();
+ }
+ continue;
+ }
+ if self.started.elapsed() > MAX_LIFETIME {
+ self.finish();
+ continue;
+ }
+ std::thread::sleep(POLL);
+ self.since_keepalive += POLL;
+ if self.since_keepalive >= KEEPALIVE {
+ self.since_keepalive = Duration::ZERO;
+ self.out.extend(b": keepalive\n\n");
+ }
+ }
+ }
+}
+
+/// Read `path` from `offset`. Returns the bytes and whether the file grew.
+fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) {
+ let mut f = match std::fs::File::open(path) {
+ Ok(f) => f,
+ Err(_) => return (Vec::new(), false),
+ };
+ use std::io::Seek;
+ if f.seek(std::io::SeekFrom::Start(offset)).is_err() {
+ return (Vec::new(), false);
+ }
+ let mut buf = Vec::new();
+ if f.read_to_end(&mut buf).is_err() {
+ return (Vec::new(), false);
+ }
+ let grew = !buf.is_empty();
+ (buf, grew)
+}
+
+/// A file served as-is, for static assets.
+pub struct FileBody {
+ inner: std::io::Cursor<Vec<u8>>,
+}
+
+impl FileBody {
+ pub fn new(bytes: Vec<u8>) -> Self {
+ Self { inner: std::io::Cursor::new(bytes) }
+ }
+}
+
+impl Read for FileBody {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ self.inner.read(buf)
+ }
+}