From 0e57f13c08573706fac1e1962556906c646ac805 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 20:36:50 +0100 Subject: [PATCH] fix(server): cap the event long-polls that wait at once Every event long-poll waits, up to a minute, on a thread of the blocking pool that every service call runs on, and nothing limited them: 512 waiting polls took the whole pool, and reads and writes queued behind them. Repositories now hands out at most 256 places for polls to wait in, each held until its poll ends. A poll that finds none free waits for one asynchronously, without a thread, for at most its own wait, which it shortens by as much, so a saturated server answers late rather than refusing, and clients need no new error. --- Cargo.toml | 2 +- apps/origin-src/src/http.rs | 13 ++++++++---- apps/origin-src/src/server.rs | 37 +++++++++++++++++++++++++++++++---- docs/openapi.json | 2 +- 4 files changed, 44 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6402d796..ba95d4e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,7 @@ serde_json = "1.0.154" similar = "3.2.0" tempfile = "3.27.0" thiserror = "2.0.21" -tokio = { version = "1.53.3", features = ["macros", "net", "rt-multi-thread", "signal"] } +tokio = { version = "1.53.3", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } toml = "1.1.8" tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter", "fmt"] } diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index 58274c3b..81bd2b86 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -609,7 +609,9 @@ async fn landings( } /// Reads the events after a cursor, waiting up to `wait` for some: a -/// long-poll. Pass the page's `next` as the next request's cursor. +/// long-poll. Pass the page's `next` as the next request's cursor. While +/// the server has too many long-polls waiting, it waits for one to end +/// first, which counts toward `wait`. #[utoipa::path( get, path = "/api/v1/repos/{repo}/events", @@ -622,12 +624,15 @@ async fn landings( ) )] async fn events( - repos: Repos, + State(repositories): Repos, Path(repo): Path, caller: Caller, - Query(query): Query, + Query(mut query): Query, ) -> Result, HttpError> { - call(repos, repo, caller, move |service, caller| { + let permit = repositories.poll(&mut query).await; + call(State(repositories), repo, caller, move |service, caller| { + // Held until the poll ends. + let _permit = permit; service.events(caller, &query) }) .await diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 38da0569..99ed8c5d 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -11,13 +11,14 @@ use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use anyhow::Context; use origin_shared::access::{Capability, Token}; -use origin_shared::api::{RepoName, RepoSummary}; -use origin_shared::{Principal, PrincipalName}; +use origin_shared::api::{EventsQuery, RepoName, RepoSummary}; +use origin_shared::{Period, Principal, PrincipalName}; use serde::Deserialize; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use crate::auth::{Credentials, StaticTokens}; use crate::config::KeyFile; @@ -189,24 +190,52 @@ impl ServerConfig { } /// The repositories a server hosts, each served by the server's node and -/// kept open while it runs, and how it tells its callers apart. +/// kept open while it runs, how it tells its callers apart, and the places +/// event long-polls wait in. #[derive(Debug)] pub struct Repositories { repos: BTreeMap, credentials: Credentials, + polls: Arc, } impl Repositories { /// How often [`Repositories::compact_in_background`] checks. const COMPACT_EVERY: Duration = Duration::from_mins(1); + /// How many event long-polls wait at once, each on a thread of the + /// blocking pool, of 512 threads: the rest stay free for every other + /// call. + const MAX_POLLS: usize = 256; + /// No repositories yet, for callers `credentials` tells apart. #[must_use] pub fn new(credentials: Credentials) -> Self { Self { repos: BTreeMap::new(), credentials, + polls: Arc::new(Semaphore::new(Self::MAX_POLLS)), + } + } + + /// Takes one of the [`Repositories::MAX_POLLS`] places an event + /// long-poll waits in, to hold until it ends, if `query` waits. If none + /// is free, it waits for one, without taking a thread, for at most as + /// long as `query` would wait for events, and shortens that wait by as + /// much: to none if no place freed up, so the poll answers at once. + pub async fn poll(&self, query: &mut EventsQuery) -> Option { + let wait = query.wait?.duration().min(OriginService::MAX_WAIT); + if wait.is_zero() { + return None; + } + if let Ok(permit) = Arc::clone(&self.polls).try_acquire_owned() { + return Some(permit); } + let start = Instant::now(); + let permit = tokio::time::timeout(wait, Arc::clone(&self.polls).acquire_owned()).await; + let left = wait.saturating_sub(start.elapsed()); + query.wait = Some(Period::from_secs(left.as_secs())); + permit.ok().and_then(Result::ok) } /// Opens the repositories at the given paths, served by `node`, and diff --git a/docs/openapi.json b/docs/openapi.json index 6f47cd52..9503fdcb 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -160,7 +160,7 @@ }, "/api/v1/repos/{repo}/events": { "get": { - "summary": "Reads the events after a cursor, waiting up to `wait` for some: a\nlong-poll. Pass the page's `next` as the next request's cursor.", + "summary": "Reads the events after a cursor, waiting up to `wait` for some: a\nlong-poll. Pass the page's `next` as the next request's cursor. While\nthe server has too many long-polls waiting, it waits for one to end\nfirst, which counts toward `wait`.", "operationId": "events", "parameters": [ {