summaryrefslogtreecommitdiffstats
path: root/src/http
diff options
context:
space:
mode:
Diffstat (limited to 'src/http')
-rw-r--r--src/http/auth.rs17
-rw-r--r--src/http/forms.rs1
-rw-r--r--src/http/mod.rs41
-rw-r--r--src/http/render.rs16
-rw-r--r--src/http/routes/mod.rs15
-rw-r--r--src/http/routes/mutations.rs17
-rw-r--r--src/http/routes/pages.rs21
-rw-r--r--src/http/sse.rs12
8 files changed, 0 insertions, 140 deletions
diff --git a/src/http/auth.rs b/src/http/auth.rs
index 9689fd8..6720607 100644
--- a/src/http/auth.rs
+++ b/src/http/auth.rs
@@ -4,23 +4,17 @@ use std::sync::OnceLock;
use crate::hash;
-/// Live sids and whether each has passed the password gate. One map, so
-/// dropping a session removes its authentication with it.
static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
fn sessions() -> &'static Mutex<HashMap<String, bool>> {
SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
-/// Random hex token from the system RNG, or `None` when there is no usable one.
-/// A session id is the whole credential (C-1), so "no RNG" is a refusal rather
-/// than a weaker, guessable token.
fn random_hex() -> Option<String> {
use std::io::Read;
let mut buf = [0u8; 32];
let mut f = std::fs::File::open("/dev/urandom").ok()?;
f.read_exact(&mut buf).ok()?;
- // Mixed in so two calls in the same instant still differ.
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
@@ -34,8 +28,6 @@ fn counter() -> u64 {
C.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
-/// Mint an anonymous session: enough for a CSRF token, not enough to see a
-/// single page when a password is set.
pub fn new_session() -> Option<String> {
let sid = random_hex()?;
if let Ok(mut s) = sessions().lock() {
@@ -48,8 +40,6 @@ pub fn is_valid_session(sid: &str) -> bool {
sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false)
}
-/// Mark a session as having passed the password gate. An unknown sid stays
-/// unknown rather than being inserted as a side effect of a login attempt.
pub fn authenticate(sid: &str) {
if let Ok(mut s) = sessions().lock() {
if let Some(authenticated) = s.get_mut(sid) {
@@ -58,8 +48,6 @@ pub fn authenticate(sid: &str) {
}
}
-/// The gate's whole question: is this sid one we issued, and did someone type
-/// the password into a form on it?
pub fn is_authenticated(sid: &str) -> bool {
sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false)
}
@@ -70,8 +58,6 @@ pub fn drop_session(sid: &str) {
}
}
-/// The CSRF token for a session. Derived rather than stored, so it cannot drift
-/// out of sync with the session.
pub fn csrf_token(sid: &str) -> String {
hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string()
}
@@ -92,7 +78,6 @@ fn constant_time_eq(a: &str, b: &str) -> bool {
diff == 0
}
-/// Parse a `Cookie:` header value.
pub fn parse_cookies(header: &str) -> Vec<(String, String)> {
header
.split(';')
@@ -104,8 +89,6 @@ pub fn parse_cookies(header: &str) -> Vec<(String, String)> {
.collect()
}
-/// An empty password means the UI is open, which is the default on loopback;
-/// the CSRF gate still applies.
pub fn password_ok(cfg: &crate::config::Config, given: &str) -> bool {
cfg.password.is_empty() || constant_time_eq(&cfg.password, given)
}
diff --git a/src/http/forms.rs b/src/http/forms.rs
index 03da7b8..579b931 100644
--- a/src/http/forms.rs
+++ b/src/http/forms.rs
@@ -1,4 +1,3 @@
-/// Percent-decode one token (`+` means space in a form body).
pub fn decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
diff --git a/src/http/mod.rs b/src/http/mod.rs
index 11ea107..7beeff4 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -9,13 +9,11 @@ use std::sync::Arc;
use crate::config::Config;
use crate::db::Db;
-/// Shared state every handler needs.
pub struct State {
pub cfg: Config,
pub db: Db,
}
-/// A request that has been decoded enough to route on.
pub struct Req {
pub method: String,
pub path: String,
@@ -23,11 +21,7 @@ pub struct Req {
pub body: String,
pub cookies: Vec<(String, String)>,
pub query_pairs: Vec<(String, String)>,
- /// The body's form pairs, parsed once when the request is decoded (n-3) — a
- /// single handler asks for five of them.
pub form_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,
}
@@ -46,18 +40,12 @@ impl Req {
}
}
-/// What a handler produced.
pub struct Res {
pub status: u16,
pub content_type: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
- /// When set, the 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>,
}
@@ -68,9 +56,6 @@ impl Res {
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(), stream: None, stream_len: None }
}
- /// A streamed response. `known_len` lets a static file be sent with a
- /// Content-Length, which is what a browser wants for a file whose size it
- /// already knows.
pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self {
Self {
status: 200,
@@ -99,8 +84,6 @@ impl Res {
}
}
-/// Start the HTTP server. Returns the accept-loop handle and the address it
-/// actually bound, which matters for `:0` in tests.
pub struct Server {
pub handle: std::thread::JoinHandle<()>,
pub addr: String,
@@ -115,8 +98,6 @@ pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> {
let handle = std::thread::Builder::new()
.name("http-accept".into())
.spawn(move || {
- // `tiny_http` hands each connection to its own worker internally;
- // the accept loop just blocks on `recv` and hands off.
for request in server.incoming_requests() {
let state = state.clone();
std::thread::Builder::new()
@@ -152,7 +133,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
.find(|h| h.field.equiv("Accept-Encoding"))
.map(|h| h.value.as_str().contains("gzip"))
.unwrap_or(false);
- // Parsed once, here, rather than per `form_get` call (n-3).
let form_pairs = forms::parse(&body);
let req = Req {
method: request.method().as_str().to_string(),
@@ -166,7 +146,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
};
let mut res = dispatch(&state, &req);
- // Attach the session cookie if the handler minted one.
if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) {
res.headers.retain(|(k, _)| k != "X-New-Session");
res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict"));
@@ -180,8 +159,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
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),
@@ -190,9 +167,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
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);
}
@@ -206,34 +180,23 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
request.respond(builder)
}
-/// Route table (§12). One flat match: no middleware stack, just the session gate
-/// and then a path.
fn dispatch(state: &State, req: &Req) -> Res {
let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect();
let is_get = req.method == "GET";
- // 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, 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()),
- // Metrics are counts only — no package names, versions, or audit detail
- // — and a Prometheus scraper has no session to present. The bind address
- // is loopback by default, which is where this is safe.
("GET", ["metrics"]) => return routes::metrics(state),
_ => {}
}
- // Session gate: mint a session for anonymous visitors so the CSRF token
- // exists before anyone logs in. It is not a login — `gate` only lets through
- // a sid that a successful login marked authenticated.
let (sid, new_session) = match req.cookie("sid") {
Some(s) if auth::is_valid_session(&s) => (s, false),
_ => match auth::new_session() {
Some(s) => (s, true),
- // No system RNG means no unguessable session id. Refuse rather than
- // hand out a token someone else could compute.
None => return Res::text(500, "500: could not mint a session\n".into()),
},
};
@@ -245,7 +208,6 @@ fn dispatch(state: &State, req: &Req) -> Res {
return finish(state, req, res, &sid, new_session);
}
- // CSRF: every state-changing request must carry the token for its session.
if !is_get {
let token = req.form_get("csrf").or_else(|| req.query_get("csrf")).unwrap_or_default();
if !auth::csrf_ok(&sid, &token) {
@@ -261,14 +223,11 @@ fn dispatch(state: &State, req: &Req) -> Res {
}
fn finish(_state: &State, _req: &Req, mut res: Res, _sid: &str, _new: bool) -> Res {
- // A tiny security posture for a tool that serves a package index.
res.header("X-Content-Type-Options", "nosniff");
res.header("Referrer-Policy", "same-origin");
res
}
-/// Percent-decode a path segment. Enough for package names and ids, which is
-/// all that ever needs it here.
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
diff --git a/src/http/render.rs b/src/http/render.rs
index f049a25..f3e4669 100644
--- a/src/http/render.rs
+++ b/src/http/render.rs
@@ -1,7 +1,5 @@
use askama::Template;
-/// Everything the shared chrome needs. Embedded in each page context because
-/// askama inheritance passes the whole struct down.
#[derive(Debug, Clone)]
pub struct Page {
pub title: String,
@@ -19,7 +17,6 @@ pub struct Page {
pub nav_subscriptions: &'static str,
pub nav_audit: &'static str,
pub nav_settings: &'static str,
- /// True when a password gate is configured, so the chrome offers a logout.
pub gated: bool,
}
@@ -116,7 +113,6 @@ pub struct ReviewDetail {
pub base_version: String,
pub has_base: bool,
pub panels: Vec<Panel>,
- /// First introductions show the whole recipe instead of a diff (§7.1b).
pub recipe: String,
pub srcinfo: String,
pub has_srcinfo: bool,
@@ -134,8 +130,6 @@ pub struct ReviewHead {
pub risk: String,
pub signals: Vec<String>,
pub missing_deps: Vec<String>,
- /// §10.3: "approving this marks N packages stale" — the packages of ours
- /// whose own recipes name one of the packages this candidate produces.
pub dependents: Vec<String>,
pub revision: i64,
pub aur_commit: String,
@@ -196,9 +190,6 @@ pub struct Attention {
pub blocked: Vec<BlockedRow>,
}
-/// §8.4: an approval whose build failed. The index is still serving the older
-/// version and nothing about the package looks wrong from the outside, so this
-/// row exists to be impossible to miss.
#[derive(Debug, Clone)]
pub struct UnbuiltRow {
pub pkgbase: String,
@@ -221,7 +212,6 @@ pub struct NoticeRow {
#[derive(Debug, Clone)]
pub struct StaleRow {
pub pkgbase: String,
- /// The dependency that moved (or `aur` for a downgrade row).
pub dependency: String,
pub built_with: String,
pub now: String,
@@ -261,7 +251,6 @@ pub struct PackageDetail {
pub summary: String,
pub can_withdraw: bool,
pub stale: Vec<String>,
- /// "v2 approved, build failed, index still serving v1" (§8.4).
pub unbuilt: Vec<UnbuiltRow>,
pub deps_in: Vec<String>,
pub deps_out: Vec<String>,
@@ -287,7 +276,6 @@ pub struct Builds {
pub recent: Vec<BuildRow>,
}
-/// The same table on its own, for the htmx fragment refresh.
#[derive(Template)]
#[template(path = "builds_table.html")]
pub struct BuildsTable {
@@ -379,10 +367,6 @@ pub struct SettingRow {
pub value: String,
}
-/// 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 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 {
diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs
index 0dfed52..ed488c8 100644
--- a/src/http/routes/mod.rs
+++ b/src/http/routes/mod.rs
@@ -8,9 +8,6 @@ use super::{Req, Res, State};
mod mutations;
mod pages;
-// The handlers live in two files by direction of travel — reads in `pages`,
-// writes in `mutations` — and are pulled back into scope here so the routing
-// table below still reads as one flat list of endpoints (n-4).
pub(crate) use mutations::*;
pub(crate) use pages::*;
@@ -29,9 +26,6 @@ pub fn login_form(state: &State, req: &Req) -> Res {
page_to_res(Login { page, error: String::new() }, 200)
}
-/// Forget the session server-side and clear the cookie. The CSRF token is
-/// derived from the sid, so dropping the sid invalidates every form a browser
-/// still has open — which is exactly what logout should do.
pub fn logout(req: &Req) -> Res {
if let Some(sid) = req.cookie("sid") {
auth::drop_session(&sid);
@@ -45,9 +39,6 @@ pub fn login(state: &State, req: &Req) -> Res {
let given = req.form_get("password").unwrap_or_default();
let page = Page::new("Sign in", csrf(state, req));
if auth::password_ok(&state.cfg, &given) {
- // Rotate rather than promote: the sid the visitor arrived with (if any)
- // is dropped, so the session that existed before the password was typed
- // is never the one that carries the privilege afterwards.
if let Some(old) = req.cookie("sid") {
auth::drop_session(&old);
}
@@ -57,7 +48,6 @@ pub fn login(state: &State, req: &Req) -> Res {
};
auth::authenticate(&sid);
let mut res = Res::redirect("/");
- // `serve` turns this into the `Set-Cookie: sid=…` header.
res.header("X-New-Session", &sid);
res
} else {
@@ -109,7 +99,6 @@ fn not_found(state: &State, req: &Req) -> Res {
)
}
-/// The shared chrome: counts for the nav badges and the active-tab marker.
fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page {
let db = &state.db;
let mut page = Page::new(title, csrf(state, req));
@@ -133,7 +122,6 @@ fn csrf(_state: &State, req: &Req) -> String {
req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default()
}
-/// A byte count a human can read at a glance.
fn human_size(bytes: i64) -> String {
const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"];
let mut v = bytes as f64;
@@ -158,9 +146,6 @@ fn age(detected_at: &str) -> String {
format!("{detected_at} → {now}")
}
-/// Who the audit trail says made a decision. With no password configured the
-/// UI is open on loopback and every session is the operator's; with one, only
-/// a session that passed the gate gets a name.
fn actor(state: &State, req: &Req) -> &'static str {
let sid = req.cookie("sid").unwrap_or_default();
if !auth::auth_required(&state.cfg) || auth::is_authenticated(&sid) {
diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs
index 79089b2..2af8b7f 100644
--- a/src/http/routes/mutations.rs
+++ b/src/http/routes/mutations.rs
@@ -37,8 +37,6 @@ pub(crate) fn review_approve(state: &State, req: &Req, id: &str) -> Res {
page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200)
}
Err(ap::ApproveError::System(e)) => {
- // The database refused. Telling the reviewer their review went stale
- // would be a lie about the one thing they cannot check themselves.
let mut page = chrome(state, req, "Review failed", "nav_reviews");
page.flash = format!("the approval could not be recorded: {e}");
page.has_flash = true;
@@ -46,14 +44,10 @@ pub(crate) fn review_approve(state: &State, req: &Req, id: &str) -> Res {
page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 500)
}
Err(ap::ApproveError::Stale(stale)) => {
- // §7.1a: refuse, re-render what it is now, and say why. Never
- // silently retarget the approval onto the newer state.
let mut page = chrome(state, req, "Review changed", "nav_reviews");
page.flash = format!("refused: {stale}");
page.has_flash = true;
page.flash_err = true;
- // Show the review as it stands NOW — the frozen one the form came
- // from may have collapsed or been superseded while it was open.
let current = candidates::pending_candidates(db)
.unwrap_or_default()
.into_iter()
@@ -109,8 +103,6 @@ pub(crate) fn review_reject(state: &State, req: &Req, id: &str) -> Res {
}
}
-/// Bulk approve/reject (§7.4): per-item, never "approve everything forever",
-/// and high-risk items are refused unless each was confirmed individually.
pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res {
let db = &state.db;
let form = req.form();
@@ -136,8 +128,6 @@ pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res {
page.flash_err = true;
return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 400);
}
- // The rule itself lives in `review::approve::bulk`, so the page and the
- // library cannot disagree about what a bulk decision means (§7.4).
let items: Vec<(i64, String, String)> = ids
.iter()
.filter_map(|id| {
@@ -200,9 +190,6 @@ pub(crate) fn sub_pause(state: &State, req: &Req) -> Res {
let db = &state.db;
let name = req.form_get("pkgbase").unwrap_or_default();
let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state);
- // Pause and resume are the only moves this page makes. A subscription that
- // is orphaned or removed is not the reviewer's to pause, and saying so beats
- // quietly rewriting its state.
let next = match cur {
Some(SubscriptionState::Active) => SubscriptionState::Paused,
Some(SubscriptionState::Paused) => SubscriptionState::Active,
@@ -223,8 +210,6 @@ pub(crate) fn sub_remove(state: &State, req: &Req) -> Res {
pub(crate) fn notice_ack(state: &State, req: &Req) -> Res {
let id: i64 = req.form_get("id").and_then(|s| s.parse().ok()).unwrap_or(0);
let _ = db::acknowledge_notice(&state.db.writer, id);
- // POST-redirect-GET: the notice vanishing from the list is its own
- // confirmation, and a refresh can no longer re-POST.
Res::redirect("/attention")
}
@@ -270,8 +255,6 @@ pub(crate) fn build_cancel(state: &State, req: &Req, id: &str) -> Res {
builds_with(state, req, page)
}
-/// Retrying a failed build is an explicit, audited decision (§8.4), not
-/// something the system does to itself.
pub(crate) fn build_retry(state: &State, req: &Req, id: &str) -> Res {
match builds::retry(&state.db, id) {
Ok(()) => {
diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs
index f1f3ef8..bb5db34 100644
--- a/src/http/routes/pages.rs
+++ b/src/http/routes/pages.rs
@@ -56,7 +56,6 @@ pub(crate) fn review_rows(db: &Db) -> Vec<ReviewRow> {
revision: c.revision,
})
.collect();
- // Risk first, then oldest — the scarcest resource gets the loudest rows.
let rank = |r: &str| match r {
risk::level::HIGH => 0,
risk::level::MEDIUM => 1,
@@ -83,8 +82,6 @@ pub(crate) fn review_detail(state: &State, req: &Req, id: &str) -> Res {
let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else {
return not_found(state, req);
};
- // Opening a review freezes it: a later detection now opens a fresh review
- // instead of silently changing what is on screen (§7.1).
let _ = candidates::mark_viewed(db, id);
let page = chrome(state, req, &format!("Review {}", c.pkgbase), "nav_reviews");
let (head, panels, recipe, srcinfo, sources_resolved, deps_resolved) = review_body(state, &c);
@@ -113,7 +110,6 @@ pub(crate) fn panels_base(c: &CandidateRow) -> (String, bool) {
}
}
-/// Build the review body: the panel set plus the first-introduction material.
pub(crate) fn review_body(
state: &State,
c: &CandidateRow,
@@ -224,7 +220,6 @@ pub(crate) fn attention(state: &State, req: &Req) -> Res {
.into_iter()
.map(|(id, pkgbase, blocked_on)| BlockedRow { id_short: short(&id), id, pkgbase, blocked_on })
.collect();
- // Staleness is computed on read (P4 fills the query in).
let stale = crate::watch::staleness::stale_rows(db).unwrap_or_default();
let outdated: Vec<StaleRow> = stale
.iter()
@@ -322,8 +317,6 @@ pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res {
step: b.current_step.unwrap_or_default(),
})
.collect();
- // Depends-on comes from the recipe we actually serve; needed-by comes from
- // the packages whose own recipes name this one (§10.3).
let deps_in: Vec<String> = accepted
.as_ref()
.and_then(|r| db::accepted_recipe(db, r).ok().flatten())
@@ -375,8 +368,6 @@ pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res {
// --------------------------------------------------------------- builds --
-/// The version a build is about. A build points at a candidate, or — for a
-/// manual rebuild of something already published — at a release.
pub(crate) fn build_version(db: &Db, b: &builds::BuildRow) -> String {
if let Some(cid) = b.candidate_id {
if let Some(c) = candidates::candidate_by_id(db, cid).ok().flatten() {
@@ -424,8 +415,6 @@ pub(crate) fn build_rows(state: &State) -> Vec<BuildRow> {
pub(crate) 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) },
@@ -514,17 +503,12 @@ pub(crate) 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.
pub(crate) 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
@@ -550,11 +534,6 @@ pub(crate) fn audit(state: &State, req: &Req) -> Res {
page_to_res(Audit { page, rows }, 200)
}
-/// `GET /metrics` in Prometheus text exposition format (§12, §15).
-///
-/// Everything here is computed from live state on every scrape. There are no counters
-/// incremented at event sites: a counter every code path has to maintain quietly
-/// drifts the first time a path is added; a query cannot drift.
pub fn metrics(state: &State) -> Res {
match ops::metrics(&state.cfg, &state.db) {
Ok(m) => {
diff --git a/src/http/sse.rs b/src/http/sse.rs
index 561de33..e4a5e6a 100644
--- a/src/http/sse.rs
+++ b/src/http/sse.rs
@@ -4,10 +4,7 @@ use std::time::{Duration, Instant};
use crate::db::builds;
-/// 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);
@@ -15,9 +12,7 @@ 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,
@@ -41,21 +36,16 @@ impl LogTail {
fn terminal(&self) -> bool {
match builds::get(&self.db, &self.build_id) {
Ok(Some(b)) => b.state.is_terminal(),
- // 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;
@@ -111,7 +101,6 @@ impl Read for LogTail {
}
}
-/// 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,
@@ -129,7 +118,6 @@ fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) {
(buf, grew)
}
-/// A file served as-is, for static assets.
pub struct FileBody {
inner: std::io::Cursor<Vec<u8>>,
}