diff --git a/crates/indexer/Cargo.toml b/crates/indexer/Cargo.toml index 6f65f327..cc447627 100644 --- a/crates/indexer/Cargo.toml +++ b/crates/indexer/Cargo.toml @@ -31,7 +31,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } tower-http = { version = "0.5", features = ["trace", "request-id"] } uuid = { version= "1", features = ["v4", "serde"] } config = { version = "0.15.16", default-features = true } -tokio = { version = "1.49.0", features = ["rt-multi-thread", "macros"] } +tokio = { version = "1.49.0", features = ["rt-multi-thread", "macros", "sync"] } serde = { version= "1", features = ["derive"]} dotenvy = "0.15" diff --git a/crates/indexer/README.md b/crates/indexer/README.md index 6b87dfb1..cdbf0970 100644 --- a/crates/indexer/README.md +++ b/crates/indexer/README.md @@ -231,6 +231,8 @@ data: {"type":"offer_vault_withdrawal_indexed","id":"42","txid":"ccdd…","heigh Clients should treat events as signals to refetch REST resources rather than as full state snapshots. Keep-alive comments are sent periodically so proxies do not close idle connections. If an nginx (or similar) reverse proxy sits in front of the API, disable response buffering for this path. +Concurrent subscriptions are capped. The bundled nginx configs allow 256 streams in total, answering `429` beyond that; the API itself answers `503` once 512 streams are open. Browsers' `EventSource` does not retry after a non-`200` response, so clients should reconnect themselves with backoff. + API and indexer may run as separate processes (`RUN_MODE=api` / `RUN_MODE=indexer`); events cross the process boundary via Postgres LISTEN/NOTIFY. ### Identifiers diff --git a/crates/indexer/src/api/error.rs b/crates/indexer/src/api/error.rs index 2381dce1..c1079db7 100644 --- a/crates/indexer/src/api/error.rs +++ b/crates/indexer/src/api/error.rs @@ -15,6 +15,9 @@ pub enum ApiError { #[error("Validation error: {0}")] BadRequest(String), + + #[error("Service unavailable: {0}")] + ServiceUnavailable(String), } impl IntoResponse for ApiError { @@ -34,6 +37,11 @@ impl IntoResponse for ApiError { format!("Resource not found: {}", id), ), ApiError::BadRequest(msg) => (StatusCode::BAD_REQUEST, "bad_request", msg.clone()), + ApiError::ServiceUnavailable(msg) => ( + StatusCode::SERVICE_UNAVAILABLE, + "service_unavailable", + msg.clone(), + ), }; let body = Json(json!({ @@ -94,4 +102,18 @@ mod tests { assert_eq!(json["error"]["code"], "internal_error"); assert_eq!(json["error"]["message"], "An unexpected error occurred"); } + + #[tokio::test] + async fn service_unavailable_maps_to_503_with_message() { + let response = ApiError::ServiceUnavailable("busy".to_string()).into_response(); + let status = response.status(); + let body_bytes = to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + let json: Value = serde_json::from_slice(&body_bytes).expect("valid json"); + + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(json["error"]["code"], "service_unavailable"); + assert_eq!(json["error"]["message"], "busy"); + } } diff --git a/crates/indexer/src/api/events/bus.rs b/crates/indexer/src/api/events/bus.rs index 6e550ad0..3249f2ec 100644 --- a/crates/indexer/src/api/events/bus.rs +++ b/crates/indexer/src/api/events/bus.rs @@ -1,19 +1,40 @@ -use tokio::sync::broadcast; +use std::sync::Arc; + +use tokio::sync::{OwnedSemaphorePermit, Semaphore, broadcast}; use crate::events::IndexerEvent; const EVENT_BUS_CAPACITY: usize = 64; +/// Upper bound on concurrent SSE subscribers in this process. The reverse +/// proxy caps `/events` lower than this; this is the backstop for direct access. +const MAX_SSE_SUBSCRIBERS: usize = 512; + #[derive(Clone, Debug)] pub struct EventBus { sender: broadcast::Sender, + subscriber_slots: Arc, +} + +/// A live subscription. Its slot is released when it is dropped. +#[derive(Debug)] +pub struct Subscription { + pub receiver: broadcast::Receiver, + _permit: OwnedSemaphorePermit, } impl EventBus { pub fn new() -> Self { + Self::with_max_subscribers(MAX_SSE_SUBSCRIBERS) + } + + pub fn with_max_subscribers(max_subscribers: usize) -> Self { let (sender, _) = broadcast::channel(EVENT_BUS_CAPACITY); - Self { sender } + Self { + sender, + subscriber_slots: Arc::new(Semaphore::new(max_subscribers)), + } } pub fn publish(&self, event: IndexerEvent) { @@ -21,8 +42,14 @@ impl EventBus { let _ = self.sender.send(event); } - pub fn subscribe(&self) -> broadcast::Receiver { - self.sender.subscribe() + /// Returns `None` when all subscriber slots are taken. + pub fn subscribe(&self) -> Option { + let permit = self.subscriber_slots.clone().try_acquire_owned().ok()?; + + Some(Subscription { + receiver: self.sender.subscribe(), + _permit: permit, + }) } } @@ -31,3 +58,25 @@ impl Default for EventBus { Self::new() } } + +#[cfg(test)] +mod tests { + use super::EventBus; + + #[test] + fn subscribe_rejects_when_full_and_frees_slot_on_drop() { + let bus = EventBus::with_max_subscribers(1); + + let first = bus.subscribe().expect("first subscription fits"); + assert!( + bus.subscribe().is_none(), + "second subscription must be rejected" + ); + + drop(first); + assert!( + bus.subscribe().is_some(), + "slot must be released when a subscription is dropped" + ); + } +} diff --git a/crates/indexer/src/api/events/handlers.rs b/crates/indexer/src/api/events/handlers.rs index 5fbe1e5f..5d91d2c0 100644 --- a/crates/indexer/src/api/events/handlers.rs +++ b/crates/indexer/src/api/events/handlers.rs @@ -7,7 +7,7 @@ use axum::response::sse::{Event, KeepAlive, Sse}; use futures_util::stream::{Stream, unfold}; use tokio::sync::broadcast::error::RecvError; -use crate::api::AppState; +use crate::api::{ApiError, AppState}; #[utoipa::path( get, @@ -20,24 +20,34 @@ use crate::api::AppState; description = "Server-Sent Events stream. Event types: `block_indexed`, `factory_created`, `offer_created`, `offer_status_updated`, `offer_repayment_indexed`, `offer_vault_withdrawal_indexed`. Each `data` field carries a tagged JSON `IndexerEvent`. Clients should refetch REST resources on receipt.", content_type = "text/event-stream" ), + ( + status = 503, + description = "Subscriber limit reached. Clients should retry with backoff." + ), ) )] #[tracing::instrument(name = "Subscribing to indexer events", skip(state))] pub async fn subscribe_events( State(state): State>, -) -> Sse>> { - let receiver = state.events.subscribe(); +) -> Result>>, ApiError> { + let Some(subscription) = state.events.subscribe() else { + tracing::warn!("SSE subscriber limit reached; rejecting subscription"); + return Err(ApiError::ServiceUnavailable( + "Too many event subscribers, retry later".to_string(), + )); + }; - let stream = unfold(receiver, |mut receiver| async move { + // The subscription (and its slot) lives as long as the stream does. + let stream = unfold(subscription, |mut subscription| async move { loop { - match receiver.recv().await { + match subscription.receiver.recv().await { Ok(event) => { let sse_event = Event::default() .event(event.sse_event_name()) .json_data(&event); match sse_event { - Ok(sse_event) => return Some((Ok(sse_event), receiver)), + Ok(sse_event) => return Some((Ok(sse_event), subscription)), Err(error) => { tracing::error!(?error, "Failed to serialize SSE event"); continue; @@ -53,9 +63,9 @@ pub async fn subscribe_events( } }); - Sse::new(stream).keep_alive( + Ok(Sse::new(stream).keep_alive( KeepAlive::new() .interval(Duration::from_secs(15)) .text("keep-alive"), - ) + )) } diff --git a/deployment/configs/nginx/default.conf.template b/deployment/configs/nginx/default.conf.template index 1459e2c7..fde1926e 100644 --- a/deployment/configs/nginx/default.conf.template +++ b/deployment/configs/nginx/default.conf.template @@ -1,3 +1,8 @@ +# Cap on concurrent SSE streams (/api/events). Each stream holds two nginx +# connections (client + upstream), so the total must stay well below +# worker_connections. +limit_conn_zone $server_name zone=sse_total:1m; + server { listen 80; server_name _; @@ -19,6 +24,23 @@ server { proxy_redirect off; } + # Server-Sent Events: unbuffered and capped in total. + location = /api/events { + limit_conn sse_total 256; + limit_conn_status 429; + + proxy_pass http://api:8000/events; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffering off; + proxy_cache off; + } + location /api/ { proxy_pass http://api:8000/; proxy_http_version 1.1; diff --git a/nginx/nginx.conf b/nginx/nginx.conf index 057dd5ae..44302bbb 100644 --- a/nginx/nginx.conf +++ b/nginx/nginx.conf @@ -1,4 +1,6 @@ -events {} +events { + worker_connections 1024; +} http { map $http_origin $cors_origin { @@ -7,6 +9,11 @@ http { "~^https?://127\.0\.0\.1(:[0-9]+)?$" $http_origin; } + # Cap on concurrent SSE streams (/events). Each stream holds two nginx + # connections (client + upstream), so the total must stay well below + # worker_connections. + limit_conn_zone $server_name zone=sse_total:1m; + server { listen 80; server_name _; @@ -33,6 +40,9 @@ http { } location /events { + limit_conn sse_total 256; + limit_conn_status 429; + add_header Access-Control-Allow-Origin $cors_origin always; add_header Vary Origin always;