Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
13 changes: 9 additions & 4 deletions apps/origin-src/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -622,12 +624,15 @@ async fn landings(
)
)]
async fn events(
repos: Repos,
State(repositories): Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Query(query): Query<EventsQuery>,
Query(mut query): Query<EventsQuery>,
) -> Result<Json<Page>, 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
Expand Down
37 changes: 33 additions & 4 deletions apps/origin-src/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<RepoName, OriginService>,
credentials: Credentials,
polls: Arc<Semaphore>,
}

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<OwnedSemaphorePermit> {
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
Expand Down
2 changes: 1 addition & 1 deletion docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
{
Expand Down
Loading