diff --git a/crates/forge-core/src/advisories.rs b/crates/forge-core/src/advisories.rs index e2c7223..26768cf 100644 --- a/crates/forge-core/src/advisories.rs +++ b/crates/forge-core/src/advisories.rs @@ -182,12 +182,21 @@ pub fn parse_record(json: &[u8], ecosystem: &str) -> Result> { Ok(merged.into_values().collect()) } -/// Reads every `.json` record of an OSV zip dump for `ecosystem`. A record that does not parse, -/// or is too large, is skipped and counted in the second value. -pub fn read_dump(reader: R, ecosystem: &str) -> Result<(Vec, usize)> { +/// Advisories handed to the sink of [`read_dump`] at a time. +const IMPORT_BATCH: usize = 500; + +/// Reads every `.json` record of an OSV zip dump for `ecosystem`, handing the advisories to `sink` +/// in batches of about [`IMPORT_BATCH`], so the whole dump is never held in memory. A record that +/// does not parse, or is too large, is skipped and counted in the returned value. An error from +/// the sink or from a broken zip stops the read and is returned. +pub fn read_dump(reader: R, ecosystem: &str, mut sink: F) -> Result +where + R: Read + Seek, + F: FnMut(Vec) -> Result<()>, +{ let mut zip = zip::ZipArchive::new(reader) .map_err(|e| Error::Invalid(format!("advisory dump is not a zip file: {e}")))?; - let mut advisories = Vec::new(); + let mut pending = Vec::new(); let mut skipped = 0; for index in 0..zip.len() { let mut file = zip @@ -205,11 +214,17 @@ pub fn read_dump(reader: R, ecosystem: &str) -> Result<(Vec advisories.extend(found), + Ok(found) => pending.extend(found), Err(_) => skipped += 1, } + if pending.len() >= IMPORT_BATCH { + sink(std::mem::take(&mut pending))?; + } + } + if !pending.is_empty() { + sink(pending)?; } - Ok((advisories, skipped)) + Ok(skipped) } /// Parses a version as semver, after dropping a leading `v` (Go style). @@ -503,7 +518,12 @@ mod tests { zip.finish().expect("finish"); } buf.set_position(0); - let (found, skipped) = read_dump(buf, "npm").expect("dump reads"); + let mut found = Vec::new(); + let skipped = read_dump(buf, "npm", |batch| { + found.extend(batch); + Ok(()) + }) + .expect("dump reads"); assert_eq!(skipped, 1); assert_eq!(found.len(), 1); assert_eq!(found[0].package, "left"); diff --git a/crates/forge-core/src/avatar.rs b/crates/forge-core/src/avatar.rs index ad8f10b..b7d54f2 100644 --- a/crates/forge-core/src/avatar.rs +++ b/crates/forge-core/src/avatar.rs @@ -56,17 +56,20 @@ pub fn process_avatar(bytes: &[u8]) -> Result { limits.max_alloc = Some(MAX_ALLOC_BYTES); reader.limits(limits); - let decoded = reader - .decode() - .map_err(|e| Error::Invalid(format!("could not decode avatar: {e}")))?; - - // Center-crop to the largest square, then scale down to the avatar size. - let (width, height) = (decoded.width(), decoded.height()); - let side = width.min(height); - let x = (width - side) / 2; - let y = (height - side) / 2; - let square = decoded.crop_imm(x, y, side, side); - let resized = square.resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3); + // Center-crop to the largest square, then scale down to the avatar size. The decoded image + // (up to 128 MiB) is dropped as soon as the crop copies it, before the resize allocates. + let resized = { + let decoded = reader + .decode() + .map_err(|e| Error::Invalid(format!("could not decode avatar: {e}")))?; + let (width, height) = (decoded.width(), decoded.height()); + let side = width.min(height); + let x = (width - side) / 2; + let y = (height - side) / 2; + let square = decoded.crop_imm(x, y, side, side); + drop(decoded); + square.resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3) + }; let mut png = Cursor::new(Vec::new()); resized diff --git a/crates/forge-core/src/store/advisories.rs b/crates/forge-core/src/store/advisories.rs index 2bf40e1..7f25999 100644 --- a/crates/forge-core/src/store/advisories.rs +++ b/crates/forge-core/src/store/advisories.rs @@ -7,6 +7,7 @@ use std::collections::{BTreeSet, HashMap}; +use tokio::sync::mpsc; use turso::{Row, Value}; use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; @@ -131,41 +132,58 @@ fn key_params(repo_id: &str, key: &AlertKey) -> Vec { } impl Store { - /// Replaces every advisory of `ecosystem` with `advisories`, in one transaction. Rows for other - /// ecosystems are not touched. Callers rescan the repos afterwards. - pub async fn replace_advisories(&self, ecosystem: &str, advisories: &[Advisory]) -> Result<()> { + /// Replaces every advisory of `ecosystem` with the advisories received from `batches`, in one + /// transaction, so the old rows stay until the last batch is in. The sender ends with `Ok(None)` + /// to commit; an `Err` item, or the channel closing without `Ok(None)` (the parser died), rolls + /// back. Rows for other ecosystems are not touched. Returns how many advisories were stored. + /// Callers rescan the repos afterwards. + pub async fn replace_advisories( + &self, + ecosystem: &str, + mut batches: mpsc::Receiver>>>, + ) -> Result { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<()> = async { + let outcome: Result = async { tx.execute( "DELETE FROM advisories WHERE ecosystem = ?1", (ecosystem.to_string(),), ) .await .map_err(db_err)?; - for advisory in advisories { - if advisory.ecosystem != ecosystem { - continue; + let mut stored = 0; + loop { + let Some(batch) = batches.recv().await else { + return Err(Error::Invalid("advisory import ended without finishing".into())); + }; + let Some(batch) = batch? else { + break; + }; + for advisory in batch { + if advisory.ecosystem != ecosystem { + continue; + } + let params = vec![ + Value::Text(advisory.id.clone()), + Value::Text(advisory.ecosystem.clone()), + Value::Text(advisory.package.clone()), + Value::Text(advisory.summary.clone()), + Value::Text(advisory.severity.clone()), + Value::Text(serde_json::to_string(&advisory.ranges).map_err(json_err)?), + Value::Text(serde_json::to_string(&advisory.versions).map_err(json_err)?), + Value::Text(advisory.modified.clone()), + ]; + tx.execute( + "INSERT OR REPLACE INTO advisories (id, ecosystem, package, summary, severity, \ + ranges_json, versions_json, modified) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params, + ) + .await + .map_err(db_err)?; + stored += 1; } - let params = vec![ - Value::Text(advisory.id.clone()), - Value::Text(advisory.ecosystem.clone()), - Value::Text(advisory.package.clone()), - Value::Text(advisory.summary.clone()), - Value::Text(advisory.severity.clone()), - Value::Text(serde_json::to_string(&advisory.ranges).map_err(json_err)?), - Value::Text(serde_json::to_string(&advisory.versions).map_err(json_err)?), - Value::Text(advisory.modified.clone()), - ]; - tx.execute( - "INSERT OR REPLACE INTO advisories (id, ecosystem, package, summary, severity, \ - ranges_json, versions_json, modified) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", - params, - ) - .await - .map_err(db_err)?; } - Ok(()) + Ok(stored) } .await; finish(tx, outcome).await @@ -537,6 +555,20 @@ mod tests { use crate::advisories::{Event, Range}; use crate::store::Store; + impl Store { + /// Replaces `ecosystem` with `advisories` sent as one batch. + async fn replace_in_one_batch( + &self, + ecosystem: &str, + advisories: &[Advisory], + ) -> Result { + let (tx, rx) = mpsc::channel(2); + tx.send(Ok(Some(advisories.to_vec()))).await.unwrap(); + tx.send(Ok(None)).await.unwrap(); + self.replace_advisories(ecosystem, rx).await + } + } + fn advisory(id: &str, package: &str, fixed: &str) -> Advisory { Advisory { id: id.into(), @@ -584,7 +616,7 @@ mod tests { // A scan opens alerts, closes fixed ones, and keeps dismissed ones. store - .replace_advisories( + .replace_in_one_batch( "crates.io", &[ advisory("RUSTSEC-1", "old", "2.0.0"), @@ -696,7 +728,7 @@ mod tests { .unwrap() .id; store - .replace_advisories("crates.io", &[advisory("RUSTSEC-3", "back", "2.0.0")]) + .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-3", "back", "2.0.0")]) .await .unwrap(); store @@ -725,10 +757,10 @@ mod tests { // Replacing advisories for one ecosystem leaves the others alone. store - .replace_advisories("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")]) + .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")]) .await .unwrap(); - store.replace_advisories("npm", &[]).await.unwrap(); + store.replace_in_one_batch("npm", &[]).await.unwrap(); assert_eq!( store .advisories_for_package("crates.io", "a") @@ -739,7 +771,7 @@ mod tests { "crates.io advisory kept" ); store - .replace_advisories("crates.io", &[advisory("RUSTSEC-5", "a", "3.0.0")]) + .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-5", "a", "3.0.0")]) .await .unwrap(); let rows = store diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 2ffeb98..9ff3304 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -155,6 +155,7 @@ impl Store { let reader = db.connect().map_err(db_err)?; apply_pragmas(&reader).await; apply_query_only(&reader).await?; + apply_reader_cache_size(&reader).await?; readers.push(Mutex::new(reader)); } Ok(Store { @@ -971,6 +972,17 @@ async fn apply_query_only(conn: &Connection) -> Result<()> { Ok(()) } +/// Caps each reader's page cache at 2 MiB (negative means KiB). Turso gives every connection +/// its own cache, so the default 2000 pages (~8 MB) per reader adds up across the pool. +async fn apply_reader_cache_size(conn: &Connection) -> Result<()> { + let mut rows = conn + .query("PRAGMA cache_size = -2048", ()) + .await + .map_err(db_err)?; + while rows.next().await.map_err(db_err)?.is_some() {} + Ok(()) +} + /// Applies the connection PRAGMAs. Unsupported ones are logged and skipped, never fatal. /// The values actually in effect are logged after the attempt. async fn apply_pragmas(conn: &Connection) { diff --git a/crates/forge-core/src/store/notifications.rs b/crates/forge-core/src/store/notifications.rs index caec50f..eaab87e 100644 --- a/crates/forge-core/src/store/notifications.rs +++ b/crates/forge-core/src/store/notifications.rs @@ -5,9 +5,9 @@ use turso::{Row, Value}; use super::issues::finish; use super::repo_listing::READABLE_BY_VIEWER; -use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id}; +use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, map_user, new_id}; use crate::error::{Error, Result}; -use crate::model::Id; +use crate::model::{Id, User}; use crate::notifications::{Notification, Reason, SubState, WatchLevel}; use crate::time::now_stamp; @@ -137,6 +137,32 @@ impl Store { .await } + /// How many users watch the repo at level `watching` (the count of `watchers`). + pub async fn watcher_count(&self, repo_id: &str) -> Result { + let conn = self.read_conn().await; + let n = fetch_opt( + &conn, + "SELECT COUNT(*) FROM repo_watches WHERE repo_id = ?1 AND level = 'watching'", + (repo_id.to_string(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + Ok(u64::try_from(n).unwrap_or(0)) + } + + /// The site admins (accounts with `is_admin` set), ordered by username. + pub async fn list_admins(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {USER_COLS} FROM users WHERE is_admin = 1 ORDER BY username_folded"), + (), + map_user, + ) + .await + } + /// Sets the user's subscription on an issue or pull, replacing any existing row. This is /// the explicit user action. pub async fn subscribe( diff --git a/crates/forge-core/src/store/pulls.rs b/crates/forge-core/src/store/pulls.rs index 185705d..3fb8cba 100644 --- a/crates/forge-core/src/store/pulls.rs +++ b/crates/forge-core/src/store/pulls.rs @@ -610,6 +610,21 @@ impl Store { ) .await } + + /// How many public forks the repo has (the count of `list_forks` filtered to public). + pub async fn public_fork_count(&self, repo_id: &str) -> Result { + let conn = self.read_conn().await; + let n = fetch_opt( + &conn, + "SELECT COUNT(*) FROM repos r JOIN users u ON u.id = r.owner_id \ + WHERE r.fork_of = ?1 AND r.visibility = 'public'", + (repo_id.to_string(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + Ok(u64::try_from(n).unwrap_or(0)) + } } #[cfg(test)] diff --git a/crates/forge-git/src/browse.rs b/crates/forge-git/src/browse.rs index c6962c6..52b06dc 100644 --- a/crates/forge-git/src/browse.rs +++ b/crates/forge-git/src/browse.rs @@ -75,8 +75,11 @@ fn gerr(e: impl std::fmt::Display) -> Error { Error::Failed(e.to_string()) } +/// Every call opens a new handle, and gix's default delta-base cache is 96 MB per handle, so it is +/// capped here. fn open(repo: &Path) -> Result { - gix::open_opts(repo, gix::open::Options::isolated()).map_err(gerr) + let options = gix::open::Options::isolated().config_overrides(["core.deltaBaseCacheLimit=16m"]); + gix::open_opts(repo, options).map_err(gerr) } /// Git's ref-name rules (check-ref-format), plus rejection of anything that could be read as @@ -333,6 +336,17 @@ pub fn read_blob( commit: &str, path: &str, max_bytes: usize, +) -> Result> { + blob_at(repo, commit, path, max_bytes, false) +} + +/// `text_only` makes a blob larger than `max_bytes` yield None before its data is loaded. +fn blob_at( + repo: &Path, + commit: &str, + path: &str, + max_bytes: usize, + text_only: bool, ) -> Result> { validate_repo_path(path)?; if path.is_empty() { @@ -360,12 +374,19 @@ pub fn read_blob( is_binary: false, })), EntryKind::Blob | EntryKind::Executable | EntryKind::Symlink => { - let blob = repo.find_blob(oid).map_err(gerr)?; - let full = &blob.data; - let size = full.len() as u64; - let is_binary = full[..full.len().min(BINARY_PROBE_BYTES)].contains(&0); - let truncated = full.len() > max_bytes; - let data = full[..full.len().min(max_bytes)].to_vec(); + if text_only && repo.find_header(oid).map_err(gerr)?.size() > max_bytes as u64 { + return Ok(None); + } + let mut blob = repo.find_blob(oid).map_err(gerr)?; + let mut data = blob.take_data(); + let size = data.len() as u64; + let is_binary = data[..data.len().min(BINARY_PROBE_BYTES)].contains(&0); + let truncated = data.len() > max_bytes; + if truncated { + // Give back the memory of the dropped tail, not just its length. + data.truncate(max_bytes); + data.shrink_to_fit(); + } Ok(Some(BlobData { oid: oid.to_hex().to_string(), kind, @@ -386,13 +407,10 @@ pub fn read_text_blob( path: &str, max_bytes: usize, ) -> Result> { - let Some(blob) = read_blob(repo, commit, path, max_bytes)? else { + let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else { return Ok(None); }; - if matches!(blob.kind, EntryKind::Tree | EntryKind::Submodule) - || blob.truncated - || blob.is_binary - { + if matches!(blob.kind, EntryKind::Tree | EntryKind::Submodule) || blob.is_binary { return Ok(None); } Ok(String::from_utf8(blob.data).ok()) diff --git a/crates/forge-git/src/fsck.rs b/crates/forge-git/src/fsck.rs index f592e47..8b2b190 100644 --- a/crates/forge-git/src/fsck.rs +++ b/crates/forge-git/src/fsck.rs @@ -2,11 +2,17 @@ use std::path::Path; +use std::process::Stdio; + use crate::command::{GitCommand, GitEnv}; use crate::error::Result; +use crate::history::read_pipe_head; + +/// Longest git output kept, in bytes. +const MAX_OUTPUT_BYTES: usize = 64 * 1024; -/// Outcome of [`fsck`]. `output` holds git's diagnostics (stdout and stderr, trimmed). It is -/// empty when the repo is clean. +/// Outcome of [`fsck`]. `output` holds git's diagnostics (stdout and stderr, trimmed, at most +/// 64 KiB). It is empty when the repo is clean. #[derive(Debug, Clone, PartialEq, Eq)] pub struct FsckReport { pub ok: bool, @@ -17,15 +23,34 @@ pub struct FsckReport { /// one with damaged objects, is a report with `ok` false, not an error. Only a failure to start /// git is an error. pub async fn fsck(env: &GitEnv, repo: &Path, full: bool) -> Result { - let mut cmd = GitCommand::new(env, "fsck").git_dir(repo); + // Dangling objects are not problems and would only pad the output. + let mut cmd = GitCommand::new(env, "fsck") + .git_dir(repo) + .arg("--no-dangling"); if full { cmd = cmd.arg("--full"); } - let out = cmd.into_tokio().output().await?; - let mut text = String::from_utf8_lossy(&out.stdout).into_owned(); - text.push_str(&String::from_utf8_lossy(&out.stderr)); + let mut command = cmd.into_tokio(); + command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = command.spawn()?; + let stdout = child.stdout.take().map(|p| tokio::spawn(read_pipe_head(p))); + let stderr = child.stderr.take().map(|p| tokio::spawn(read_pipe_head(p))); + let status = child.wait().await?; + let mut text = String::new(); + for task in [stdout, stderr].into_iter().flatten() { + text.push_str(&String::from_utf8_lossy(&task.await.unwrap_or_default())); + } + // Each pipe keeps its own head, so the two together can exceed the cap. + let mut end = text.len().min(MAX_OUTPUT_BYTES); + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); Ok(FsckReport { - ok: out.status.success(), + ok: status.success(), output: text.trim().to_owned(), }) } diff --git a/crates/forge-git/src/history.rs b/crates/forge-git/src/history.rs index fb06c0d..d7e9d55 100644 --- a/crates/forge-git/src/history.rs +++ b/crates/forge-git/src/history.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet}; use std::path::Path; use std::process::Stdio; -use tokio::io::AsyncReadExt; +use tokio::io::{AsyncRead, AsyncReadExt}; use crate::browse::{self, CommitInfo}; use crate::command::{GitCommand, GitEnv, ObjectSource}; @@ -127,6 +127,18 @@ fn validate_prefix(prefix: &str) -> Result<()> { Ok(()) } +/// Longest kept head of a child's output pipe, in bytes. +const PIPE_HEAD_CAP: u64 = 64 * 1024; + +/// Keeps the first [`PIPE_HEAD_CAP`] bytes of a child's output pipe. The rest is read and +/// dropped, so the child never blocks on a full pipe while it is being waited for. +pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec { + let mut kept = Vec::new(); + let _ = (&mut pipe).take(PIPE_HEAD_CAP).read_to_end(&mut kept).await; + let _ = tokio::io::copy(&mut pipe, &mut tokio::io::sink()).await; + kept +} + /// Feeds stdout chunks to `f` until EOF, until `f` returns false, or until /// [`OUTPUT_CAP`] bytes. Returns `true` only when EOF was reached. A non-zero exit /// after EOF becomes `Error::Failed` with stderr. @@ -138,13 +150,7 @@ async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Re .stdout .take() .ok_or_else(|| Error::Failed("git stdout missing".into()))?; - let stderr_task = child.stderr.take().map(|mut e| { - tokio::spawn(async move { - let mut v = Vec::new(); - let _ = e.read_to_end(&mut v).await; - v - }) - }); + let stderr_task = child.stderr.take().map(|e| tokio::spawn(read_pipe_head(e))); let mut chunk = vec![0u8; 64 * 1024]; let mut total = 0usize; @@ -191,6 +197,28 @@ pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec, bool)> { Ok((buf, complete)) } +/// Feeds each NUL-terminated record of stdout to `f` as it arrives, until `f` returns false. +/// Empty records are skipped and a record cut off by the output cap is dropped. Returns `true` +/// only when EOF was reached. +async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result { + let mut carry = Vec::new(); + for_each_chunk(cmd, |chunk| { + let mut rest = chunk; + while let Some(end) = rest.iter().position(|&b| b == 0) { + carry.extend_from_slice(&rest[..end]); + rest = &rest[end + 1..]; + let keep_going = carry.is_empty() || f(&carry); + carry.clear(); + if !keep_going { + return false; + } + } + carry.extend_from_slice(rest); + true + }) + .await +} + /// Parses one record (the bytes after a `%x1e` up to the next one). Returns the commit /// and the bytes after `%x1d` (file names when `--name-only` is used). fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> { @@ -815,24 +843,18 @@ pub async fn list_files( .arg("--name-only") .arg("--full-tree") .user_revs(&[commit])?; - let (buf, complete) = read_capped(cmd).await?; - let mut paths: Vec<&[u8]> = buf.split(|&b| b == 0).filter(|p| !p.is_empty()).collect(); - let mut cut = !complete; - if !complete { - // The last record may be partial. - paths.pop(); - } - if paths.len() > max { - paths.truncate(max); - cut = true; - } - Ok(( - paths - .into_iter() - .map(|p| String::from_utf8_lossy(p).into_owned()) - .collect(), - cut, - )) + let mut paths = Vec::new(); + let mut cut = false; + let complete = for_each_nul_record(cmd, |path| { + if paths.len() == max { + cut = true; + return false; + } + paths.push(String::from_utf8_lossy(path).into_owned()); + true + }) + .await?; + Ok((paths, cut || !complete)) } /// Every blob in the tree of `commit` with its size in bytes, at most `max` of them. The flag is @@ -851,39 +873,35 @@ pub async fn list_file_sizes( .arg("-l") .arg("--full-tree") .user_revs(&[commit])?; - let (buf, complete) = read_capped(cmd).await?; - let mut recs: Vec<&[u8]> = buf.split(|&b| b == 0).filter(|p| !p.is_empty()).collect(); - let mut cut = !complete; - if !complete { - // The last record may be partial. - recs.pop(); - } let mut out = Vec::new(); - for rec in recs { + let mut cut = false; + let complete = for_each_nul_record(cmd, |rec| { // ` SP SP SP+ \t`; the path may hold tabs, so split at the first. let Some(tab) = rec.iter().position(|&b| b == b'\t') else { - continue; + return true; }; let meta = String::from_utf8_lossy(&rec[..tab]); let mut fields = meta.split_whitespace(); let (Some(mode), Some(kind), Some(_oid), Some(size)) = (fields.next(), fields.next(), fields.next(), fields.next()) else { - continue; + return true; }; if kind != "blob" || mode == "120000" { - continue; + return true; } let Ok(size) = size.parse::() else { - continue; + return true; }; if out.len() >= max { cut = true; - break; + return false; } out.push((String::from_utf8_lossy(&rec[tab + 1..]).into_owned(), size)); - } - Ok((out, cut)) + true + }) + .await?; + Ok((out, cut || !complete)) } /// The newest commit (walking back from `commit`) that touched each direct child of `dir`, diff --git a/crates/forge-git/src/search.rs b/crates/forge-git/src/search.rs index b0f80e6..28f51ee 100644 --- a/crates/forge-git/src/search.rs +++ b/crates/forge-git/src/search.rs @@ -6,11 +6,11 @@ use std::path::Path; use std::process::Stdio; use std::time::Duration; -use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; +use tokio::io::{AsyncBufRead, AsyncBufReadExt, BufReader}; use crate::command::GitEnv; use crate::error::{Error, Result}; -use crate::history::{git, validate_oid}; +use crate::history::{git, read_pipe_head, validate_oid}; /// Longest accepted query, in bytes. pub const MAX_QUERY_BYTES: usize = 200; @@ -18,6 +18,9 @@ pub const MAX_QUERY_BYTES: usize = 200; const MAX_GLOB_BYTES: usize = 512; /// Longest line text kept in a hit, in characters. const MAX_LINE_CHARS: usize = 500; +/// Bytes kept of one `git grep` output line. Up to 4 bytes per character, so this holds the +/// header (commit, path, line number) and `MAX_LINE_CHARS` of text; the rest is dropped unread. +const MAX_RECORD_BYTES: usize = 4 * MAX_LINE_CHARS + 4096; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GrepOptions { @@ -107,6 +110,34 @@ fn parse_record(record: &[u8], commit: &str) -> Option { }) } +/// Reads one line into `buf`, without its `\n`, keeping at most `keep` bytes of it. The rest of +/// the line is consumed and dropped, so a huge line does not allocate its whole size. Returns +/// false at end of input. +async fn read_line_capped( + reader: &mut R, + buf: &mut Vec, + keep: usize, +) -> std::io::Result { + buf.clear(); + let mut started = false; + loop { + let available = reader.fill_buf().await?; + if available.is_empty() { + return Ok(started); + } + started = true; + let newline = available.iter().position(|&b| b == b'\n'); + let content = newline.unwrap_or(available.len()); + let take = content.min(keep - buf.len()); + buf.extend_from_slice(&available[..take]); + let consumed = newline.map_or(available.len(), |i| i + 1); + reader.consume(consumed); + if newline.is_some() { + return Ok(true); + } + } +} + /// Searches the tree of `commit` for `query`. Exit code 1 from git (no match) is an empty result. pub async fn grep( env: &GitEnv, @@ -142,13 +173,7 @@ pub async fn grep( .stdout .take() .ok_or_else(|| Error::Failed("git stdout missing".into()))?; - let stderr_task = child.stderr.take().map(|mut e| { - tokio::spawn(async move { - let mut v = Vec::new(); - let _ = e.read_to_end(&mut v).await; - v - }) - }); + let stderr_task = child.stderr.take().map(|e| tokio::spawn(read_pipe_head(e))); let max = opts.max_matches; let mut hits = Vec::new(); @@ -156,13 +181,8 @@ pub async fn grep( let reading = async { let mut lines = BufReader::new(stdout); let mut buf = Vec::new(); - loop { - buf.clear(); - if lines.read_until(b'\n', &mut buf).await? == 0 { - break; - } - let record = buf.strip_suffix(b"\n").unwrap_or(&buf); - let Some(hit) = parse_record(record, commit) else { + while read_line_capped(&mut lines, &mut buf, MAX_RECORD_BYTES).await? { + let Some(hit) = parse_record(&buf, commit) else { continue; }; if hits.len() == max { diff --git a/crates/forge-runner/src/artifacts.rs b/crates/forge-runner/src/artifacts.rs index 26126ad..1639220 100644 --- a/crates/forge-runner/src/artifacts.rs +++ b/crates/forge-runner/src/artifacts.rs @@ -129,14 +129,14 @@ pub fn collect( } } else if file_type.is_file() && globs.is_match(&rel) { found.push((rel, entry.path())); + if found.len() > MAX_FILES { + return Err(ArtifactError::TooMany); + } } } } found.sort(); - if found.len() > MAX_FILES { - return Err(ArtifactError::TooMany); - } let mut seen = HashSet::new(); let mut out = Vec::with_capacity(found.len()); diff --git a/crates/forge-runner/src/logs.rs b/crates/forge-runner/src/logs.rs index fbb9169..64886a8 100644 --- a/crates/forge-runner/src/logs.rs +++ b/crates/forge-runner/src/logs.rs @@ -46,7 +46,7 @@ impl Default for PumpConfig { /// Bytes kept for resends. Acknowledged bytes are trimmed past this, oldest first. Unacknowledged /// bytes are never trimmed (they are at most one batch). -pub const RETAIN_CAP: usize = 8 * 1024 * 1024; +pub const RETAIN_CAP: usize = 2 * 1024 * 1024; /// Written in place of bytes the forge lost and the runner no longer holds. pub const GAP_MARKER: &[u8] = b"[log gap]\n"; @@ -303,8 +303,13 @@ where (take, done) }; reader.consume(take); - if (done || line.len() >= MAX_LINE) && alive { - alive = tx.send(std::mem::take(&mut line)).await.is_ok(); + if done || line.len() >= MAX_LINE { + // Once the receiver is gone, drop the line instead of letting it grow. + if alive { + alive = tx.send(std::mem::take(&mut line)).await.is_ok(); + } else { + line.clear(); + } } } if !line.is_empty() && alive { diff --git a/crates/forge-runner/src/oci/mod.rs b/crates/forge-runner/src/oci/mod.rs index 35ba4f2..1440a02 100644 --- a/crates/forge-runner/src/oci/mod.rs +++ b/crates/forge-runner/src/oci/mod.rs @@ -31,6 +31,8 @@ pub enum ImageError { #[source] source: oci_client::errors::OciDistributionError, }, + #[error("image {image} config size {size} is negative or over 4 MiB")] + ConfigTooLarge { image: String, size: i64 }, #[error("unsupported or malformed digest {0}, only sha256: is supported")] UnsupportedDigest(String), #[error("blob digest mismatch: expected {expected}, got {actual}")] diff --git a/crates/forge-runner/src/oci/pull.rs b/crates/forge-runner/src/oci/pull.rs index 31b8898..6c05b4b 100644 --- a/crates/forge-runner/src/oci/pull.rs +++ b/crates/forge-runner/src/oci/pull.rs @@ -19,6 +19,9 @@ use super::store::{ImageMeta, ImageStore, lock_file}; use super::unpack::{Ownership, UnpackStats, unpack_layers}; use super::{ImageError, PreparedImage, RegistryAuth}; +/// Largest image config blob the runner will read into memory. +const MAX_CONFIG_BYTES: i64 = 4 * 1024 * 1024; + impl ImageStore { /// Makes `image` available as an unpacked rootfs and returns it with its config. /// @@ -74,6 +77,12 @@ impl ImageStore { return Ok(prepared); } + if manifest.config.size < 0 || manifest.config.size > MAX_CONFIG_BYTES { + return Err(ImageError::ConfigTooLarge { + image: whole, + size: manifest.config.size, + }); + } let mut config_bytes = Vec::new(); client .pull_blob(&reference, &manifest.config, &mut config_bytes) diff --git a/crates/forge-runner/src/oci/unpack.rs b/crates/forge-runner/src/oci/unpack.rs index 00950f9..f27ff24 100644 --- a/crates/forge-runner/src/oci/unpack.rs +++ b/crates/forge-runner/src/oci/unpack.rs @@ -240,8 +240,14 @@ impl Unpacker { } self.own(&path)?; fs::set_permissions(&path, Permissions::from_mode(mode | 0o700))?; + // Only a directory whose mode is not already owner rwx needs its mode restored. + // A later layer may reset a directory an earlier one recorded, so drop the stale entry. if matches!(self.ownership, Ownership::Preserve { .. }) { - self.dir_modes.insert(path, mode); + if mode & 0o700 != 0o700 { + self.dir_modes.insert(path, mode); + } else { + self.dir_modes.remove(&path); + } } self.created.insert(rel); self.stats.dirs += 1; diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index b86d8fb..eadea55 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -27,7 +27,7 @@ use crate::update::{self, Installed, UpdateState}; use crate::workspace; /// Log lines queued between the executor and the log shipper. -const LOG_CHANNEL: usize = 256; +const LOG_CHANNEL: usize = 64; /// How many times the runner tries to report a finished job. const FINISH_ATTEMPTS: u32 = 5; /// Largest single artifact the runner will upload. The forge enforces its own total cap. diff --git a/crates/forge-ssh/src/server.rs b/crates/forge-ssh/src/server.rs index e32c6cf..f5dc18a 100644 --- a/crates/forge-ssh/src/server.rs +++ b/crates/forge-ssh/src/server.rs @@ -24,7 +24,7 @@ use russh::{Channel, ChannelId, ChannelOpenFailure, Disconnect, MethodKind, Meth use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; use tokio::process::{Child, ChildStdin}; -use tokio::sync::{Notify, mpsc}; +use tokio::sync::{Notify, Semaphore, mpsc}; use crate::backend::GitBackend; use crate::error::{Error, Result}; @@ -34,9 +34,12 @@ use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate}; const PUMP_CHUNK: usize = 32 * 1024; /// Client input chunks buffered in front of the child's stdin. This bounds memory and /// propagates backpressure to the SSH read loop. -const STDIN_QUEUE: usize = 32; +const STDIN_QUEUE: usize = 8; /// Failed publickey attempts before the connection is dropped. const MAX_AUTH_ATTEMPTS: usize = 6; +/// Connections served at once, counting unauthenticated ones. Each can hold a russh packet +/// buffer of up to 256 KiB before auth, so this bounds that memory. +const MAX_CONNECTIONS: usize = 256; #[derive(Debug, Clone)] pub struct SshConfig { @@ -64,6 +67,7 @@ pub async fn run(config: SshConfig, backend: Arc) -> Result<() let listener = TcpListener::bind(config.listen).await?; tracing::info!(addr = %config.listen, "ssh server listening"); + let connection_slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); loop { let (stream, peer) = match listener.accept().await { Ok(v) => v, @@ -74,6 +78,11 @@ pub async fn run(config: SshConfig, backend: Arc) -> Result<() continue; } }; + // At the limit the socket is dropped at once rather than queued. + let Ok(permit) = connection_slots.clone().try_acquire_owned() else { + tracing::warn!(%peer, "ssh connection limit reached, dropping connection"); + continue; + }; let authed = Arc::new(AtomicBool::new(false)); let client = Client { backend: Arc::clone(&backend), @@ -86,6 +95,8 @@ pub async fn run(config: SshConfig, backend: Arc) -> Result<() let russh_config = Arc::clone(&russh_config); let auth_timeout = config.auth_timeout; tokio::spawn(async move { + // Held until the connection ends, then the slot is free for the next client. + let _permit = permit; let running = match run_stream(russh_config, stream, client).await { Ok(running) => running, Err(e) => { @@ -553,6 +564,7 @@ async fn pump( Ok(0) | Err(_) => break, Ok(n) => n, }; + // A right-sized copy: a chunk queued for the client holds only the bytes read. let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default()); let sent = match ext { None => handle.data(channel, chunk).await.is_ok(), diff --git a/crates/forge-web/src/advisories/worker.rs b/crates/forge-web/src/advisories/worker.rs index 83e85fd..a137a5f 100644 --- a/crates/forge-web/src/advisories/worker.rs +++ b/crates/forge-web/src/advisories/worker.rs @@ -12,12 +12,15 @@ use std::io::{BufReader, Write}; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime}; -use forge_core::advisories::{KNOWN_ECOSYSTEMS, read_dump}; +use forge_core::advisories::{Advisory, KNOWN_ECOSYSTEMS, read_dump}; use forge_core::{Error, Result}; +use tokio::sync::mpsc; use super::scan::scan_all; use crate::state::AppState; +/// Batches the parser may have queued ahead of the store's writer. +const IMPORT_QUEUE: usize = 2; /// First wait after a failed download. It doubles with each further failure. const RETRY_FIRST: Duration = Duration::from_secs(5 * 60); /// Longest wait after a failed download. @@ -204,25 +207,39 @@ async fn fetch_into(client: &reqwest::Client, url: &str, part: &Path) -> Result< Ok(total) } -/// Parses the dump on a blocking thread and replaces the stored advisories of `ecosystem`. +/// Parses the dump on a blocking thread and replaces the stored advisories of `ecosystem`. The +/// parser sends its batches over a channel of [`IMPORT_QUEUE`] slots, and the store writes each one +/// in the replacement's transaction as it comes, so only a few batches are in memory at a time. +/// A parse error goes down the channel as an `Err` item, which rolls the replacement back; only +/// the parser's closing `Ok(None)` commits it. async fn import(state: &AppState, ecosystem: &str, path: &Path) -> Result<()> { + let (tx, rx) = mpsc::channel::>>>(IMPORT_QUEUE); let owned_path = path.to_owned(); let eco = ecosystem.to_owned(); - let (advisories, skipped) = tokio::task::spawn_blocking(move || -> Result<_> { - let file = File::open(&owned_path)?; - read_dump(BufReader::new(file), &eco) - }) - .await - .map_err(|e| Error::Invalid(format!("advisory import task failed: {e}")))??; - state - .store - .replace_advisories(ecosystem, &advisories) - .await?; - tracing::info!( - ecosystem, - imported = advisories.len(), - skipped, - "advisories: dump imported" - ); + let parser = tokio::task::spawn_blocking(move || -> usize { + let parsed = File::open(&owned_path).map_err(Error::from).and_then(|file| { + read_dump(BufReader::new(file), &eco, |batch| { + tx.blocking_send(Ok(Some(batch))) + .map_err(|_| Error::Invalid("advisory import was stopped".into())) + }) + }); + // The store commits only on `Ok(None)`, so a panic above (sender dropped) rolls back. + match parsed { + Ok(skipped) => { + let _ = tx.blocking_send(Ok(None)); + skipped + } + Err(e) => { + let _ = tx.blocking_send(Err(e)); + 0 + } + } + }); + let stored = state.store.replace_advisories(ecosystem, rx).await; + let skipped = parser + .await + .map_err(|e| Error::Invalid(format!("advisory import task failed: {e}")))?; + let imported = stored?; + tracing::info!(ecosystem, imported, skipped, "advisories: dump imported"); Ok(()) } diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web/src/alerts.rs index 848aa81..cddb6f7 100644 --- a/crates/forge-web/src/alerts.rs +++ b/crates/forge-web/src/alerts.rs @@ -108,8 +108,8 @@ async fn deliver( ) { // The alert was written (raised, resolved or recorded): the health page follows it. crate::live::admin().bump(&crate::live::Topic::AdminHealth); - let users = match state.store.list_users().await { - Ok(users) => users, + let admins = match state.store.list_admins().await { + Ok(admins) => admins, Err(e) => { tracing::error!(error = %e, "alerts: listing the admins failed"); return; @@ -118,7 +118,7 @@ async fn deliver( let live = state.live(); let base = live.base_url.trim_end_matches('/').to_owned(); let state_word = if resolved { "resolved" } else { "raised" }; - for admin in users.into_iter().filter(|u| u.is_admin && !u.is_org()) { + for admin in admins.into_iter().filter(|u| !u.is_org()) { if let Err(e) = state .store .add_admin_notice(&admin.id, key, topic, subject, detail, resolved) diff --git a/crates/forge-web/src/auth.rs b/crates/forge-web/src/auth.rs index 62388d3..be91f45 100644 --- a/crates/forge-web/src/auth.rs +++ b/crates/forge-web/src/auth.rs @@ -3,6 +3,7 @@ //! The browser holds the raw session token in `__Host-forge_session`. The database //! stores only `hash_token(token)`, so a leaked DB row cannot be replayed as a cookie. +use std::sync::{Arc, OnceLock}; use std::time::Duration; use forge_core::password::{hash_password, verify_password}; @@ -13,6 +14,7 @@ use forge_core::{Session, Store, User, secret, totp}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use tokio::sync::Semaphore; use topcoat::router::error::{forbidden, see_other}; use topcoat::router::request::{headers, uri}; @@ -162,8 +164,22 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> { .build() } +/// Argon2 runs at once, server-wide. Each hash or verify allocates about 19 MiB, so a burst of +/// logins would otherwise pile that memory up on the blocking pool. +const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4; + +/// Permits for argon2 work. A permit is held until the hash or verify finishes. +fn password_slots() -> &'static Arc { + static SLOTS: OnceLock> = OnceLock::new(); + SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES))) +} + /// Hashes a password with argon2 on the blocking pool, keeping the async runtime free. pub async fn hash_password_async(password: String) -> forge_core::Result { + let _permit = password_slots() + .acquire() + .await + .map_err(|_| forge_core::Error::Crypto("password hashing is shut down".into()))?; tokio::task::spawn_blocking(move || hash_password(&password)) .await .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))? @@ -171,6 +187,10 @@ pub async fn hash_password_async(password: String) -> forge_core::Result /// Verifies a password with argon2 on the blocking pool. pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result { + let _permit = password_slots() + .acquire() + .await + .map_err(|_| forge_core::Error::Crypto("password verification is shut down".into()))?; tokio::task::spawn_blocking(move || verify_password(&password, &hash)) .await .map_err(|_| forge_core::Error::Crypto("password verification task failed".into())) diff --git a/crates/forge-web/src/exporter.rs b/crates/forge-web/src/exporter.rs index aad9751..58880eb 100644 --- a/crates/forge-web/src/exporter.rs +++ b/crates/forge-web/src/exporter.rs @@ -12,6 +12,7 @@ //! - `repos//releases.json` (release metadata and asset names, not the asset bytes) use std::collections::HashMap; +use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::{LazyLock, Mutex, PoisonError}; use std::time::Duration; @@ -37,9 +38,10 @@ static HUB: LazyLock>>> = /// Follows a user's exports. Subscribe before reading their state. pub fn subscribe(user_id: &str) -> watch::Receiver { - HUB.lock() - .unwrap_or_else(PoisonError::into_inner) - .entry(user_id.to_owned()) + let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); + // Users nobody follows any more are dropped here, so the map stays small. + hub.retain(|_, tx| tx.receiver_count() > 0); + hub.entry(user_id.to_owned()) .or_insert_with(|| watch::channel(0).0) .subscribe() } @@ -211,6 +213,22 @@ async fn write_json(path: &Path, value: &Value) -> Result<(), String> { .map_err(|e| e.to_string()) } +/// Appends one element of a pretty-printed JSON array, indented as `to_vec_pretty` would indent it. +/// JSON strings never hold a raw newline, so every newline in the element is structural. +fn write_array_item( + out: &mut impl Write, + written: &mut usize, + value: &Value, +) -> Result<(), String> { + let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; + let lead: &[u8] = if *written == 0 { b"[\n " } else { b",\n " }; + out.write_all(lead) + .and_then(|()| out.write_all(text.replace('\n', "\n ").as_bytes())) + .map_err(|e| e.to_string())?; + *written += 1; + Ok(()) +} + /// The account fields worth taking along. Never the password hash. pub fn profile_json(user: &User) -> Value { json!({ @@ -260,7 +278,11 @@ async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), Str }); write_json(&dir.join("repo.json"), &meta).await?; - let mut issues = Vec::new(); + // Issues go to the file as they are built, so a repo's issues are never all in memory at once. + let mut out = BufWriter::new( + std::fs::File::create(dir.join("issues.json")).map_err(|e| e.to_string())?, + ); + let mut written = 0usize; let mut page = 1; loop { let filter = IssueFilter { @@ -294,14 +316,17 @@ async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), Str .map_err(|e| e.to_string())?; let names: HashMap = names.into_iter().map(|(k, (name, _))| (k, name)).collect(); - issues.push(issue_json(&item, &comments, &names)); + write_array_item(&mut out, &mut written, &issue_json(&item, &comments, &names))?; } if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total { break; } page += 1; } - write_json(&dir.join("issues.json"), &Value::Array(issues)).await?; + // Closes the array the same way to_vec_pretty would, so the file reads as before. + out.write_all(if written == 0 { b"[]" } else { b"\n]" }) + .and_then(|()| out.flush()) + .map_err(|e| e.to_string())?; let releases = state .store diff --git a/crates/forge-web/src/git_http.rs b/crates/forge-web/src/git_http.rs index c1bec6b..a5f1a57 100644 --- a/crates/forge-web/src/git_http.rs +++ b/crates/forge-web/src/git_http.rs @@ -70,19 +70,17 @@ async fn info_refs(cx: &Cx) -> topcoat::Result { ) .output() .await; - let refs = match advertisement { + let mut payload = match advertisement { Ok(refs) => refs, Err(e) => { tracing::error!(error = %e, service = service.name(), "info/refs failed"); return Ok(internal_error()); } }; - - let mut payload = Vec::with_capacity(refs.len() + 64); + // Splicing in front reuses the advertisement's buffer instead of copying it into a new one. if needs_service_header(service, wants_v2(protocol)) { - payload.extend(pktline::service_advertisement_header(service)); + payload.splice(..0, pktline::service_advertisement_header(service)); } - payload.extend(refs); Ok(respond( StatusCode::OK, @@ -188,7 +186,12 @@ async fn pump_request(body: Body, gzip: bool, mut stdin: ChildStdin) { async fn reap(mut child: Child, service: GitService) { let mut stderr_buf = Vec::new(); if let Some(mut stderr) = child.stderr.take() { - let _ = stderr.read_to_end(&mut stderr_buf).await; + // Only the first 64 KiB is logged. The rest is drained so git never blocks on a full pipe. + let _ = (&mut stderr) + .take(64 * 1024) + .read_to_end(&mut stderr_buf) + .await; + let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await; } let stderr_text = String::from_utf8_lossy(&stderr_buf); match child.wait().await { diff --git a/crates/forge-web/src/importer/api.rs b/crates/forge-web/src/importer/api.rs index f9c8e83..6b88f24 100644 --- a/crates/forge-web/src/importer/api.rs +++ b/crates/forge-web/src/importer/api.rs @@ -5,15 +5,21 @@ use std::fmt; use std::future::Future; +use std::io; use std::sync::Arc; use std::time::Duration; +use bytes::Bytes; +use futures_util::stream::{BoxStream, StreamExt}; use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER}; use serde::Deserialize; use serde::de::DeserializeOwned; use crate::webhooks::client::{WebhookPolicy, validate_url}; +/// A release asset's bytes as they arrive from the server, ready for the blob writer. +pub type AssetStream = BoxStream<'static, io::Result>; + const PER_PAGE: usize = 100; /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever. /// Forgejo and Gitea cap `limit` at 50 by default. @@ -145,12 +151,12 @@ pub trait RemoteApi: Send + Sync { issue: &ExtIssue, ) -> impl Future>> + Send; fn releases(&self, repo: &str) -> impl Future>> + Send; - /// The bytes of a release asset, at most `max_bytes`. + /// The bytes of a release asset, at most `max_bytes`, streamed as they arrive. fn download( &self, asset: &ExtAsset, max_bytes: u64, - ) -> impl Future>> + Send; + ) -> impl Future> + Send; } /// True for one URL path segment of an owner, repo or group name. @@ -378,9 +384,9 @@ impl Http { } /// Downloads a file, following redirects by hand: the token goes to the API host only, and - /// each hop is fetched under the same address policy as every other request. - pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult> { - let max = usize::try_from(max_bytes).unwrap_or(usize::MAX); + /// each hop is fetched under the same address policy as every other request. The body is + /// streamed, so a large asset is never held in memory whole. + pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult { let mut current = url.to_owned(); for _ in 0..=MAX_REDIRECTS { let resp = self @@ -408,10 +414,28 @@ impl Http { { return Err(ApiError::TooLarge); } - return Self::body(resp, max).await; + return Ok(Self::stream(resp, max_bytes)); } Err(ApiError::Http("too many redirects".into())) } + + /// The body as it arrives. Counting happens here, so the stream fails with `InvalidData` as + /// soon as more than `max` bytes have come, whether or not the server sent a length. + fn stream(resp: reqwest::Response, max: u64) -> AssetStream { + let mut seen: u64 = 0; + Box::pin(resp.bytes_stream().map(move |chunk| { + let chunk: reqwest::Result = chunk; + let chunk = chunk.map_err(|e| io::Error::other(e.without_url().to_string()))?; + seen = seen.saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); + if seen > max { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "the file is larger than the allowed size", + )); + } + Ok(chunk) + })) + } } fn day(stamp: &str) -> Option { @@ -726,7 +750,7 @@ impl RemoteApi for GitHub { Ok(raw.into_iter().map(gh_release).collect()) } - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult> { + async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult { if !asset.url.starts_with("https://api.github.com/") { return Err(ApiError::Http("unexpected asset address".into())); } @@ -1077,7 +1101,7 @@ impl RemoteApi for GitLab { Ok(raw.into_iter().map(gl_release).collect()) } - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult> { + async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult { if !asset.url.starts_with("https://") { return Err(ApiError::Http("unexpected asset address".into())); } @@ -1377,7 +1401,7 @@ impl RemoteApi for Forgejo { Ok(raw.into_iter().map(fj_release).collect()) } - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult> { + async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult { if !asset.url.starts_with(&format!("{}/", self.origin)) { return Err(ApiError::Http("unexpected asset address".into())); } diff --git a/crates/forge-web/src/importer/mod.rs b/crates/forge-web/src/importer/mod.rs index ea758f9..eca1f9d 100644 --- a/crates/forge-web/src/importer/mod.rs +++ b/crates/forge-web/src/importer/mod.rs @@ -1051,8 +1051,8 @@ impl Run<'_, A> { self.rep .log("info", format!("Downloading asset {}", asset.name)) .await; - let bytes = match self.api.download(asset, max_bytes).await { - Ok(bytes) => bytes, + let stream = match self.api.download(asset, max_bytes).await { + Ok(stream) => stream, Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => { return Err(e.to_string()); } @@ -1066,8 +1066,6 @@ impl Run<'_, A> { }; let name = asset_name(&asset.name); let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str()); - let stream = - futures_util::stream::iter([Ok::<_, std::io::Error>(bytes::Bytes::from(bytes))]); match crate::release_ops::put_asset( self.state, self.repo, diff --git a/crates/forge-web/src/importer/tests.rs b/crates/forge-web/src/importer/tests.rs index 9deb26a..210b1a5 100644 --- a/crates/forge-web/src/importer/tests.rs +++ b/crates/forge-web/src/importer/tests.rs @@ -10,8 +10,8 @@ use forge_core::store::imports::{ImportJob, ImportState}; use forge_core::{IssueState, Visibility}; use super::api::{ - ApiError, ApiResult, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, ExtRelease, - ExtRepo, RemoteApi, + ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, + ExtRelease, ExtRepo, RemoteApi, }; use super::{ ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note, @@ -71,11 +71,15 @@ impl RemoteApi for Fake { Ok(self.releases.clone()) } - async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult> { - self.files + async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult { + let bytes = self + .files .get(&asset.url) .cloned() - .ok_or_else(|| ApiError::NotFound("asset".into())) + .ok_or_else(|| ApiError::NotFound("asset".into()))?; + Ok(Box::pin(futures_util::stream::once(async move { + Ok::<_, std::io::Error>(bytes::Bytes::from(bytes)) + }))) } } diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index c7bcb7c..100c636 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -120,6 +120,12 @@ fn main() -> ExitCode { if raw.first().is_some_and(|arg| arg == "runner") { return forge_runner::cli::main_with_args("forge runner", raw.into_iter().skip(1)); } + // mimalloc (turso's global allocator) madvises its arenas for transparent huge pages, so each + // touched 2 MiB region becomes resident whole: about a third of the server's RSS. Set after + // the runner dispatch so CI jobs, which inherit the flag, keep THP for compilers. + if let Err(e) = nix::sys::prctl::set_thp_disable(true) { + eprintln!("forge: cannot disable transparent huge pages: {e}"); + } let runtime = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() diff --git a/crates/forge-web/src/oci/manifests.rs b/crates/forge-web/src/oci/manifests.rs index a16ed2d..c018714 100644 --- a/crates/forge-web/src/oci/manifests.rs +++ b/crates/forge-web/src/oci/manifests.rs @@ -225,10 +225,12 @@ pub async fn get_manifest( Ok(None) => return manifest_unknown(), Err(e) => return internal(e), }; + // Taken before the content is moved into the body. + let len = manifest.content.len(); let mut res = Response::new(if head { Body::empty() } else { - Body::from(manifest.content.clone()) + Body::from(manifest.content) }); *res.status_mut() = StatusCode::OK; if let Ok(value) = HeaderValue::from_str(&manifest.media_type) { @@ -236,7 +238,7 @@ pub async fn get_manifest( } insert(&mut res, "docker-content-digest", &manifest.digest); res.headers_mut() - .insert(CONTENT_LENGTH, HeaderValue::from(manifest.content.len())); + .insert(CONTENT_LENGTH, HeaderValue::from(len)); res } diff --git a/crates/forge-web/src/packages_live.rs b/crates/forge-web/src/packages_live.rs index 2d7208a..b72c732 100644 --- a/crates/forge-web/src/packages_live.rs +++ b/crates/forge-web/src/packages_live.rs @@ -22,7 +22,9 @@ impl PackagesLive { /// after this call wakes it. Subscribe before the state you read, so a change in between is /// not lost. pub fn subscribe(&self, owner_id: &str) -> watch::Receiver { - self.owners() + let mut owners = self.owners(); + owners.retain(|_, tx| tx.receiver_count() > 0); + owners .entry(owner_id.to_owned()) .or_insert_with(|| watch::channel(0).0) .subscribe() diff --git a/crates/forge-web/src/pages/code_live.rs b/crates/forge-web/src/pages/code_live.rs index e1eec36..1ee0de0 100644 --- a/crates/forge-web/src/pages/code_live.rs +++ b/crates/forge-web/src/pages/code_live.rs @@ -91,7 +91,7 @@ async fn header_fingerprint( return Ok(String::new()); }; let stars = state.store.star_count(repo_id).await?; - let watchers = state.store.watchers(repo_id).await?.len(); + let watchers = state.store.watcher_count(repo_id).await?; let forks = fork_count(state, repo_id).await?; let (open_issues, _) = state.store.issue_counts(repo_id).await?; let (open_pulls, _) = state.store.pull_counts(repo_id).await?; @@ -110,7 +110,7 @@ async fn header_fingerprint( ), None => String::new(), }; - Ok(header_text(&repo, [stars, watchers as u64, forks, open_issues, open_pulls], &format!( + Ok(header_text(&repo, [stars, watchers, forks, open_issues, open_pulls], &format!( "{discussions} {wiki} {watch}\n{mirror}" ))) } diff --git a/crates/forge-web/src/pages/repo_ctx.rs b/crates/forge-web/src/pages/repo_ctx.rs index 96eb2ca..d1a6721 100644 --- a/crates/forge-web/src/pages/repo_ctx.rs +++ b/crates/forge-web/src/pages/repo_ctx.rs @@ -213,8 +213,7 @@ impl RepoCtx { }), None => None, }; - let watchers = - u64::try_from(state.store.watchers(&self.repo.id).await?.len()).unwrap_or(u64::MAX); + let watchers = state.store.watcher_count(&self.repo.id).await?; let watch = match &self.viewer { Some((user, session)) => Some(WatchButton { level: state.store.watch_level(&user.id, &self.repo.id).await?, @@ -275,12 +274,7 @@ impl RepoCtx { /// Load `owner/name` for the current viewer, or 404. /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`). pub async fn fork_count(state: &AppState, repo_id: &str) -> Result { - let forks = state.store.list_forks(repo_id).await?; - let public = forks - .iter() - .filter(|fork| fork.visibility == Visibility::Public) - .count(); - Ok(u64::try_from(public).unwrap_or(u64::MAX)) + Ok(state.store.public_fork_count(repo_id).await?) } pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result { diff --git a/crates/forge-web/src/pages/repo_side.rs b/crates/forge-web/src/pages/repo_side.rs index ea7835d..0129471 100644 --- a/crates/forge-web/src/pages/repo_side.rs +++ b/crates/forge-web/src/pages/repo_side.rs @@ -100,10 +100,12 @@ pub async fn tree_facts( size, languages: languages(&files, TOP_LANGUAGES), }; - cache() - .lock() - .expect("facts cache") - .insert(repo.id.clone(), (commit.to_owned(), facts.clone())); + let mut map = cache().lock().expect("facts cache"); + // Bounded: at the cap the whole map is dropped; entries refill on the next reads. + if map.len() >= 512 { + map.clear(); + } + map.insert(repo.id.clone(), (commit.to_owned(), facts.clone())); Ok(facts) } diff --git a/crates/forge-web/src/pages/settings_profile.rs b/crates/forge-web/src/pages/settings_profile.rs index 0276d02..1d4cadd 100644 --- a/crates/forge-web/src/pages/settings_profile.rs +++ b/crates/forge-web/src/pages/settings_profile.rs @@ -2,12 +2,15 @@ //! capitalization, the "about" text and the timezone. The avatar menu beside it posts to its own upload and removal //! routes. Every POST checks the CSRF token first. +use std::sync::{Arc, OnceLock}; + use forge_core::AuditAction; use forge_core::names::capitalization_change; use forge_core::store::MAX_DISPLAY_NAME_CHARS; use forge_core::tz::{all_timezones, validate_timezone}; use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar}; use serde::Deserialize; +use tokio::sync::Semaphore; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; @@ -286,6 +289,15 @@ fn field_message(err: forge_core::Error) -> Result { } } +/// Avatar uploads processed at once, server-wide. +const MAX_CONCURRENT_AVATARS: usize = 2; + +/// Permits for avatar processing. A permit is held until the decode and resize finish. +fn avatar_slots() -> &'static Arc { + static SLOTS: OnceLock> = OnceLock::new(); + SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_AVATARS))) +} + /// Stores a processed avatar, or removes it if no image was sent. async fn store_avatar( store: &Store, @@ -298,7 +310,9 @@ async fn store_avatar( t(lang, Key::ErrChooseImage).into(), )); }; - // Decoding and resizing are CPU-bound; keep them off the async workers. + // Decoding and resizing are CPU-bound; keep them off the async workers. A decode can take + // around 128 MiB, so only a couple run at once. + let _permit = avatar_slots().acquire().await.map_err(std::io::Error::other)?; let joined = tokio::task::spawn_blocking(move || process_avatar(&bytes)).await; let processed = joined.map_err(std::io::Error::other)??; store diff --git a/crates/forge-web/src/render/highlight.rs b/crates/forge-web/src/render/highlight.rs index 9e559b1..7dbc9c9 100644 --- a/crates/forge-web/src/render/highlight.rs +++ b/crates/forge-web/src/render/highlight.rs @@ -29,7 +29,6 @@ const DARK_WHEN_FORCED: &str = ":root[data-theme=\"dark\"]"; // Newline-aware syntaxes are required because input is fed through LinesWithEndings. static SYNTAX_SET: LazyLock = LazyLock::new(SyntaxSet::load_defaults_newlines); -static THEME_SET: LazyLock = LazyLock::new(ThemeSet::load_defaults); static CSS: LazyLock = LazyLock::new(build_css); fn class_style() -> ClassStyle { @@ -111,11 +110,13 @@ pub fn highlight_lines(file_name: &str, text: &str) -> Option> { } fn build_css() -> String { - let light = THEME_SET + // Local so the theme set is freed once the CSS is built; only the CSS string is kept. + let theme_set = ThemeSet::load_defaults(); + let light = theme_set .themes .get(LIGHT_THEME) .expect("syntect default theme InspiredGitHub is present"); - let dark = THEME_SET + let dark = theme_set .themes .get(DARK_THEME) .expect("syntect default theme base16-ocean.dark is present"); diff --git a/crates/forge-web/src/render/markdown.rs b/crates/forge-web/src/render/markdown.rs index 2b51d73..5d69b72 100644 --- a/crates/forge-web/src/render/markdown.rs +++ b/crates/forge-web/src/render/markdown.rs @@ -8,6 +8,7 @@ use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::ops::Range; +use std::sync::LazyLock; use ammonia::{Builder, UrlRelative}; use comrak::nodes::{Ast, AstNode, NodeLink, NodeValue}; @@ -66,7 +67,7 @@ pub fn render_markdown(src: &str, ctx: Option<&LinkContext>) -> String { if format_html(root, &options, &mut html).is_err() { return String::new(); } - sanitizer().clean(&apply_link_classes(&html)).to_string() + SANITIZER.clean(&apply_link_classes(&html)).to_string() } fn markdown_options() -> Options<'static> { @@ -757,6 +758,9 @@ const SCRIPT_LIKE: &[&str] = &[ "svg", "math", "form", ]; +/// Built once: the allowlist is fixed, and rebuilding it per render allocated every set again. +static SANITIZER: LazyLock> = LazyLock::new(sanitizer); + /// The strict allowlist. Anything not listed here is removed, and so are all `style` /// and `on*` attributes, because they are not in any attribute list. fn sanitizer() -> Builder<'static> { diff --git a/crates/forge-web/src/throttle.rs b/crates/forge-web/src/throttle.rs index 5e16626..1457335 100644 --- a/crates/forge-web/src/throttle.rs +++ b/crates/forge-web/src/throttle.rs @@ -21,7 +21,7 @@ pub const GIT_IP_LIMIT: usize = 30; /// Failed second-factor checks (login and settings) allowed per user inside [`WINDOW`]. pub const TWO_FACTOR_USER_LIMIT: usize = 10; /// Maximum number of distinct keys tracked at once. -const MAX_KEYS: usize = 100_000; +const MAX_KEYS: usize = 20_000; /// Run a full prune every this many recorded failures. const PRUNE_EVERY: u32 = 256; diff --git a/deploy/forge.service b/deploy/forge.service index eefd41f..6f58c0b 100644 --- a/deploy/forge.service +++ b/deploy/forge.service @@ -10,6 +10,9 @@ Type=simple User=forge Group=forge Environment=FORGE_CONFIG=/etc/forge/forge.toml +# forge turns transparent huge pages off itself at start; this also makes the allocator return +# memory in small pieces, which keeps a further ~7% off the resident size. +Environment=MIMALLOC_ALLOW_THP=0 ExecStart=/usr/local/bin/forge serve WorkingDirectory=/var/lib/forge Restart=on-failure