Skip to content
Merged
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 crates/indexer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
2 changes: 2 additions & 0 deletions crates/indexer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions crates/indexer/src/api/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ pub enum ApiError {

#[error("Validation error: {0}")]
BadRequest(String),

#[error("Service unavailable: {0}")]
ServiceUnavailable(String),
}

impl IntoResponse for ApiError {
Expand All @@ -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!({
Expand Down Expand Up @@ -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");
}
}
57 changes: 53 additions & 4 deletions crates/indexer/src/api/events/bus.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,55 @@
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<IndexerEvent>,
subscriber_slots: Arc<Semaphore>,
}

/// A live subscription. Its slot is released when it is dropped.
#[derive(Debug)]
pub struct Subscription {
pub receiver: broadcast::Receiver<IndexerEvent>,
_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) {
// No active subscribers is fine — `send` returns Err in that case.
let _ = self.sender.send(event);
}

pub fn subscribe(&self) -> broadcast::Receiver<IndexerEvent> {
self.sender.subscribe()
/// Returns `None` when all subscriber slots are taken.
pub fn subscribe(&self) -> Option<Subscription> {
let permit = self.subscriber_slots.clone().try_acquire_owned().ok()?;

Some(Subscription {
receiver: self.sender.subscribe(),
_permit: permit,
})
}
}

Expand All @@ -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"
);
}
}
26 changes: 18 additions & 8 deletions crates/indexer/src/api/events/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<Arc<AppState>>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let receiver = state.events.subscribe();
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, 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;
Expand All @@ -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"),
)
))
}
22 changes: 22 additions & 0 deletions deployment/configs/nginx/default.conf.template
Original file line number Diff line number Diff line change
@@ -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 _;
Expand All @@ -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;
Expand Down
12 changes: 11 additions & 1 deletion nginx/nginx.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
events {}
events {
worker_connections 1024;
}

http {
map $http_origin $cors_origin {
Expand All @@ -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 _;
Expand All @@ -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;

Expand Down