forge
Explore
Log in

Don't you dare go Hollow

Forge uses about a quarter less memory: the server turns off transparent huge pages at start (mimalloc's 2 MiB pages counted whole: 166 → 123 MB after a seeded 600-page crawl, 63 → 40 MB at boot) and the unit sets MIMALLOC_ALLOW_THP=0

Browse files at this commit

cae59729d957d668c2be5e66e99a4d5d42328a0eAhmet Kaan GümüşParent: 2dd2054
Some checks failed
Show checks
  • perf
    • forge uses about a quarter less memory: the server turns off transparent huge pages at start (mimalloc's 2 MiB pages counted whole: 166 → 123 MB after a seeded 600-page crawl, 63 → 40 MB at boot) and the unit sets MIMALLOC_ALLOW_THP=0
    • worst cases are bounded across the crates: gix's delta cache is 16 MB per open, not 96 MB
    • blob reads don't copy and text reads check the size first
    • file listings, git stderr, grep lines and fsck output are capped
    • readers keep a 2 MiB page cache
    • the advisory import and the issue export stream in batches and an import commits only when parsing finished
    • imported release assets stream to storage
    • argon2 (4) and avatar decodes (2) are capped server-wide
    • SSH takes at most 256 connections
    • watcher, fork and admin counts are SQL counts
    • the runner keeps a 2 MiB log tail per job, drops output once nothing reads it, stops artifact walks at the cap and refuses image configs over 4 MiB
Show full message
⚡ perf: forge uses about a quarter less memory: the server turns off transparent huge pages at start (mimalloc's 2 MiB pages counted whole: 166 → 123 MB after a seeded 600-page crawl, 63 → 40 MB at boot) and the unit sets MIMALLOC_ALLOW_THP=0; worst cases are bounded across the crates: gix's delta cache is 16 MB per open, not 96 MB; blob reads don't copy and text reads check the size first; file listings, git stderr, grep lines and fsck output are capped; readers keep a 2 MiB page cache; the advisory import and the issue export stream in batches and an import commits only when parsing finished; imported release assets stream to storage; argon2 (4) and avatar decodes (2) are capped server-wide; SSH takes at most 256 connections; watcher, fork and admin counts are SQL counts; the runner keeps a 2 MiB log tail per job, drops output once nothing reads it, stops artifact walks at the cap and refuses image configs over 4 MiB
crates/forge-core/src/advisories.rsmodified+27 -7
@@ -182,12 +182,21 @@ pub fn parse_record(json: &[u8], ecosystem: &str) -> Result<Vec<Advisory>> {
182 Ok(merged.into_values().collect())182 Ok(merged.into_values().collect())
183 }183 }
184 184
185-/// Reads every `.json` record of an OSV zip dump for `ecosystem`. A record that does not parse,185+/// Advisories handed to the sink of [`read_dump`] at a time.
186-/// or is too large, is skipped and counted in the second value.186+const IMPORT_BATCH: usize = 500;
187-pub fn read_dump<R: Read + Seek>(reader: R, ecosystem: &str) -> Result<(Vec<Advisory>, usize)> {187+
188+/// Reads every `.json` record of an OSV zip dump for `ecosystem`, handing the advisories to `sink`
189+/// in batches of about [`IMPORT_BATCH`], so the whole dump is never held in memory. A record that
190+/// does not parse, or is too large, is skipped and counted in the returned value. An error from
191+/// the sink or from a broken zip stops the read and is returned.
192+pub fn read_dump<R, F>(reader: R, ecosystem: &str, mut sink: F) -> Result<usize>
193+where
194+ R: Read + Seek,
195+ F: FnMut(Vec<Advisory>) -> Result<()>,
196+{
188 let mut zip = zip::ZipArchive::new(reader)197 let mut zip = zip::ZipArchive::new(reader)
189 .map_err(|e| Error::Invalid(format!("advisory dump is not a zip file: {e}")))?;198 .map_err(|e| Error::Invalid(format!("advisory dump is not a zip file: {e}")))?;
190- let mut advisories = Vec::new();199+ let mut pending = Vec::new();
191 let mut skipped = 0;200 let mut skipped = 0;
192 for index in 0..zip.len() {201 for index in 0..zip.len() {
193 let mut file = zip202 let mut file = zip
@@ -205,11 +214,17 @@ pub fn read_dump<R: Read + Seek>(reader: R, ecosystem: &str) -> Result<(Vec<Advi
205 continue;214 continue;
206 }215 }
207 match parse_record(&buf, ecosystem) {216 match parse_record(&buf, ecosystem) {
208- Ok(found) => advisories.extend(found),217+ Ok(found) => pending.extend(found),
209 Err(_) => skipped += 1,218 Err(_) => skipped += 1,
210 }219 }
220+ if pending.len() >= IMPORT_BATCH {
221+ sink(std::mem::take(&mut pending))?;
222+ }
223+ }
224+ if !pending.is_empty() {
225+ sink(pending)?;
211 }226 }
212- Ok((advisories, skipped))227+ Ok(skipped)
213 }228 }
214 229
215 /// Parses a version as semver, after dropping a leading `v` (Go style).230 /// Parses a version as semver, after dropping a leading `v` (Go style).
@@ -503,7 +518,12 @@ mod tests {
503 zip.finish().expect("finish");518 zip.finish().expect("finish");
504 }519 }
505 buf.set_position(0);520 buf.set_position(0);
506- let (found, skipped) = read_dump(buf, "npm").expect("dump reads");521+ let mut found = Vec::new();
522+ let skipped = read_dump(buf, "npm", |batch| {
523+ found.extend(batch);
524+ Ok(())
525+ })
526+ .expect("dump reads");
507 assert_eq!(skipped, 1);527 assert_eq!(skipped, 1);
508 assert_eq!(found.len(), 1);528 assert_eq!(found.len(), 1);
509 assert_eq!(found[0].package, "left");529 assert_eq!(found[0].package, "left");
crates/forge-core/src/avatar.rsmodified+14 -11
@@ -56,17 +56,20 @@ pub fn process_avatar(bytes: &[u8]) -> Result<ProcessedAvatar> {
56 limits.max_alloc = Some(MAX_ALLOC_BYTES);56 limits.max_alloc = Some(MAX_ALLOC_BYTES);
57 reader.limits(limits);57 reader.limits(limits);
58 58
59- let decoded = reader59+ // Center-crop to the largest square, then scale down to the avatar size. The decoded image
60- .decode()60+ // (up to 128 MiB) is dropped as soon as the crop copies it, before the resize allocates.
61- .map_err(|e| Error::Invalid(format!("could not decode avatar: {e}")))?;61+ let resized = {
62-62+ let decoded = reader
63- // Center-crop to the largest square, then scale down to the avatar size.63+ .decode()
64- let (width, height) = (decoded.width(), decoded.height());64+ .map_err(|e| Error::Invalid(format!("could not decode avatar: {e}")))?;
65- let side = width.min(height);65+ let (width, height) = (decoded.width(), decoded.height());
66- let x = (width - side) / 2;66+ let side = width.min(height);
67- let y = (height - side) / 2;67+ let x = (width - side) / 2;
68- let square = decoded.crop_imm(x, y, side, side);68+ let y = (height - side) / 2;
69- let resized = square.resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3);69+ let square = decoded.crop_imm(x, y, side, side);
70+ drop(decoded);
71+ square.resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3)
72+ };
70 73
71 let mut png = Cursor::new(Vec::new());74 let mut png = Cursor::new(Vec::new());
72 resized75 resized
crates/forge-core/src/store/advisories.rsmodified+62 -30
@@ -7,6 +7,7 @@
7 7
8 use std::collections::{BTreeSet, HashMap};8 use std::collections::{BTreeSet, HashMap};
9 9
10+use tokio::sync::mpsc;
10 use turso::{Row, Value};11 use turso::{Row, Value};
11 12
12 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish};13 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<Value> {
131 }132 }
132 133
133 impl Store {134 impl Store {
134- /// Replaces every advisory of `ecosystem` with `advisories`, in one transaction. Rows for other135+ /// Replaces every advisory of `ecosystem` with the advisories received from `batches`, in one
135- /// ecosystems are not touched. Callers rescan the repos afterwards.136+ /// transaction, so the old rows stay until the last batch is in. The sender ends with `Ok(None)`
136- pub async fn replace_advisories(&self, ecosystem: &str, advisories: &[Advisory]) -> Result<()> {137+ /// to commit; an `Err` item, or the channel closing without `Ok(None)` (the parser died), rolls
138+ /// back. Rows for other ecosystems are not touched. Returns how many advisories were stored.
139+ /// Callers rescan the repos afterwards.
140+ pub async fn replace_advisories(
141+ &self,
142+ ecosystem: &str,
143+ mut batches: mpsc::Receiver<Result<Option<Vec<Advisory>>>>,
144+ ) -> Result<usize> {
137 let conn = self.inner.conn.lock().await;145 let conn = self.inner.conn.lock().await;
138 let tx = conn.unchecked_transaction().await.map_err(db_err)?;146 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
139- let outcome: Result<()> = async {147+ let outcome: Result<usize> = async {
140 tx.execute(148 tx.execute(
141 "DELETE FROM advisories WHERE ecosystem = ?1",149 "DELETE FROM advisories WHERE ecosystem = ?1",
142 (ecosystem.to_string(),),150 (ecosystem.to_string(),),
143 )151 )
144 .await152 .await
145 .map_err(db_err)?;153 .map_err(db_err)?;
146- for advisory in advisories {154+ let mut stored = 0;
147- if advisory.ecosystem != ecosystem {155+ loop {
148- continue;156+ let Some(batch) = batches.recv().await else {
157+ return Err(Error::Invalid("advisory import ended without finishing".into()));
158+ };
159+ let Some(batch) = batch? else {
160+ break;
161+ };
162+ for advisory in batch {
163+ if advisory.ecosystem != ecosystem {
164+ continue;
165+ }
166+ let params = vec![
167+ Value::Text(advisory.id.clone()),
168+ Value::Text(advisory.ecosystem.clone()),
169+ Value::Text(advisory.package.clone()),
170+ Value::Text(advisory.summary.clone()),
171+ Value::Text(advisory.severity.clone()),
172+ Value::Text(serde_json::to_string(&advisory.ranges).map_err(json_err)?),
173+ Value::Text(serde_json::to_string(&advisory.versions).map_err(json_err)?),
174+ Value::Text(advisory.modified.clone()),
175+ ];
176+ tx.execute(
177+ "INSERT OR REPLACE INTO advisories (id, ecosystem, package, summary, severity, \
178+ ranges_json, versions_json, modified) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
179+ params,
180+ )
181+ .await
182+ .map_err(db_err)?;
183+ stored += 1;
149 }184 }
150- let params = vec![
151- Value::Text(advisory.id.clone()),
152- Value::Text(advisory.ecosystem.clone()),
153- Value::Text(advisory.package.clone()),
154- Value::Text(advisory.summary.clone()),
155- Value::Text(advisory.severity.clone()),
156- Value::Text(serde_json::to_string(&advisory.ranges).map_err(json_err)?),
157- Value::Text(serde_json::to_string(&advisory.versions).map_err(json_err)?),
158- Value::Text(advisory.modified.clone()),
159- ];
160- tx.execute(
161- "INSERT OR REPLACE INTO advisories (id, ecosystem, package, summary, severity, \
162- ranges_json, versions_json, modified) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
163- params,
164- )
165- .await
166- .map_err(db_err)?;
167 }185 }
168- Ok(())186+ Ok(stored)
169 }187 }
170 .await;188 .await;
171 finish(tx, outcome).await189 finish(tx, outcome).await
@@ -537,6 +555,20 @@ mod tests {
537 use crate::advisories::{Event, Range};555 use crate::advisories::{Event, Range};
538 use crate::store::Store;556 use crate::store::Store;
539 557
558+ impl Store {
559+ /// Replaces `ecosystem` with `advisories` sent as one batch.
560+ async fn replace_in_one_batch(
561+ &self,
562+ ecosystem: &str,
563+ advisories: &[Advisory],
564+ ) -> Result<usize> {
565+ let (tx, rx) = mpsc::channel(2);
566+ tx.send(Ok(Some(advisories.to_vec()))).await.unwrap();
567+ tx.send(Ok(None)).await.unwrap();
568+ self.replace_advisories(ecosystem, rx).await
569+ }
570+ }
571+
540 fn advisory(id: &str, package: &str, fixed: &str) -> Advisory {572 fn advisory(id: &str, package: &str, fixed: &str) -> Advisory {
541 Advisory {573 Advisory {
542 id: id.into(),574 id: id.into(),
@@ -584,7 +616,7 @@ mod tests {
584 616
585 // A scan opens alerts, closes fixed ones, and keeps dismissed ones.617 // A scan opens alerts, closes fixed ones, and keeps dismissed ones.
586 store618 store
587- .replace_advisories(619+ .replace_in_one_batch(
588 "crates.io",620 "crates.io",
589 &[621 &[
590 advisory("RUSTSEC-1", "old", "2.0.0"),622 advisory("RUSTSEC-1", "old", "2.0.0"),
@@ -696,7 +728,7 @@ mod tests {
696 .unwrap()728 .unwrap()
697 .id;729 .id;
698 store730 store
699- .replace_advisories("crates.io", &[advisory("RUSTSEC-3", "back", "2.0.0")])731+ .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-3", "back", "2.0.0")])
700 .await732 .await
701 .unwrap();733 .unwrap();
702 store734 store
@@ -725,10 +757,10 @@ mod tests {
725 757
726 // Replacing advisories for one ecosystem leaves the others alone.758 // Replacing advisories for one ecosystem leaves the others alone.
727 store759 store
728- .replace_advisories("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")])760+ .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")])
729 .await761 .await
730 .unwrap();762 .unwrap();
731- store.replace_advisories("npm", &[]).await.unwrap();763+ store.replace_in_one_batch("npm", &[]).await.unwrap();
732 assert_eq!(764 assert_eq!(
733 store765 store
734 .advisories_for_package("crates.io", "a")766 .advisories_for_package("crates.io", "a")
@@ -739,7 +771,7 @@ mod tests {
739 "crates.io advisory kept"771 "crates.io advisory kept"
740 );772 );
741 store773 store
742- .replace_advisories("crates.io", &[advisory("RUSTSEC-5", "a", "3.0.0")])774+ .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-5", "a", "3.0.0")])
743 .await775 .await
744 .unwrap();776 .unwrap();
745 let rows = store777 let rows = store
crates/forge-core/src/store/mod.rsmodified+12 -0
@@ -155,6 +155,7 @@ impl Store {
155 let reader = db.connect().map_err(db_err)?;155 let reader = db.connect().map_err(db_err)?;
156 apply_pragmas(&reader).await;156 apply_pragmas(&reader).await;
157 apply_query_only(&reader).await?;157 apply_query_only(&reader).await?;
158+ apply_reader_cache_size(&reader).await?;
158 readers.push(Mutex::new(reader));159 readers.push(Mutex::new(reader));
159 }160 }
160 Ok(Store {161 Ok(Store {
@@ -971,6 +972,17 @@ async fn apply_query_only(conn: &Connection) -> Result<()> {
971 Ok(())972 Ok(())
972 }973 }
973 974
975+/// Caps each reader's page cache at 2 MiB (negative means KiB). Turso gives every connection
976+/// its own cache, so the default 2000 pages (~8 MB) per reader adds up across the pool.
977+async fn apply_reader_cache_size(conn: &Connection) -> Result<()> {
978+ let mut rows = conn
979+ .query("PRAGMA cache_size = -2048", ())
980+ .await
981+ .map_err(db_err)?;
982+ while rows.next().await.map_err(db_err)?.is_some() {}
983+ Ok(())
984+}
985+
974 /// Applies the connection PRAGMAs. Unsupported ones are logged and skipped, never fatal.986 /// Applies the connection PRAGMAs. Unsupported ones are logged and skipped, never fatal.
975 /// The values actually in effect are logged after the attempt.987 /// The values actually in effect are logged after the attempt.
976 async fn apply_pragmas(conn: &Connection) {988 async fn apply_pragmas(conn: &Connection) {
crates/forge-core/src/store/notifications.rsmodified+28 -2
@@ -5,9 +5,9 @@ use turso::{Row, Value};
5 5
6 use super::issues::finish;6 use super::issues::finish;
7 use super::repo_listing::READABLE_BY_VIEWER;7 use super::repo_listing::READABLE_BY_VIEWER;
8-use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id};8+use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, map_user, new_id};
9 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
10-use crate::model::Id;10+use crate::model::{Id, User};
11 use crate::notifications::{Notification, Reason, SubState, WatchLevel};11 use crate::notifications::{Notification, Reason, SubState, WatchLevel};
12 use crate::time::now_stamp;12 use crate::time::now_stamp;
13 13
@@ -137,6 +137,32 @@ impl Store {
137 .await137 .await
138 }138 }
139 139
140+ /// How many users watch the repo at level `watching` (the count of `watchers`).
141+ pub async fn watcher_count(&self, repo_id: &str) -> Result<u64> {
142+ let conn = self.read_conn().await;
143+ let n = fetch_opt(
144+ &conn,
145+ "SELECT COUNT(*) FROM repo_watches WHERE repo_id = ?1 AND level = 'watching'",
146+ (repo_id.to_string(),),
147+ |row| col_int(row, 0),
148+ )
149+ .await?
150+ .unwrap_or(0);
151+ Ok(u64::try_from(n).unwrap_or(0))
152+ }
153+
154+ /// The site admins (accounts with `is_admin` set), ordered by username.
155+ pub async fn list_admins(&self) -> Result<Vec<User>> {
156+ let conn = self.read_conn().await;
157+ fetch_all(
158+ &conn,
159+ &format!("SELECT {USER_COLS} FROM users WHERE is_admin = 1 ORDER BY username_folded"),
160+ (),
161+ map_user,
162+ )
163+ .await
164+ }
165+
140 /// Sets the user's subscription on an issue or pull, replacing any existing row. This is166 /// Sets the user's subscription on an issue or pull, replacing any existing row. This is
141 /// the explicit user action.167 /// the explicit user action.
142 pub async fn subscribe(168 pub async fn subscribe(
crates/forge-core/src/store/pulls.rsmodified+15 -0
@@ -610,6 +610,21 @@ impl Store {
610 )610 )
611 .await611 .await
612 }612 }
613+
614+ /// How many public forks the repo has (the count of `list_forks` filtered to public).
615+ pub async fn public_fork_count(&self, repo_id: &str) -> Result<u64> {
616+ let conn = self.read_conn().await;
617+ let n = fetch_opt(
618+ &conn,
619+ "SELECT COUNT(*) FROM repos r JOIN users u ON u.id = r.owner_id \
620+ WHERE r.fork_of = ?1 AND r.visibility = 'public'",
621+ (repo_id.to_string(),),
622+ |row| col_int(row, 0),
623+ )
624+ .await?
625+ .unwrap_or(0);
626+ Ok(u64::try_from(n).unwrap_or(0))
627+ }
613 }628 }
614 629
615 #[cfg(test)]630 #[cfg(test)]
crates/forge-git/src/browse.rsmodified+30 -12
@@ -75,8 +75,11 @@ fn gerr(e: impl std::fmt::Display) -> Error {
75 Error::Failed(e.to_string())75 Error::Failed(e.to_string())
76 }76 }
77 77
78+/// Every call opens a new handle, and gix's default delta-base cache is 96 MB per handle, so it is
79+/// capped here.
78 fn open(repo: &Path) -> Result<gix::Repository> {80 fn open(repo: &Path) -> Result<gix::Repository> {
79- gix::open_opts(repo, gix::open::Options::isolated()).map_err(gerr)81+ let options = gix::open::Options::isolated().config_overrides(["core.deltaBaseCacheLimit=16m"]);
82+ gix::open_opts(repo, options).map_err(gerr)
80 }83 }
81 84
82 /// Git's ref-name rules (check-ref-format), plus rejection of anything that could be read as85 /// 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(
333 commit: &str,336 commit: &str,
334 path: &str,337 path: &str,
335 max_bytes: usize,338 max_bytes: usize,
339+) -> Result<Option<BlobData>> {
340+ blob_at(repo, commit, path, max_bytes, false)
341+}
342+
343+/// `text_only` makes a blob larger than `max_bytes` yield None before its data is loaded.
344+fn blob_at(
345+ repo: &Path,
346+ commit: &str,
347+ path: &str,
348+ max_bytes: usize,
349+ text_only: bool,
336 ) -> Result<Option<BlobData>> {350 ) -> Result<Option<BlobData>> {
337 validate_repo_path(path)?;351 validate_repo_path(path)?;
338 if path.is_empty() {352 if path.is_empty() {
@@ -360,12 +374,19 @@ pub fn read_blob(
360 is_binary: false,374 is_binary: false,
361 })),375 })),
362 EntryKind::Blob | EntryKind::Executable | EntryKind::Symlink => {376 EntryKind::Blob | EntryKind::Executable | EntryKind::Symlink => {
363- let blob = repo.find_blob(oid).map_err(gerr)?;377+ if text_only && repo.find_header(oid).map_err(gerr)?.size() > max_bytes as u64 {
364- let full = &blob.data;378+ return Ok(None);
365- let size = full.len() as u64;379+ }
366- let is_binary = full[..full.len().min(BINARY_PROBE_BYTES)].contains(&0);380+ let mut blob = repo.find_blob(oid).map_err(gerr)?;
367- let truncated = full.len() > max_bytes;381+ let mut data = blob.take_data();
368- let data = full[..full.len().min(max_bytes)].to_vec();382+ let size = data.len() as u64;
383+ let is_binary = data[..data.len().min(BINARY_PROBE_BYTES)].contains(&0);
384+ let truncated = data.len() > max_bytes;
385+ if truncated {
386+ // Give back the memory of the dropped tail, not just its length.
387+ data.truncate(max_bytes);
388+ data.shrink_to_fit();
389+ }
369 Ok(Some(BlobData {390 Ok(Some(BlobData {
370 oid: oid.to_hex().to_string(),391 oid: oid.to_hex().to_string(),
371 kind,392 kind,
@@ -386,13 +407,10 @@ pub fn read_text_blob(
386 path: &str,407 path: &str,
387 max_bytes: usize,408 max_bytes: usize,
388 ) -> Result<Option<String>> {409 ) -> Result<Option<String>> {
389- let Some(blob) = read_blob(repo, commit, path, max_bytes)? else {410+ let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else {
390 return Ok(None);411 return Ok(None);
391 };412 };
392- if matches!(blob.kind, EntryKind::Tree | EntryKind::Submodule)413+ if matches!(blob.kind, EntryKind::Tree | EntryKind::Submodule) || blob.is_binary {
393- || blob.truncated
394- || blob.is_binary
395- {
396 return Ok(None);414 return Ok(None);
397 }415 }
398 Ok(String::from_utf8(blob.data).ok())416 Ok(String::from_utf8(blob.data).ok())
crates/forge-git/src/fsck.rsmodified+32 -7
@@ -2,11 +2,17 @@
2 2
3 use std::path::Path;3 use std::path::Path;
4 4
5+use std::process::Stdio;
6+
5 use crate::command::{GitCommand, GitEnv};7 use crate::command::{GitCommand, GitEnv};
6 use crate::error::Result;8 use crate::error::Result;
9+use crate::history::read_pipe_head;
10+
11+/// Longest git output kept, in bytes.
12+const MAX_OUTPUT_BYTES: usize = 64 * 1024;
7 13
8-/// Outcome of [`fsck`]. `output` holds git's diagnostics (stdout and stderr, trimmed). It is14+/// Outcome of [`fsck`]. `output` holds git's diagnostics (stdout and stderr, trimmed, at most
9-/// empty when the repo is clean.15+/// 64 KiB). It is empty when the repo is clean.
10 #[derive(Debug, Clone, PartialEq, Eq)]16 #[derive(Debug, Clone, PartialEq, Eq)]
11 pub struct FsckReport {17 pub struct FsckReport {
12 pub ok: bool,18 pub ok: bool,
@@ -17,15 +23,34 @@ pub struct FsckReport {
17 /// one with damaged objects, is a report with `ok` false, not an error. Only a failure to start23 /// one with damaged objects, is a report with `ok` false, not an error. Only a failure to start
18 /// git is an error.24 /// git is an error.
19 pub async fn fsck(env: &GitEnv, repo: &Path, full: bool) -> Result<FsckReport> {25 pub async fn fsck(env: &GitEnv, repo: &Path, full: bool) -> Result<FsckReport> {
20- let mut cmd = GitCommand::new(env, "fsck").git_dir(repo);26+ // Dangling objects are not problems and would only pad the output.
27+ let mut cmd = GitCommand::new(env, "fsck")
28+ .git_dir(repo)
29+ .arg("--no-dangling");
21 if full {30 if full {
22 cmd = cmd.arg("--full");31 cmd = cmd.arg("--full");
23 }32 }
24- let out = cmd.into_tokio().output().await?;33+ let mut command = cmd.into_tokio();
25- let mut text = String::from_utf8_lossy(&out.stdout).into_owned();34+ command
26- text.push_str(&String::from_utf8_lossy(&out.stderr));35+ .stdin(Stdio::null())
36+ .stdout(Stdio::piped())
37+ .stderr(Stdio::piped());
38+ let mut child = command.spawn()?;
39+ let stdout = child.stdout.take().map(|p| tokio::spawn(read_pipe_head(p)));
40+ let stderr = child.stderr.take().map(|p| tokio::spawn(read_pipe_head(p)));
41+ let status = child.wait().await?;
42+ let mut text = String::new();
43+ for task in [stdout, stderr].into_iter().flatten() {
44+ text.push_str(&String::from_utf8_lossy(&task.await.unwrap_or_default()));
45+ }
46+ // Each pipe keeps its own head, so the two together can exceed the cap.
47+ let mut end = text.len().min(MAX_OUTPUT_BYTES);
48+ while !text.is_char_boundary(end) {
49+ end -= 1;
50+ }
51+ text.truncate(end);
27 Ok(FsckReport {52 Ok(FsckReport {
28- ok: out.status.success(),53+ ok: status.success(),
29 output: text.trim().to_owned(),54 output: text.trim().to_owned(),
30 })55 })
31 }56 }
crates/forge-git/src/history.rsmodified+59 -41
@@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet};
5 use std::path::Path;5 use std::path::Path;
6 use std::process::Stdio;6 use std::process::Stdio;
7 7
8-use tokio::io::AsyncReadExt;8+use tokio::io::{AsyncRead, AsyncReadExt};
9 9
10 use crate::browse::{self, CommitInfo};10 use crate::browse::{self, CommitInfo};
11 use crate::command::{GitCommand, GitEnv, ObjectSource};11 use crate::command::{GitCommand, GitEnv, ObjectSource};
@@ -127,6 +127,18 @@ fn validate_prefix(prefix: &str) -> Result<()> {
127 Ok(())127 Ok(())
128 }128 }
129 129
130+/// Longest kept head of a child's output pipe, in bytes.
131+const PIPE_HEAD_CAP: u64 = 64 * 1024;
132+
133+/// Keeps the first [`PIPE_HEAD_CAP`] bytes of a child's output pipe. The rest is read and
134+/// dropped, so the child never blocks on a full pipe while it is being waited for.
135+pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec<u8> {
136+ let mut kept = Vec::new();
137+ let _ = (&mut pipe).take(PIPE_HEAD_CAP).read_to_end(&mut kept).await;
138+ let _ = tokio::io::copy(&mut pipe, &mut tokio::io::sink()).await;
139+ kept
140+}
141+
130 /// Feeds stdout chunks to `f` until EOF, until `f` returns false, or until142 /// Feeds stdout chunks to `f` until EOF, until `f` returns false, or until
131 /// [`OUTPUT_CAP`] bytes. Returns `true` only when EOF was reached. A non-zero exit143 /// [`OUTPUT_CAP`] bytes. Returns `true` only when EOF was reached. A non-zero exit
132 /// after EOF becomes `Error::Failed` with stderr.144 /// 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
138 .stdout150 .stdout
139 .take()151 .take()
140 .ok_or_else(|| Error::Failed("git stdout missing".into()))?;152 .ok_or_else(|| Error::Failed("git stdout missing".into()))?;
141- let stderr_task = child.stderr.take().map(|mut e| {153+ let stderr_task = child.stderr.take().map(|e| tokio::spawn(read_pipe_head(e)));
142- tokio::spawn(async move {
143- let mut v = Vec::new();
144- let _ = e.read_to_end(&mut v).await;
145- v
146- })
147- });
148 154
149 let mut chunk = vec![0u8; 64 * 1024];155 let mut chunk = vec![0u8; 64 * 1024];
150 let mut total = 0usize;156 let mut total = 0usize;
@@ -191,6 +197,28 @@ pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> {
191 Ok((buf, complete))197 Ok((buf, complete))
192 }198 }
193 199
200+/// Feeds each NUL-terminated record of stdout to `f` as it arrives, until `f` returns false.
201+/// Empty records are skipped and a record cut off by the output cap is dropped. Returns `true`
202+/// only when EOF was reached.
203+async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {
204+ let mut carry = Vec::new();
205+ for_each_chunk(cmd, |chunk| {
206+ let mut rest = chunk;
207+ while let Some(end) = rest.iter().position(|&b| b == 0) {
208+ carry.extend_from_slice(&rest[..end]);
209+ rest = &rest[end + 1..];
210+ let keep_going = carry.is_empty() || f(&carry);
211+ carry.clear();
212+ if !keep_going {
213+ return false;
214+ }
215+ }
216+ carry.extend_from_slice(rest);
217+ true
218+ })
219+ .await
220+}
221+
194 /// Parses one record (the bytes after a `%x1e` up to the next one). Returns the commit222 /// Parses one record (the bytes after a `%x1e` up to the next one). Returns the commit
195 /// and the bytes after `%x1d` (file names when `--name-only` is used).223 /// and the bytes after `%x1d` (file names when `--name-only` is used).
196 fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {224 fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {
@@ -815,24 +843,18 @@ pub async fn list_files(
815 .arg("--name-only")843 .arg("--name-only")
816 .arg("--full-tree")844 .arg("--full-tree")
817 .user_revs(&[commit])?;845 .user_revs(&[commit])?;
818- let (buf, complete) = read_capped(cmd).await?;846+ let mut paths = Vec::new();
819- let mut paths: Vec<&[u8]> = buf.split(|&b| b == 0).filter(|p| !p.is_empty()).collect();847+ let mut cut = false;
820- let mut cut = !complete;848+ let complete = for_each_nul_record(cmd, |path| {
821- if !complete {849+ if paths.len() == max {
822- // The last record may be partial.850+ cut = true;
823- paths.pop();851+ return false;
824- }852+ }
825- if paths.len() > max {853+ paths.push(String::from_utf8_lossy(path).into_owned());
826- paths.truncate(max);854+ true
827- cut = true;855+ })
828- }856+ .await?;
829- Ok((857+ Ok((paths, cut || !complete))
830- paths
831- .into_iter()
832- .map(|p| String::from_utf8_lossy(p).into_owned())
833- .collect(),
834- cut,
835- ))
836 }858 }
837 859
838 /// Every blob in the tree of `commit` with its size in bytes, at most `max` of them. The flag is860 /// 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(
851 .arg("-l")873 .arg("-l")
852 .arg("--full-tree")874 .arg("--full-tree")
853 .user_revs(&[commit])?;875 .user_revs(&[commit])?;
854- let (buf, complete) = read_capped(cmd).await?;
855- let mut recs: Vec<&[u8]> = buf.split(|&b| b == 0).filter(|p| !p.is_empty()).collect();
856- let mut cut = !complete;
857- if !complete {
858- // The last record may be partial.
859- recs.pop();
860- }
861 let mut out = Vec::new();876 let mut out = Vec::new();
862- for rec in recs {877+ let mut cut = false;
878+ let complete = for_each_nul_record(cmd, |rec| {
863 // `<mode> SP <type> SP <oid> SP+ <size>\t<path>`; the path may hold tabs, so split at the first.879 // `<mode> SP <type> SP <oid> SP+ <size>\t<path>`; the path may hold tabs, so split at the first.
864 let Some(tab) = rec.iter().position(|&b| b == b'\t') else {880 let Some(tab) = rec.iter().position(|&b| b == b'\t') else {
865- continue;881+ return true;
866 };882 };
867 let meta = String::from_utf8_lossy(&rec[..tab]);883 let meta = String::from_utf8_lossy(&rec[..tab]);
868 let mut fields = meta.split_whitespace();884 let mut fields = meta.split_whitespace();
869 let (Some(mode), Some(kind), Some(_oid), Some(size)) =885 let (Some(mode), Some(kind), Some(_oid), Some(size)) =
870 (fields.next(), fields.next(), fields.next(), fields.next())886 (fields.next(), fields.next(), fields.next(), fields.next())
871 else {887 else {
872- continue;888+ return true;
873 };889 };
874 if kind != "blob" || mode == "120000" {890 if kind != "blob" || mode == "120000" {
875- continue;891+ return true;
876 }892 }
877 let Ok(size) = size.parse::<u64>() else {893 let Ok(size) = size.parse::<u64>() else {
878- continue;894+ return true;
879 };895 };
880 if out.len() >= max {896 if out.len() >= max {
881 cut = true;897 cut = true;
882- break;898+ return false;
883 }899 }
884 out.push((String::from_utf8_lossy(&rec[tab + 1..]).into_owned(), size));900 out.push((String::from_utf8_lossy(&rec[tab + 1..]).into_owned(), size));
885- }901+ true
886- Ok((out, cut))902+ })
903+ .await?;
904+ Ok((out, cut || !complete))
887 }905 }
888 906
889 /// The newest commit (walking back from `commit`) that touched each direct child of `dir`,907 /// The newest commit (walking back from `commit`) that touched each direct child of `dir`,
crates/forge-git/src/search.rsmodified+36 -16
@@ -6,11 +6,11 @@ use std::path::Path;
6 use std::process::Stdio;6 use std::process::Stdio;
7 use std::time::Duration;7 use std::time::Duration;
8 8
9-use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};9+use tokio::io::{AsyncBufRead, AsyncBufReadExt, BufReader};
10 10
11 use crate::command::GitEnv;11 use crate::command::GitEnv;
12 use crate::error::{Error, Result};12 use crate::error::{Error, Result};
13-use crate::history::{git, validate_oid};13+use crate::history::{git, read_pipe_head, validate_oid};
14 14
15 /// Longest accepted query, in bytes.15 /// Longest accepted query, in bytes.
16 pub const MAX_QUERY_BYTES: usize = 200;16 pub const MAX_QUERY_BYTES: usize = 200;
@@ -18,6 +18,9 @@ pub const MAX_QUERY_BYTES: usize = 200;
18 const MAX_GLOB_BYTES: usize = 512;18 const MAX_GLOB_BYTES: usize = 512;
19 /// Longest line text kept in a hit, in characters.19 /// Longest line text kept in a hit, in characters.
20 const MAX_LINE_CHARS: usize = 500;20 const MAX_LINE_CHARS: usize = 500;
21+/// Bytes kept of one `git grep` output line. Up to 4 bytes per character, so this holds the
22+/// header (commit, path, line number) and `MAX_LINE_CHARS` of text; the rest is dropped unread.
23+const MAX_RECORD_BYTES: usize = 4 * MAX_LINE_CHARS + 4096;
21 24
22 #[derive(Debug, Clone, PartialEq, Eq)]25 #[derive(Debug, Clone, PartialEq, Eq)]
23 pub struct GrepOptions {26 pub struct GrepOptions {
@@ -107,6 +110,34 @@ fn parse_record(record: &[u8], commit: &str) -> Option<GrepHit> {
107 })110 })
108 }111 }
109 112
113+/// Reads one line into `buf`, without its `\n`, keeping at most `keep` bytes of it. The rest of
114+/// the line is consumed and dropped, so a huge line does not allocate its whole size. Returns
115+/// false at end of input.
116+async fn read_line_capped<R: AsyncBufRead + Unpin>(
117+ reader: &mut R,
118+ buf: &mut Vec<u8>,
119+ keep: usize,
120+) -> std::io::Result<bool> {
121+ buf.clear();
122+ let mut started = false;
123+ loop {
124+ let available = reader.fill_buf().await?;
125+ if available.is_empty() {
126+ return Ok(started);
127+ }
128+ started = true;
129+ let newline = available.iter().position(|&b| b == b'\n');
130+ let content = newline.unwrap_or(available.len());
131+ let take = content.min(keep - buf.len());
132+ buf.extend_from_slice(&available[..take]);
133+ let consumed = newline.map_or(available.len(), |i| i + 1);
134+ reader.consume(consumed);
135+ if newline.is_some() {
136+ return Ok(true);
137+ }
138+ }
139+}
140+
110 /// Searches the tree of `commit` for `query`. Exit code 1 from git (no match) is an empty result.141 /// Searches the tree of `commit` for `query`. Exit code 1 from git (no match) is an empty result.
111 pub async fn grep(142 pub async fn grep(
112 env: &GitEnv,143 env: &GitEnv,
@@ -142,13 +173,7 @@ pub async fn grep(
142 .stdout173 .stdout
143 .take()174 .take()
144 .ok_or_else(|| Error::Failed("git stdout missing".into()))?;175 .ok_or_else(|| Error::Failed("git stdout missing".into()))?;
145- let stderr_task = child.stderr.take().map(|mut e| {176+ let stderr_task = child.stderr.take().map(|e| tokio::spawn(read_pipe_head(e)));
146- tokio::spawn(async move {
147- let mut v = Vec::new();
148- let _ = e.read_to_end(&mut v).await;
149- v
150- })
151- });
152 177
153 let max = opts.max_matches;178 let max = opts.max_matches;
154 let mut hits = Vec::new();179 let mut hits = Vec::new();
@@ -156,13 +181,8 @@ pub async fn grep(
156 let reading = async {181 let reading = async {
157 let mut lines = BufReader::new(stdout);182 let mut lines = BufReader::new(stdout);
158 let mut buf = Vec::new();183 let mut buf = Vec::new();
159- loop {184+ while read_line_capped(&mut lines, &mut buf, MAX_RECORD_BYTES).await? {
160- buf.clear();185+ let Some(hit) = parse_record(&buf, commit) else {
161- if lines.read_until(b'\n', &mut buf).await? == 0 {
162- break;
163- }
164- let record = buf.strip_suffix(b"\n").unwrap_or(&buf);
165- let Some(hit) = parse_record(record, commit) else {
166 continue;186 continue;
167 };187 };
168 if hits.len() == max {188 if hits.len() == max {
crates/forge-runner/src/artifacts.rsmodified+3 -3
@@ -129,14 +129,14 @@ pub fn collect(
129 }129 }
130 } else if file_type.is_file() && globs.is_match(&rel) {130 } else if file_type.is_file() && globs.is_match(&rel) {
131 found.push((rel, entry.path()));131 found.push((rel, entry.path()));
132+ if found.len() > MAX_FILES {
133+ return Err(ArtifactError::TooMany);
134+ }
132 }135 }
133 }136 }
134 }137 }
135 138
136 found.sort();139 found.sort();
137- if found.len() > MAX_FILES {
138- return Err(ArtifactError::TooMany);
139- }
140 140
141 let mut seen = HashSet::new();141 let mut seen = HashSet::new();
142 let mut out = Vec::with_capacity(found.len());142 let mut out = Vec::with_capacity(found.len());
crates/forge-runner/src/logs.rsmodified+8 -3
@@ -46,7 +46,7 @@ impl Default for PumpConfig {
46 46
47 /// Bytes kept for resends. Acknowledged bytes are trimmed past this, oldest first. Unacknowledged47 /// Bytes kept for resends. Acknowledged bytes are trimmed past this, oldest first. Unacknowledged
48 /// bytes are never trimmed (they are at most one batch).48 /// bytes are never trimmed (they are at most one batch).
49-pub const RETAIN_CAP: usize = 8 * 1024 * 1024;49+pub const RETAIN_CAP: usize = 2 * 1024 * 1024;
50 /// Written in place of bytes the forge lost and the runner no longer holds.50 /// Written in place of bytes the forge lost and the runner no longer holds.
51 pub const GAP_MARKER: &[u8] = b"[log gap]\n";51 pub const GAP_MARKER: &[u8] = b"[log gap]\n";
52 52
@@ -303,8 +303,13 @@ where
303 (take, done)303 (take, done)
304 };304 };
305 reader.consume(take);305 reader.consume(take);
306- if (done || line.len() >= MAX_LINE) && alive {306+ if done || line.len() >= MAX_LINE {
307- alive = tx.send(std::mem::take(&mut line)).await.is_ok();307+ // Once the receiver is gone, drop the line instead of letting it grow.
308+ if alive {
309+ alive = tx.send(std::mem::take(&mut line)).await.is_ok();
310+ } else {
311+ line.clear();
312+ }
308 }313 }
309 }314 }
310 if !line.is_empty() && alive {315 if !line.is_empty() && alive {
crates/forge-runner/src/oci/mod.rsmodified+2 -0
@@ -31,6 +31,8 @@ pub enum ImageError {
31 #[source]31 #[source]
32 source: oci_client::errors::OciDistributionError,32 source: oci_client::errors::OciDistributionError,
33 },33 },
34+ #[error("image {image} config size {size} is negative or over 4 MiB")]
35+ ConfigTooLarge { image: String, size: i64 },
34 #[error("unsupported or malformed digest {0}, only sha256:<hex> is supported")]36 #[error("unsupported or malformed digest {0}, only sha256:<hex> is supported")]
35 UnsupportedDigest(String),37 UnsupportedDigest(String),
36 #[error("blob digest mismatch: expected {expected}, got {actual}")]38 #[error("blob digest mismatch: expected {expected}, got {actual}")]
crates/forge-runner/src/oci/pull.rsmodified+9 -0
@@ -19,6 +19,9 @@ use super::store::{ImageMeta, ImageStore, lock_file};
19 use super::unpack::{Ownership, UnpackStats, unpack_layers};19 use super::unpack::{Ownership, UnpackStats, unpack_layers};
20 use super::{ImageError, PreparedImage, RegistryAuth};20 use super::{ImageError, PreparedImage, RegistryAuth};
21 21
22+/// Largest image config blob the runner will read into memory.
23+const MAX_CONFIG_BYTES: i64 = 4 * 1024 * 1024;
24+
22 impl ImageStore {25 impl ImageStore {
23 /// Makes `image` available as an unpacked rootfs and returns it with its config.26 /// Makes `image` available as an unpacked rootfs and returns it with its config.
24 ///27 ///
@@ -74,6 +77,12 @@ impl ImageStore {
74 return Ok(prepared);77 return Ok(prepared);
75 }78 }
76 79
80+ if manifest.config.size < 0 || manifest.config.size > MAX_CONFIG_BYTES {
81+ return Err(ImageError::ConfigTooLarge {
82+ image: whole,
83+ size: manifest.config.size,
84+ });
85+ }
77 let mut config_bytes = Vec::new();86 let mut config_bytes = Vec::new();
78 client87 client
79 .pull_blob(&reference, &manifest.config, &mut config_bytes)88 .pull_blob(&reference, &manifest.config, &mut config_bytes)
crates/forge-runner/src/oci/unpack.rsmodified+7 -1
@@ -240,8 +240,14 @@ impl Unpacker {
240 }240 }
241 self.own(&path)?;241 self.own(&path)?;
242 fs::set_permissions(&path, Permissions::from_mode(mode | 0o700))?;242 fs::set_permissions(&path, Permissions::from_mode(mode | 0o700))?;
243+ // Only a directory whose mode is not already owner rwx needs its mode restored.
244+ // A later layer may reset a directory an earlier one recorded, so drop the stale entry.
243 if matches!(self.ownership, Ownership::Preserve { .. }) {245 if matches!(self.ownership, Ownership::Preserve { .. }) {
244- self.dir_modes.insert(path, mode);246+ if mode & 0o700 != 0o700 {
247+ self.dir_modes.insert(path, mode);
248+ } else {
249+ self.dir_modes.remove(&path);
250+ }
245 }251 }
246 self.created.insert(rel);252 self.created.insert(rel);
247 self.stats.dirs += 1;253 self.stats.dirs += 1;
crates/forge-runner/src/runner.rsmodified+1 -1
@@ -27,7 +27,7 @@ use crate::update::{self, Installed, UpdateState};
27 use crate::workspace;27 use crate::workspace;
28 28
29 /// Log lines queued between the executor and the log shipper.29 /// Log lines queued between the executor and the log shipper.
30-const LOG_CHANNEL: usize = 256;30+const LOG_CHANNEL: usize = 64;
31 /// How many times the runner tries to report a finished job.31 /// How many times the runner tries to report a finished job.
32 const FINISH_ATTEMPTS: u32 = 5;32 const FINISH_ATTEMPTS: u32 = 5;
33 /// Largest single artifact the runner will upload. The forge enforces its own total cap.33 /// Largest single artifact the runner will upload. The forge enforces its own total cap.
crates/forge-ssh/src/server.rsmodified+14 -2
@@ -24,7 +24,7 @@ use russh::{Channel, ChannelId, ChannelOpenFailure, Disconnect, MethodKind, Meth
24 use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};24 use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
25 use tokio::net::TcpListener;25 use tokio::net::TcpListener;
26 use tokio::process::{Child, ChildStdin};26 use tokio::process::{Child, ChildStdin};
27-use tokio::sync::{Notify, mpsc};27+use tokio::sync::{Notify, Semaphore, mpsc};
28 28
29 use crate::backend::GitBackend;29 use crate::backend::GitBackend;
30 use crate::error::{Error, Result};30 use crate::error::{Error, Result};
@@ -34,9 +34,12 @@ use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate};
34 const PUMP_CHUNK: usize = 32 * 1024;34 const PUMP_CHUNK: usize = 32 * 1024;
35 /// Client input chunks buffered in front of the child's stdin. This bounds memory and35 /// Client input chunks buffered in front of the child's stdin. This bounds memory and
36 /// propagates backpressure to the SSH read loop.36 /// propagates backpressure to the SSH read loop.
37-const STDIN_QUEUE: usize = 32;37+const STDIN_QUEUE: usize = 8;
38 /// Failed publickey attempts before the connection is dropped.38 /// Failed publickey attempts before the connection is dropped.
39 const MAX_AUTH_ATTEMPTS: usize = 6;39 const MAX_AUTH_ATTEMPTS: usize = 6;
40+/// Connections served at once, counting unauthenticated ones. Each can hold a russh packet
41+/// buffer of up to 256 KiB before auth, so this bounds that memory.
42+const MAX_CONNECTIONS: usize = 256;
40 43
41 #[derive(Debug, Clone)]44 #[derive(Debug, Clone)]
42 pub struct SshConfig {45 pub struct SshConfig {
@@ -64,6 +67,7 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
64 let listener = TcpListener::bind(config.listen).await?;67 let listener = TcpListener::bind(config.listen).await?;
65 tracing::info!(addr = %config.listen, "ssh server listening");68 tracing::info!(addr = %config.listen, "ssh server listening");
66 69
70+ let connection_slots = Arc::new(Semaphore::new(MAX_CONNECTIONS));
67 loop {71 loop {
68 let (stream, peer) = match listener.accept().await {72 let (stream, peer) = match listener.accept().await {
69 Ok(v) => v,73 Ok(v) => v,
@@ -74,6 +78,11 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
74 continue;78 continue;
75 }79 }
76 };80 };
81+ // At the limit the socket is dropped at once rather than queued.
82+ let Ok(permit) = connection_slots.clone().try_acquire_owned() else {
83+ tracing::warn!(%peer, "ssh connection limit reached, dropping connection");
84+ continue;
85+ };
77 let authed = Arc::new(AtomicBool::new(false));86 let authed = Arc::new(AtomicBool::new(false));
78 let client = Client {87 let client = Client {
79 backend: Arc::clone(&backend),88 backend: Arc::clone(&backend),
@@ -86,6 +95,8 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
86 let russh_config = Arc::clone(&russh_config);95 let russh_config = Arc::clone(&russh_config);
87 let auth_timeout = config.auth_timeout;96 let auth_timeout = config.auth_timeout;
88 tokio::spawn(async move {97 tokio::spawn(async move {
98+ // Held until the connection ends, then the slot is free for the next client.
99+ let _permit = permit;
89 let running = match run_stream(russh_config, stream, client).await {100 let running = match run_stream(russh_config, stream, client).await {
90 Ok(running) => running,101 Ok(running) => running,
91 Err(e) => {102 Err(e) => {
@@ -553,6 +564,7 @@ async fn pump<R>(
553 Ok(0) | Err(_) => break,564 Ok(0) | Err(_) => break,
554 Ok(n) => n,565 Ok(n) => n,
555 };566 };
567+ // A right-sized copy: a chunk queued for the client holds only the bytes read.
556 let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default());568 let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default());
557 let sent = match ext {569 let sent = match ext {
558 None => handle.data(channel, chunk).await.is_ok(),570 None => handle.data(channel, chunk).await.is_ok(),
crates/forge-web/src/advisories/worker.rsmodified+35 -18
@@ -12,12 +12,15 @@ use std::io::{BufReader, Write};
12 use std::path::{Path, PathBuf};12 use std::path::{Path, PathBuf};
13 use std::time::{Duration, SystemTime};13 use std::time::{Duration, SystemTime};
14 14
15-use forge_core::advisories::{KNOWN_ECOSYSTEMS, read_dump};15+use forge_core::advisories::{Advisory, KNOWN_ECOSYSTEMS, read_dump};
16 use forge_core::{Error, Result};16 use forge_core::{Error, Result};
17+use tokio::sync::mpsc;
17 18
18 use super::scan::scan_all;19 use super::scan::scan_all;
19 use crate::state::AppState;20 use crate::state::AppState;
20 21
22+/// Batches the parser may have queued ahead of the store's writer.
23+const IMPORT_QUEUE: usize = 2;
21 /// First wait after a failed download. It doubles with each further failure.24 /// First wait after a failed download. It doubles with each further failure.
22 const RETRY_FIRST: Duration = Duration::from_secs(5 * 60);25 const RETRY_FIRST: Duration = Duration::from_secs(5 * 60);
23 /// Longest wait after a failed download.26 /// Longest wait after a failed download.
@@ -204,25 +207,39 @@ async fn fetch_into(client: &reqwest::Client, url: &str, part: &Path) -> Result<
204 Ok(total)207 Ok(total)
205 }208 }
206 209
207-/// Parses the dump on a blocking thread and replaces the stored advisories of `ecosystem`.210+/// Parses the dump on a blocking thread and replaces the stored advisories of `ecosystem`. The
211+/// parser sends its batches over a channel of [`IMPORT_QUEUE`] slots, and the store writes each one
212+/// in the replacement's transaction as it comes, so only a few batches are in memory at a time.
213+/// A parse error goes down the channel as an `Err` item, which rolls the replacement back; only
214+/// the parser's closing `Ok(None)` commits it.
208 async fn import(state: &AppState, ecosystem: &str, path: &Path) -> Result<()> {215 async fn import(state: &AppState, ecosystem: &str, path: &Path) -> Result<()> {
216+ let (tx, rx) = mpsc::channel::<Result<Option<Vec<Advisory>>>>(IMPORT_QUEUE);
209 let owned_path = path.to_owned();217 let owned_path = path.to_owned();
210 let eco = ecosystem.to_owned();218 let eco = ecosystem.to_owned();
211- let (advisories, skipped) = tokio::task::spawn_blocking(move || -> Result<_> {219+ let parser = tokio::task::spawn_blocking(move || -> usize {
212- let file = File::open(&owned_path)?;220+ let parsed = File::open(&owned_path).map_err(Error::from).and_then(|file| {
213- read_dump(BufReader::new(file), &eco)221+ read_dump(BufReader::new(file), &eco, |batch| {
214- })222+ tx.blocking_send(Ok(Some(batch)))
215- .await223+ .map_err(|_| Error::Invalid("advisory import was stopped".into()))
216- .map_err(|e| Error::Invalid(format!("advisory import task failed: {e}")))??;224+ })
217- state225+ });
218- .store226+ // The store commits only on `Ok(None)`, so a panic above (sender dropped) rolls back.
219- .replace_advisories(ecosystem, &advisories)227+ match parsed {
220- .await?;228+ Ok(skipped) => {
221- tracing::info!(229+ let _ = tx.blocking_send(Ok(None));
222- ecosystem,230+ skipped
223- imported = advisories.len(),231+ }
224- skipped,232+ Err(e) => {
225- "advisories: dump imported"233+ let _ = tx.blocking_send(Err(e));
226- );234+ 0
235+ }
236+ }
237+ });
238+ let stored = state.store.replace_advisories(ecosystem, rx).await;
239+ let skipped = parser
240+ .await
241+ .map_err(|e| Error::Invalid(format!("advisory import task failed: {e}")))?;
242+ let imported = stored?;
243+ tracing::info!(ecosystem, imported, skipped, "advisories: dump imported");
227 Ok(())244 Ok(())
228 }245 }
crates/forge-web/src/alerts.rsmodified+3 -3
@@ -108,8 +108,8 @@ async fn deliver(
108 ) {108 ) {
109 // The alert was written (raised, resolved or recorded): the health page follows it.109 // The alert was written (raised, resolved or recorded): the health page follows it.
110 crate::live::admin().bump(&crate::live::Topic::AdminHealth);110 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
111- let users = match state.store.list_users().await {111+ let admins = match state.store.list_admins().await {
112- Ok(users) => users,112+ Ok(admins) => admins,
113 Err(e) => {113 Err(e) => {
114 tracing::error!(error = %e, "alerts: listing the admins failed");114 tracing::error!(error = %e, "alerts: listing the admins failed");
115 return;115 return;
@@ -118,7 +118,7 @@ async fn deliver(
118 let live = state.live();118 let live = state.live();
119 let base = live.base_url.trim_end_matches('/').to_owned();119 let base = live.base_url.trim_end_matches('/').to_owned();
120 let state_word = if resolved { "resolved" } else { "raised" };120 let state_word = if resolved { "resolved" } else { "raised" };
121- for admin in users.into_iter().filter(|u| u.is_admin && !u.is_org()) {121+ for admin in admins.into_iter().filter(|u| !u.is_org()) {
122 if let Err(e) = state122 if let Err(e) = state
123 .store123 .store
124 .add_admin_notice(&admin.id, key, topic, subject, detail, resolved)124 .add_admin_notice(&admin.id, key, topic, subject, detail, resolved)
crates/forge-web/src/auth.rsmodified+20 -0
@@ -3,6 +3,7 @@
3 //! The browser holds the raw session token in `__Host-forge_session`. The database3 //! The browser holds the raw session token in `__Host-forge_session`. The database
4 //! stores only `hash_token(token)`, so a leaked DB row cannot be replayed as a cookie.4 //! stores only `hash_token(token)`, so a leaked DB row cannot be replayed as a cookie.
5 5
6+use std::sync::{Arc, OnceLock};
6 use std::time::Duration;7 use std::time::Duration;
7 8
8 use forge_core::password::{hash_password, verify_password};9 use forge_core::password::{hash_password, verify_password};
@@ -13,6 +14,7 @@ use forge_core::{Session, Store, User, secret, totp};
13 use topcoat::Result;14 use topcoat::Result;
14 use topcoat::context::{Cx, app_context};15 use topcoat::context::{Cx, app_context};
15 use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};16 use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
17+use tokio::sync::Semaphore;
16 use topcoat::router::error::{forbidden, see_other};18 use topcoat::router::error::{forbidden, see_other};
17 use topcoat::router::request::{headers, uri};19 use topcoat::router::request::{headers, uri};
18 20
@@ -162,8 +164,22 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> {
162 .build()164 .build()
163 }165 }
164 166
167+/// Argon2 runs at once, server-wide. Each hash or verify allocates about 19 MiB, so a burst of
168+/// logins would otherwise pile that memory up on the blocking pool.
169+const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4;
170+
171+/// Permits for argon2 work. A permit is held until the hash or verify finishes.
172+fn password_slots() -> &'static Arc<Semaphore> {
173+ static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();
174+ SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES)))
175+}
176+
165 /// Hashes a password with argon2 on the blocking pool, keeping the async runtime free.177 /// Hashes a password with argon2 on the blocking pool, keeping the async runtime free.
166 pub async fn hash_password_async(password: String) -> forge_core::Result<String> {178 pub async fn hash_password_async(password: String) -> forge_core::Result<String> {
179+ let _permit = password_slots()
180+ .acquire()
181+ .await
182+ .map_err(|_| forge_core::Error::Crypto("password hashing is shut down".into()))?;
167 tokio::task::spawn_blocking(move || hash_password(&password))183 tokio::task::spawn_blocking(move || hash_password(&password))
168 .await184 .await
169 .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))?185 .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<String>
171 187
172 /// Verifies a password with argon2 on the blocking pool.188 /// Verifies a password with argon2 on the blocking pool.
173 pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result<bool> {189 pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result<bool> {
190+ let _permit = password_slots()
191+ .acquire()
192+ .await
193+ .map_err(|_| forge_core::Error::Crypto("password verification is shut down".into()))?;
174 tokio::task::spawn_blocking(move || verify_password(&password, &hash))194 tokio::task::spawn_blocking(move || verify_password(&password, &hash))
175 .await195 .await
176 .map_err(|_| forge_core::Error::Crypto("password verification task failed".into()))196 .map_err(|_| forge_core::Error::Crypto("password verification task failed".into()))
crates/forge-web/src/exporter.rsmodified+31 -6
@@ -12,6 +12,7 @@
12 //! - `repos/<name>/releases.json` (release metadata and asset names, not the asset bytes)12 //! - `repos/<name>/releases.json` (release metadata and asset names, not the asset bytes)
13 13
14 use std::collections::HashMap;14 use std::collections::HashMap;
15+use std::io::{BufWriter, Write};
15 use std::path::{Path, PathBuf};16 use std::path::{Path, PathBuf};
16 use std::sync::{LazyLock, Mutex, PoisonError};17 use std::sync::{LazyLock, Mutex, PoisonError};
17 use std::time::Duration;18 use std::time::Duration;
@@ -37,9 +38,10 @@ static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> =
37 38
38 /// Follows a user's exports. Subscribe before reading their state.39 /// Follows a user's exports. Subscribe before reading their state.
39 pub fn subscribe(user_id: &str) -> watch::Receiver<u64> {40 pub fn subscribe(user_id: &str) -> watch::Receiver<u64> {
40- HUB.lock()41+ let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner);
41- .unwrap_or_else(PoisonError::into_inner)42+ // Users nobody follows any more are dropped here, so the map stays small.
42- .entry(user_id.to_owned())43+ hub.retain(|_, tx| tx.receiver_count() > 0);
44+ hub.entry(user_id.to_owned())
43 .or_insert_with(|| watch::channel(0).0)45 .or_insert_with(|| watch::channel(0).0)
44 .subscribe()46 .subscribe()
45 }47 }
@@ -211,6 +213,22 @@ async fn write_json(path: &Path, value: &Value) -> Result<(), String> {
211 .map_err(|e| e.to_string())213 .map_err(|e| e.to_string())
212 }214 }
213 215
216+/// Appends one element of a pretty-printed JSON array, indented as `to_vec_pretty` would indent it.
217+/// JSON strings never hold a raw newline, so every newline in the element is structural.
218+fn write_array_item(
219+ out: &mut impl Write,
220+ written: &mut usize,
221+ value: &Value,
222+) -> Result<(), String> {
223+ let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?;
224+ let lead: &[u8] = if *written == 0 { b"[\n " } else { b",\n " };
225+ out.write_all(lead)
226+ .and_then(|()| out.write_all(text.replace('\n', "\n ").as_bytes()))
227+ .map_err(|e| e.to_string())?;
228+ *written += 1;
229+ Ok(())
230+}
231+
214 /// The account fields worth taking along. Never the password hash.232 /// The account fields worth taking along. Never the password hash.
215 pub fn profile_json(user: &User) -> Value {233 pub fn profile_json(user: &User) -> Value {
216 json!({234 json!({
@@ -260,7 +278,11 @@ async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), Str
260 });278 });
261 write_json(&dir.join("repo.json"), &meta).await?;279 write_json(&dir.join("repo.json"), &meta).await?;
262 280
263- let mut issues = Vec::new();281+ // Issues go to the file as they are built, so a repo's issues are never all in memory at once.
282+ let mut out = BufWriter::new(
283+ std::fs::File::create(dir.join("issues.json")).map_err(|e| e.to_string())?,
284+ );
285+ let mut written = 0usize;
264 let mut page = 1;286 let mut page = 1;
265 loop {287 loop {
266 let filter = IssueFilter {288 let filter = IssueFilter {
@@ -294,14 +316,17 @@ async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), Str
294 .map_err(|e| e.to_string())?;316 .map_err(|e| e.to_string())?;
295 let names: HashMap<String, String> =317 let names: HashMap<String, String> =
296 names.into_iter().map(|(k, (name, _))| (k, name)).collect();318 names.into_iter().map(|(k, (name, _))| (k, name)).collect();
297- issues.push(issue_json(&item, &comments, &names));319+ write_array_item(&mut out, &mut written, &issue_json(&item, &comments, &names))?;
298 }320 }
299 if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total {321 if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total {
300 break;322 break;
301 }323 }
302 page += 1;324 page += 1;
303 }325 }
304- write_json(&dir.join("issues.json"), &Value::Array(issues)).await?;326+ // Closes the array the same way to_vec_pretty would, so the file reads as before.
327+ out.write_all(if written == 0 { b"[]" } else { b"\n]" })
328+ .and_then(|()| out.flush())
329+ .map_err(|e| e.to_string())?;
305 330
306 let releases = state331 let releases = state
307 .store332 .store
crates/forge-web/src/git_http.rsmodified+9 -6
@@ -70,19 +70,17 @@ async fn info_refs(cx: &Cx) -> topcoat::Result<Response> {
70 )70 )
71 .output()71 .output()
72 .await;72 .await;
73- let refs = match advertisement {73+ let mut payload = match advertisement {
74 Ok(refs) => refs,74 Ok(refs) => refs,
75 Err(e) => {75 Err(e) => {
76 tracing::error!(error = %e, service = service.name(), "info/refs failed");76 tracing::error!(error = %e, service = service.name(), "info/refs failed");
77 return Ok(internal_error());77 return Ok(internal_error());
78 }78 }
79 };79 };
80-80+ // Splicing in front reuses the advertisement's buffer instead of copying it into a new one.
81- let mut payload = Vec::with_capacity(refs.len() + 64);
82 if needs_service_header(service, wants_v2(protocol)) {81 if needs_service_header(service, wants_v2(protocol)) {
83- payload.extend(pktline::service_advertisement_header(service));82+ payload.splice(..0, pktline::service_advertisement_header(service));
84 }83 }
85- payload.extend(refs);
86 84
87 Ok(respond(85 Ok(respond(
88 StatusCode::OK,86 StatusCode::OK,
@@ -188,7 +186,12 @@ async fn pump_request(body: Body, gzip: bool, mut stdin: ChildStdin) {
188 async fn reap(mut child: Child, service: GitService) {186 async fn reap(mut child: Child, service: GitService) {
189 let mut stderr_buf = Vec::new();187 let mut stderr_buf = Vec::new();
190 if let Some(mut stderr) = child.stderr.take() {188 if let Some(mut stderr) = child.stderr.take() {
191- let _ = stderr.read_to_end(&mut stderr_buf).await;189+ // Only the first 64 KiB is logged. The rest is drained so git never blocks on a full pipe.
190+ let _ = (&mut stderr)
191+ .take(64 * 1024)
192+ .read_to_end(&mut stderr_buf)
193+ .await;
194+ let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await;
192 }195 }
193 let stderr_text = String::from_utf8_lossy(&stderr_buf);196 let stderr_text = String::from_utf8_lossy(&stderr_buf);
194 match child.wait().await {197 match child.wait().await {
crates/forge-web/src/importer/api.rsmodified+33 -9
@@ -5,15 +5,21 @@
5 5
6 use std::fmt;6 use std::fmt;
7 use std::future::Future;7 use std::future::Future;
8+use std::io;
8 use std::sync::Arc;9 use std::sync::Arc;
9 use std::time::Duration;10 use std::time::Duration;
10 11
12+use bytes::Bytes;
13+use futures_util::stream::{BoxStream, StreamExt};
11 use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER};14 use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER};
12 use serde::Deserialize;15 use serde::Deserialize;
13 use serde::de::DeserializeOwned;16 use serde::de::DeserializeOwned;
14 17
15 use crate::webhooks::client::{WebhookPolicy, validate_url};18 use crate::webhooks::client::{WebhookPolicy, validate_url};
16 19
20+/// A release asset's bytes as they arrive from the server, ready for the blob writer.
21+pub type AssetStream = BoxStream<'static, io::Result<Bytes>>;
22+
17 const PER_PAGE: usize = 100;23 const PER_PAGE: usize = 100;
18 /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.24 /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.
19 /// Forgejo and Gitea cap `limit` at 50 by default.25 /// Forgejo and Gitea cap `limit` at 50 by default.
@@ -145,12 +151,12 @@ pub trait RemoteApi: Send + Sync {
145 issue: &ExtIssue,151 issue: &ExtIssue,
146 ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send;152 ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send;
147 fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send;153 fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send;
148- /// The bytes of a release asset, at most `max_bytes`.154+ /// The bytes of a release asset, at most `max_bytes`, streamed as they arrive.
149 fn download(155 fn download(
150 &self,156 &self,
151 asset: &ExtAsset,157 asset: &ExtAsset,
152 max_bytes: u64,158 max_bytes: u64,
153- ) -> impl Future<Output = ApiResult<Vec<u8>>> + Send;159+ ) -> impl Future<Output = ApiResult<AssetStream>> + Send;
154 }160 }
155 161
156 /// True for one URL path segment of an owner, repo or group name.162 /// True for one URL path segment of an owner, repo or group name.
@@ -378,9 +384,9 @@ impl Http {
378 }384 }
379 385
380 /// Downloads a file, following redirects by hand: the token goes to the API host only, and386 /// Downloads a file, following redirects by hand: the token goes to the API host only, and
381- /// each hop is fetched under the same address policy as every other request.387+ /// each hop is fetched under the same address policy as every other request. The body is
382- pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<Vec<u8>> {388+ /// streamed, so a large asset is never held in memory whole.
383- let max = usize::try_from(max_bytes).unwrap_or(usize::MAX);389+ pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<AssetStream> {
384 let mut current = url.to_owned();390 let mut current = url.to_owned();
385 for _ in 0..=MAX_REDIRECTS {391 for _ in 0..=MAX_REDIRECTS {
386 let resp = self392 let resp = self
@@ -408,10 +414,28 @@ impl Http {
408 {414 {
409 return Err(ApiError::TooLarge);415 return Err(ApiError::TooLarge);
410 }416 }
411- return Self::body(resp, max).await;417+ return Ok(Self::stream(resp, max_bytes));
412 }418 }
413 Err(ApiError::Http("too many redirects".into()))419 Err(ApiError::Http("too many redirects".into()))
414 }420 }
421+
422+ /// The body as it arrives. Counting happens here, so the stream fails with `InvalidData` as
423+ /// soon as more than `max` bytes have come, whether or not the server sent a length.
424+ fn stream(resp: reqwest::Response, max: u64) -> AssetStream {
425+ let mut seen: u64 = 0;
426+ Box::pin(resp.bytes_stream().map(move |chunk| {
427+ let chunk: reqwest::Result<Bytes> = chunk;
428+ let chunk = chunk.map_err(|e| io::Error::other(e.without_url().to_string()))?;
429+ seen = seen.saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX));
430+ if seen > max {
431+ return Err(io::Error::new(
432+ io::ErrorKind::InvalidData,
433+ "the file is larger than the allowed size",
434+ ));
435+ }
436+ Ok(chunk)
437+ }))
438+ }
415 }439 }
416 440
417 fn day(stamp: &str) -> Option<String> {441 fn day(stamp: &str) -> Option<String> {
@@ -726,7 +750,7 @@ impl RemoteApi for GitHub {
726 Ok(raw.into_iter().map(gh_release).collect())750 Ok(raw.into_iter().map(gh_release).collect())
727 }751 }
728 752
729- async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<Vec<u8>> {753+ async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> {
730 if !asset.url.starts_with("https://api.github.com/") {754 if !asset.url.starts_with("https://api.github.com/") {
731 return Err(ApiError::Http("unexpected asset address".into()));755 return Err(ApiError::Http("unexpected asset address".into()));
732 }756 }
@@ -1077,7 +1101,7 @@ impl RemoteApi for GitLab {
1077 Ok(raw.into_iter().map(gl_release).collect())1101 Ok(raw.into_iter().map(gl_release).collect())
1078 }1102 }
1079 1103
1080- async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<Vec<u8>> {1104+ async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> {
1081 if !asset.url.starts_with("https://") {1105 if !asset.url.starts_with("https://") {
1082 return Err(ApiError::Http("unexpected asset address".into()));1106 return Err(ApiError::Http("unexpected asset address".into()));
1083 }1107 }
@@ -1377,7 +1401,7 @@ impl RemoteApi for Forgejo {
1377 Ok(raw.into_iter().map(fj_release).collect())1401 Ok(raw.into_iter().map(fj_release).collect())
1378 }1402 }
1379 1403
1380- async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<Vec<u8>> {1404+ async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> {
1381 if !asset.url.starts_with(&format!("{}/", self.origin)) {1405 if !asset.url.starts_with(&format!("{}/", self.origin)) {
1382 return Err(ApiError::Http("unexpected asset address".into()));1406 return Err(ApiError::Http("unexpected asset address".into()));
1383 }1407 }
crates/forge-web/src/importer/mod.rsmodified+2 -4
@@ -1051,8 +1051,8 @@ impl<A: RemoteApi> Run<'_, A> {
1051 self.rep1051 self.rep
1052 .log("info", format!("Downloading asset {}", asset.name))1052 .log("info", format!("Downloading asset {}", asset.name))
1053 .await;1053 .await;
1054- let bytes = match self.api.download(asset, max_bytes).await {1054+ let stream = match self.api.download(asset, max_bytes).await {
1055- Ok(bytes) => bytes,1055+ Ok(stream) => stream,
1056 Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => {1056 Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => {
1057 return Err(e.to_string());1057 return Err(e.to_string());
1058 }1058 }
@@ -1066,8 +1066,6 @@ impl<A: RemoteApi> Run<'_, A> {
1066 };1066 };
1067 let name = asset_name(&asset.name);1067 let name = asset_name(&asset.name);
1068 let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str());1068 let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str());
1069- let stream =
1070- futures_util::stream::iter([Ok::<_, std::io::Error>(bytes::Bytes::from(bytes))]);
1071 match crate::release_ops::put_asset(1069 match crate::release_ops::put_asset(
1072 self.state,1070 self.state,
1073 self.repo,1071 self.repo,
crates/forge-web/src/importer/tests.rsmodified+9 -5
@@ -10,8 +10,8 @@ use forge_core::store::imports::{ImportJob, ImportState};
10 use forge_core::{IssueState, Visibility};10 use forge_core::{IssueState, Visibility};
11 11
12 use super::api::{12 use super::api::{
13- ApiError, ApiResult, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, ExtRelease,13+ ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone,
14- ExtRepo, RemoteApi,14+ ExtRelease, ExtRepo, RemoteApi,
15 };15 };
16 use super::{16 use super::{
17 ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note,17 ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note,
@@ -71,11 +71,15 @@ impl RemoteApi for Fake {
71 Ok(self.releases.clone())71 Ok(self.releases.clone())
72 }72 }
73 73
74- async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult<Vec<u8>> {74+ async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult<AssetStream> {
75- self.files75+ let bytes = self
76+ .files
76 .get(&asset.url)77 .get(&asset.url)
77 .cloned()78 .cloned()
78- .ok_or_else(|| ApiError::NotFound("asset".into()))79+ .ok_or_else(|| ApiError::NotFound("asset".into()))?;
80+ Ok(Box::pin(futures_util::stream::once(async move {
81+ Ok::<_, std::io::Error>(bytes::Bytes::from(bytes))
82+ })))
79 }83 }
80 }84 }
81 85
crates/forge-web/src/main.rsmodified+6 -0
@@ -120,6 +120,12 @@ fn main() -> ExitCode {
120 if raw.first().is_some_and(|arg| arg == "runner") {120 if raw.first().is_some_and(|arg| arg == "runner") {
121 return forge_runner::cli::main_with_args("forge runner", raw.into_iter().skip(1));121 return forge_runner::cli::main_with_args("forge runner", raw.into_iter().skip(1));
122 }122 }
123+ // mimalloc (turso's global allocator) madvises its arenas for transparent huge pages, so each
124+ // touched 2 MiB region becomes resident whole: about a third of the server's RSS. Set after
125+ // the runner dispatch so CI jobs, which inherit the flag, keep THP for compilers.
126+ if let Err(e) = nix::sys::prctl::set_thp_disable(true) {
127+ eprintln!("forge: cannot disable transparent huge pages: {e}");
128+ }
123 let runtime = match tokio::runtime::Builder::new_multi_thread()129 let runtime = match tokio::runtime::Builder::new_multi_thread()
124 .enable_all()130 .enable_all()
125 .build()131 .build()
crates/forge-web/src/oci/manifests.rsmodified+4 -2
@@ -225,10 +225,12 @@ pub async fn get_manifest(
225 Ok(None) => return manifest_unknown(),225 Ok(None) => return manifest_unknown(),
226 Err(e) => return internal(e),226 Err(e) => return internal(e),
227 };227 };
228+ // Taken before the content is moved into the body.
229+ let len = manifest.content.len();
228 let mut res = Response::new(if head {230 let mut res = Response::new(if head {
229 Body::empty()231 Body::empty()
230 } else {232 } else {
231- Body::from(manifest.content.clone())233+ Body::from(manifest.content)
232 });234 });
233 *res.status_mut() = StatusCode::OK;235 *res.status_mut() = StatusCode::OK;
234 if let Ok(value) = HeaderValue::from_str(&manifest.media_type) {236 if let Ok(value) = HeaderValue::from_str(&manifest.media_type) {
@@ -236,7 +238,7 @@ pub async fn get_manifest(
236 }238 }
237 insert(&mut res, "docker-content-digest", &manifest.digest);239 insert(&mut res, "docker-content-digest", &manifest.digest);
238 res.headers_mut()240 res.headers_mut()
239- .insert(CONTENT_LENGTH, HeaderValue::from(manifest.content.len()));241+ .insert(CONTENT_LENGTH, HeaderValue::from(len));
240 res242 res
241 }243 }
242 244
crates/forge-web/src/packages_live.rsmodified+3 -1
@@ -22,7 +22,9 @@ impl PackagesLive {
22 /// after this call wakes it. Subscribe before the state you read, so a change in between is22 /// after this call wakes it. Subscribe before the state you read, so a change in between is
23 /// not lost.23 /// not lost.
24 pub fn subscribe(&self, owner_id: &str) -> watch::Receiver<u64> {24 pub fn subscribe(&self, owner_id: &str) -> watch::Receiver<u64> {
25- self.owners()25+ let mut owners = self.owners();
26+ owners.retain(|_, tx| tx.receiver_count() > 0);
27+ owners
26 .entry(owner_id.to_owned())28 .entry(owner_id.to_owned())
27 .or_insert_with(|| watch::channel(0).0)29 .or_insert_with(|| watch::channel(0).0)
28 .subscribe()30 .subscribe()
crates/forge-web/src/pages/code_live.rsmodified+2 -2
@@ -91,7 +91,7 @@ async fn header_fingerprint(
91 return Ok(String::new());91 return Ok(String::new());
92 };92 };
93 let stars = state.store.star_count(repo_id).await?;93 let stars = state.store.star_count(repo_id).await?;
94- let watchers = state.store.watchers(repo_id).await?.len();94+ let watchers = state.store.watcher_count(repo_id).await?;
95 let forks = fork_count(state, repo_id).await?;95 let forks = fork_count(state, repo_id).await?;
96 let (open_issues, _) = state.store.issue_counts(repo_id).await?;96 let (open_issues, _) = state.store.issue_counts(repo_id).await?;
97 let (open_pulls, _) = state.store.pull_counts(repo_id).await?;97 let (open_pulls, _) = state.store.pull_counts(repo_id).await?;
@@ -110,7 +110,7 @@ async fn header_fingerprint(
110 ),110 ),
111 None => String::new(),111 None => String::new(),
112 };112 };
113- Ok(header_text(&repo, [stars, watchers as u64, forks, open_issues, open_pulls], &format!(113+ Ok(header_text(&repo, [stars, watchers, forks, open_issues, open_pulls], &format!(
114 "{discussions} {wiki} {watch}\n{mirror}"114 "{discussions} {wiki} {watch}\n{mirror}"
115 )))115 )))
116 }116 }
crates/forge-web/src/pages/repo_ctx.rsmodified+2 -8
@@ -213,8 +213,7 @@ impl RepoCtx {
213 }),213 }),
214 None => None,214 None => None,
215 };215 };
216- let watchers =216+ let watchers = state.store.watcher_count(&self.repo.id).await?;
217- u64::try_from(state.store.watchers(&self.repo.id).await?.len()).unwrap_or(u64::MAX);
218 let watch = match &self.viewer {217 let watch = match &self.viewer {
219 Some((user, session)) => Some(WatchButton {218 Some((user, session)) => Some(WatchButton {
220 level: state.store.watch_level(&user.id, &self.repo.id).await?,219 level: state.store.watch_level(&user.id, &self.repo.id).await?,
@@ -275,12 +274,7 @@ impl RepoCtx {
275 /// Load `owner/name` for the current viewer, or 404.274 /// Load `owner/name` for the current viewer, or 404.
276 /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`).275 /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`).
277 pub async fn fork_count(state: &AppState, repo_id: &str) -> Result<u64> {276 pub async fn fork_count(state: &AppState, repo_id: &str) -> Result<u64> {
278- let forks = state.store.list_forks(repo_id).await?;277+ Ok(state.store.public_fork_count(repo_id).await?)
279- let public = forks
280- .iter()
281- .filter(|fork| fork.visibility == Visibility::Public)
282- .count();
283- Ok(u64::try_from(public).unwrap_or(u64::MAX))
284 }278 }
285 279
286 pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {280 pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {
crates/forge-web/src/pages/repo_side.rsmodified+6 -4
@@ -100,10 +100,12 @@ pub async fn tree_facts(
100 size,100 size,
101 languages: languages(&files, TOP_LANGUAGES),101 languages: languages(&files, TOP_LANGUAGES),
102 };102 };
103- cache()103+ let mut map = cache().lock().expect("facts cache");
104- .lock()104+ // Bounded: at the cap the whole map is dropped; entries refill on the next reads.
105- .expect("facts cache")105+ if map.len() >= 512 {
106- .insert(repo.id.clone(), (commit.to_owned(), facts.clone()));106+ map.clear();
107+ }
108+ map.insert(repo.id.clone(), (commit.to_owned(), facts.clone()));
107 Ok(facts)109 Ok(facts)
108 }110 }
109 111
crates/forge-web/src/pages/settings_profile.rsmodified+15 -1
@@ -2,12 +2,15 @@
2 //! capitalization, the "about" text and the timezone. The avatar menu beside it posts to its own upload and removal2 //! capitalization, the "about" text and the timezone. The avatar menu beside it posts to its own upload and removal
3 //! routes. Every POST checks the CSRF token first.3 //! routes. Every POST checks the CSRF token first.
4 4
5+use std::sync::{Arc, OnceLock};
6+
5 use forge_core::AuditAction;7 use forge_core::AuditAction;
6 use forge_core::names::capitalization_change;8 use forge_core::names::capitalization_change;
7 use forge_core::store::MAX_DISPLAY_NAME_CHARS;9 use forge_core::store::MAX_DISPLAY_NAME_CHARS;
8 use forge_core::tz::{all_timezones, validate_timezone};10 use forge_core::tz::{all_timezones, validate_timezone};
9 use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar};11 use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar};
10 use serde::Deserialize;12 use serde::Deserialize;
13+use tokio::sync::Semaphore;
11 use topcoat::Result;14 use topcoat::Result;
12 use topcoat::context::{Cx, app_context};15 use topcoat::context::{Cx, app_context};
13 use topcoat::router::content::Form;16 use topcoat::router::content::Form;
@@ -286,6 +289,15 @@ fn field_message(err: forge_core::Error) -> Result<String> {
286 }289 }
287 }290 }
288 291
292+/// Avatar uploads processed at once, server-wide.
293+const MAX_CONCURRENT_AVATARS: usize = 2;
294+
295+/// Permits for avatar processing. A permit is held until the decode and resize finish.
296+fn avatar_slots() -> &'static Arc<Semaphore> {
297+ static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();
298+ SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_AVATARS)))
299+}
300+
289 /// Stores a processed avatar, or removes it if no image was sent.301 /// Stores a processed avatar, or removes it if no image was sent.
290 async fn store_avatar(302 async fn store_avatar(
291 store: &Store,303 store: &Store,
@@ -298,7 +310,9 @@ async fn store_avatar(
298 t(lang, Key::ErrChooseImage).into(),310 t(lang, Key::ErrChooseImage).into(),
299 ));311 ));
300 };312 };
301- // Decoding and resizing are CPU-bound; keep them off the async workers.313+ // Decoding and resizing are CPU-bound; keep them off the async workers. A decode can take
314+ // around 128 MiB, so only a couple run at once.
315+ let _permit = avatar_slots().acquire().await.map_err(std::io::Error::other)?;
302 let joined = tokio::task::spawn_blocking(move || process_avatar(&bytes)).await;316 let joined = tokio::task::spawn_blocking(move || process_avatar(&bytes)).await;
303 let processed = joined.map_err(std::io::Error::other)??;317 let processed = joined.map_err(std::io::Error::other)??;
304 store318 store
crates/forge-web/src/render/highlight.rsmodified+4 -3
@@ -29,7 +29,6 @@ const DARK_WHEN_FORCED: &str = ":root[data-theme=\"dark\"]";
29 29
30 // Newline-aware syntaxes are required because input is fed through LinesWithEndings.30 // Newline-aware syntaxes are required because input is fed through LinesWithEndings.
31 static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);31 static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
32-static THEME_SET: LazyLock<ThemeSet> = LazyLock::new(ThemeSet::load_defaults);
33 static CSS: LazyLock<String> = LazyLock::new(build_css);32 static CSS: LazyLock<String> = LazyLock::new(build_css);
34 33
35 fn class_style() -> ClassStyle {34 fn class_style() -> ClassStyle {
@@ -111,11 +110,13 @@ pub fn highlight_lines(file_name: &str, text: &str) -> Option<Vec<String>> {
111 }110 }
112 111
113 fn build_css() -> String {112 fn build_css() -> String {
114- let light = THEME_SET113+ // Local so the theme set is freed once the CSS is built; only the CSS string is kept.
114+ let theme_set = ThemeSet::load_defaults();
115+ let light = theme_set
115 .themes116 .themes
116 .get(LIGHT_THEME)117 .get(LIGHT_THEME)
117 .expect("syntect default theme InspiredGitHub is present");118 .expect("syntect default theme InspiredGitHub is present");
118- let dark = THEME_SET119+ let dark = theme_set
119 .themes120 .themes
120 .get(DARK_THEME)121 .get(DARK_THEME)
121 .expect("syntect default theme base16-ocean.dark is present");122 .expect("syntect default theme base16-ocean.dark is present");
crates/forge-web/src/render/markdown.rsmodified+5 -1
@@ -8,6 +8,7 @@
8 use std::borrow::Cow;8 use std::borrow::Cow;
9 use std::collections::{HashMap, HashSet};9 use std::collections::{HashMap, HashSet};
10 use std::ops::Range;10 use std::ops::Range;
11+use std::sync::LazyLock;
11 12
12 use ammonia::{Builder, UrlRelative};13 use ammonia::{Builder, UrlRelative};
13 use comrak::nodes::{Ast, AstNode, NodeLink, NodeValue};14 use comrak::nodes::{Ast, AstNode, NodeLink, NodeValue};
@@ -66,7 +67,7 @@ pub fn render_markdown(src: &str, ctx: Option<&LinkContext>) -> String {
66 if format_html(root, &options, &mut html).is_err() {67 if format_html(root, &options, &mut html).is_err() {
67 return String::new();68 return String::new();
68 }69 }
69- sanitizer().clean(&apply_link_classes(&html)).to_string()70+ SANITIZER.clean(&apply_link_classes(&html)).to_string()
70 }71 }
71 72
72 fn markdown_options() -> Options<'static> {73 fn markdown_options() -> Options<'static> {
@@ -757,6 +758,9 @@ const SCRIPT_LIKE: &[&str] = &[
757 "svg", "math", "form",758 "svg", "math", "form",
758 ];759 ];
759 760
761+/// Built once: the allowlist is fixed, and rebuilding it per render allocated every set again.
762+static SANITIZER: LazyLock<Builder<'static>> = LazyLock::new(sanitizer);
763+
760 /// The strict allowlist. Anything not listed here is removed, and so are all `style`764 /// The strict allowlist. Anything not listed here is removed, and so are all `style`
761 /// and `on*` attributes, because they are not in any attribute list.765 /// and `on*` attributes, because they are not in any attribute list.
762 fn sanitizer() -> Builder<'static> {766 fn sanitizer() -> Builder<'static> {
crates/forge-web/src/throttle.rsmodified+1 -1
@@ -21,7 +21,7 @@ pub const GIT_IP_LIMIT: usize = 30;
21 /// Failed second-factor checks (login and settings) allowed per user inside [`WINDOW`].21 /// Failed second-factor checks (login and settings) allowed per user inside [`WINDOW`].
22 pub const TWO_FACTOR_USER_LIMIT: usize = 10;22 pub const TWO_FACTOR_USER_LIMIT: usize = 10;
23 /// Maximum number of distinct keys tracked at once.23 /// Maximum number of distinct keys tracked at once.
24-const MAX_KEYS: usize = 100_000;24+const MAX_KEYS: usize = 20_000;
25 /// Run a full prune every this many recorded failures.25 /// Run a full prune every this many recorded failures.
26 const PRUNE_EVERY: u32 = 256;26 const PRUNE_EVERY: u32 = 256;
27 27
deploy/forge.servicemodified+3 -0
@@ -10,6 +10,9 @@ Type=simple
10 User=forge10 User=forge
11 Group=forge11 Group=forge
12 Environment=FORGE_CONFIG=/etc/forge/forge.toml12 Environment=FORGE_CONFIG=/etc/forge/forge.toml
13+# forge turns transparent huge pages off itself at start; this also makes the allocator return
14+# memory in small pieces, which keeps a further ~7% off the resident size.
15+Environment=MIMALLOC_ALLOW_THP=0
13 ExecStart=/usr/local/bin/forge serve16 ExecStart=/usr/local/bin/forge serve
14 WorkingDirectory=/var/lib/forge17 WorkingDirectory=/var/lib/forge
15 Restart=on-failure18 Restart=on-failure