From aba16b5efb19e415a9e6942ef3c13fc8c6ee53a0 Mon Sep 17 00:00:00 2001 From: angela-helios Date: Mon, 30 Nov 2026 20:08:25 -0400 Subject: [PATCH 1/4] fix(subscriptions): close a bound websocket stream when its token expires The bind handler authorized a client once at the upgrade and then streamed to it for as long as the connection lived. It now captures the expiry of the request's bearer token and closes the stream with 1008 credential-expired at that time. The websocket manager keeps the deadline with each client and drops a client past it on the next broadcast or bind. Without authentication there is no token and no deadline. Closes #2816 --- crates/rest/src/handlers/ws.rs | 126 +++++++- .../rest/tests/ws_bind_credential_expiry.rs | 288 ++++++++++++++++++ crates/subscriptions/README.md | 2 + .../subscriptions/src/channels/ws_manager.rs | 164 +++++++++- 4 files changed, 558 insertions(+), 22 deletions(-) create mode 100644 crates/rest/tests/ws_bind_credential_expiry.rs diff --git a/crates/rest/src/handlers/ws.rs b/crates/rest/src/handlers/ws.rs index 3d62cf1532..aaf5501d7a 100644 --- a/crates/rest/src/handlers/ws.rs +++ b/crates/rest/src/handlers/ws.rs @@ -12,15 +12,23 @@ //! outside the HTTP request timeout, and a peer that stops reading would //! otherwise park the handler in `send` for as long as it keeps the socket //! open while its notification queue fills. +//! +//! A bound stream ends when the bearer token that authorized the upgrade +//! expires: the connection is closed with code 1008 and the reason +//! `credential-expired`, and the client binds again with a current token. +//! Without authentication there is no token and no such deadline. use std::sync::Arc; use std::time::Duration; use axum::{ + Extension, extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket}, extract::{State, WebSocketUpgrade}, response::Response, }; +use chrono::{DateTime, Utc}; +use helios_auth::Principal; use helios_persistence::core::ResourceStorage; use tracing::{debug, info, warn}; @@ -41,17 +49,22 @@ const SEND_TIMEOUT: Duration = Duration::from_secs(30); /// buffer that much per connection. const MAX_INCOMING_MESSAGE_BYTES: usize = 4 * 1024; -/// How long the close frame for an oversized message may take to send. The -/// peer may be bound and not reading, so the send must not wait on it. +/// How long the close frame for an oversized message or an expired credential +/// may take to send. The peer may be bound and not reading, so the send must +/// not wait on it. const CLOSE_TIMEOUT: Duration = Duration::from_secs(5); /// WebSocket binding handler. /// /// The client connects to `/ws/subscriptions/bind` and then sends /// `bind-with-token ` as the first message. +/// +/// The stream lives no longer than the bearer token of the upgrade request: +/// it is closed when that token expires. pub async fn ws_bind_handler( State(state): State>, tenant: TenantExtractor, + principal: Option>, ws: WebSocketUpgrade, ) -> RestResult where @@ -66,6 +79,7 @@ where let engine = Arc::clone(engine); let base_url = state.public_base_url_for_request(&tenant); let request_tenant_id = tenant.tenant_id().to_string(); + let credential_expires_at = principal.map(|Extension(principal)| principal.expires_at); // Upgrade the HTTP connection to WebSocket. Ok(ws @@ -75,7 +89,13 @@ where // which no message this route accepts can fill. .read_buffer_size(MAX_INCOMING_MESSAGE_BYTES) .on_upgrade(move |socket| { - handle_ws_connection(socket, engine, request_tenant_id, base_url) + handle_ws_connection( + socket, + engine, + request_tenant_id, + base_url, + credential_expires_at, + ) })) } @@ -102,12 +122,15 @@ fn validate_binding_token_for_request( /// Handles the WebSocket connection lifecycle after upgrade. /// /// Waits for a `bind-with-token` message, sends a handshake notification, -/// then streams events from the subscription engine until disconnect. +/// then streams events from the subscription engine until disconnect or until +/// `credential_expires_at`, the expiry of the token that authorized the +/// upgrade. async fn handle_ws_connection( mut socket: WebSocket, engine: Arc, request_tenant_id: String, base_url: String, + credential_expires_at: Option>, ) { let token = match receive_bind_token(&mut socket).await { Some(token) => token, @@ -150,11 +173,21 @@ async fn handle_ws_connection( } }; + if credential_expires_at.is_some_and(|expires_at| expires_at <= Utc::now()) { + warn!( + subscription_id = %subscription_id, + "WebSocket bind refused: the token that authorized the upgrade has expired" + ); + close_with_credential_expired(&mut socket).await; + return; + } + // Register this client with the WebSocket manager. - let Some((client_id, mut rx)) = engine - .ws_manager() - .register_client(&tenant_id, &subscription_id) - else { + let Some((client_id, mut rx)) = engine.ws_manager().register_client_until( + &tenant_id, + &subscription_id, + credential_expires_at, + ) else { close_with_policy_violation(&mut socket, "too-many-clients").await; return; }; @@ -193,10 +226,23 @@ async fn handle_ws_connection( } } + let credential_expired = credential_expiry(credential_expires_at); + tokio::pin!(credential_expired); + // Stream notifications. WebSocket is unidirectional (server → client), // but we monitor the socket for close frames / disconnects. loop { tokio::select! { + // The token that authorized the upgrade expired. + () = &mut credential_expired => { + warn!( + client_id = %client_id, + subscription_id = %subscription_id, + "The token that bound this WebSocket client expired; closing" + ); + close_with_credential_expired(&mut socket).await; + break; + } // Notification from the subscription engine. notification = rx.recv() => { match notification { @@ -318,6 +364,20 @@ async fn send_within_deadline(socket: &mut WebSocket, msg: Utf8Bytes) -> Result< } } +/// How long until `expires_at`, or zero once it has passed. +fn time_until(expires_at: DateTime) -> Duration { + (expires_at - Utc::now()).to_std().unwrap_or(Duration::ZERO) +} + +/// Completes when the credential that authorized a bind expires. Never +/// completes for a bind without one. +async fn credential_expiry(expires_at: Option>) { + match expires_at { + Some(expires_at) => tokio::time::sleep(time_until(expires_at)).await, + None => std::future::pending().await, + } +} + async fn receive_bind_token(socket: &mut WebSocket) -> Option { let first = match tokio::time::timeout(BIND_TIMEOUT, socket.recv()).await { Ok(first) => first, @@ -375,6 +435,17 @@ async fn close_with_policy_violation(socket: &mut WebSocket, reason: &str) { .await; } +/// Tells the peer its stream ended because the token that authorized it +/// expired (close code 1008). The peer may not be reading, so the send is +/// bounded by [`CLOSE_TIMEOUT`]. +async fn close_with_credential_expired(socket: &mut WebSocket) { + let close = Message::Close(Some(CloseFrame { + code: 1008, + reason: "credential-expired".into(), + })); + let _ = tokio::time::timeout(CLOSE_TIMEOUT, socket.send(close)).await; +} + /// Whether `error` is the WebSocket layer refusing a message or frame larger /// than [`MAX_INCOMING_MESSAGE_BYTES`]. fn is_message_too_big(error: &axum::Error) -> bool { @@ -396,10 +467,47 @@ async fn close_with_message_too_big(socket: &mut WebSocket) { #[cfg(test)] mod tests { + use std::time::Duration; + + use chrono::Utc; + use super::{ - BindingTokenRejection, parse_bind_with_token_message, validate_binding_token_for_request, + BindingTokenRejection, credential_expiry, parse_bind_with_token_message, time_until, + validate_binding_token_for_request, }; + #[test] + fn time_until_a_past_expiry_is_zero() { + assert_eq!( + time_until(Utc::now() - chrono::Duration::seconds(5)), + Duration::ZERO + ); + let remaining = time_until(Utc::now() + chrono::Duration::seconds(60)); + assert!(remaining > Duration::from_secs(50) && remaining <= Duration::from_secs(60)); + } + + #[tokio::test(start_paused = true)] + async fn credential_expiry_completes_at_the_expiry_and_never_without_one() { + let in_a_minute = Some(Utc::now() + chrono::Duration::seconds(60)); + assert!( + tokio::time::timeout(Duration::from_secs(30), credential_expiry(in_a_minute)) + .await + .is_err(), + "the stream is still authorized half way to the expiry" + ); + assert!( + tokio::time::timeout(Duration::from_secs(61), credential_expiry(in_a_minute)) + .await + .is_ok() + ); + assert!( + tokio::time::timeout(Duration::from_secs(86_400), credential_expiry(None)) + .await + .is_err(), + "a bind without a credential has no deadline" + ); + } + #[test] fn test_parse_bind_with_token_message() { assert_eq!( diff --git a/crates/rest/tests/ws_bind_credential_expiry.rs b/crates/rest/tests/ws_bind_credential_expiry.rs new file mode 100644 index 0000000000..d9889c2f63 --- /dev/null +++ b/crates/rest/tests/ws_bind_credential_expiry.rs @@ -0,0 +1,288 @@ +//! A stream bound on `/ws/subscriptions/bind` lives no longer than the bearer +//! token that authorized the upgrade: the server closes it with code 1008 and +//! the reason `credential-expired` when that token expires, and delivers +//! nothing to it afterwards. +//! +//! The routes are served without the authentication middleware; a layer puts +//! the `Principal` that middleware would have produced into the request +//! extensions. +#![cfg(feature = "subscriptions")] + +use std::sync::Arc; +use std::time::Duration; + +use chrono::Utc; +use futures::{SinkExt, StreamExt}; +use helios_auth::Principal; +use helios_fhir::FhirVersion; +use helios_persistence::backends::sqlite::SqliteBackend; +use helios_persistence::tenant::TenantId; +use helios_rest::{AppState, ServerConfig}; +use helios_subscriptions::{ + ResourceEvent, ResourceEventType, SubscriptionConfig, SubscriptionEngine, +}; +use serde_json::{Value, json}; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + +type Client = WebSocketStream>; + +/// The tenant `ServerConfig::for_testing()` resolves requests to. +const TENANT_ID: &str = "test-tenant"; +const TOPIC_URL: &str = "http://example.org/topic/encounter-create"; +const SUBSCRIPTION_ID: &str = "sub-ws-1"; + +/// Close code and reason of the frame that ended a connection. +type Closed = Option<(u16, String)>; + +fn credential_expired() -> Closed { + Some((1008, "credential-expired".to_string())) +} + +/// A principal whose token expires `expires_in` from now (already expired +/// when negative). +fn principal(expires_in: chrono::Duration) -> Principal { + Principal { + subject: "client-1".to_string(), + issuer: "https://issuer.example".to_string(), + expires_at: Utc::now() + expires_in, + ..Default::default() + } +} + +/// Serves the FHIR routes with a subscription engine on a loopback port. Every +/// request carries `principal`, as it would behind the authentication +/// middleware; `None` serves them as with authentication disabled. +async fn serve(principal: Option) -> (std::net::SocketAddr, Arc) { + let backend = Arc::new(SqliteBackend::in_memory().expect("in-memory sqlite")); + backend.init_schema().expect("init schema"); + let config = SubscriptionConfig { + supported_channel_types: vec!["websocket".to_string()], + ..Default::default() + }; + let engine = Arc::new(SubscriptionEngine::new( + config, + "http://localhost".to_string(), + )); + let state = AppState::new(backend, ServerConfig::for_testing()) + .with_subscription_engine(Arc::clone(&engine)); + let app = helios_rest::routing::fhir_routes::create_routes(state); + let app = match principal { + Some(principal) => app.layer(axum::Extension(principal)), + None => app, + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind loopback"); + let addr = listener.local_addr().expect("local addr"); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve"); + }); + (addr, engine) +} + +async fn connect(addr: std::net::SocketAddr) -> Client { + let (socket, _) = + tokio_tungstenite::connect_async(format!("ws://{addr}/ws/subscriptions/bind")) + .await + .expect("upgrade"); + socket +} + +/// Reads until the server closes the connection and returns the code and +/// reason of its close frame, or `None` if it ended without one. Frames that +/// are not a close are skipped. +async fn closed(socket: &mut Client) -> Closed { + tokio::time::timeout(Duration::from_secs(10), async { + while let Some(frame) = socket.next().await { + match frame { + Ok(Message::Close(Some(close))) => { + return Some((close.code.into(), close.reason.to_string())); + } + Ok(Message::Close(None)) | Err(_) => return None, + Ok(_) => {} + } + } + None + }) + .await + .expect("the server ends the connection") +} + +fn event(resource_type: &str, id: &str, resource: Value) -> ResourceEvent { + ResourceEvent { + tenant_id: TenantId::new(TENANT_ID), + fhir_version: FhirVersion::default(), + resource_type: resource_type.to_string(), + resource_id: id.to_string(), + version_id: "1".to_string(), + event_type: ResourceEventType::Create, + resource: Some(resource), + previous_resource: None, + timestamp: Utc::now(), + } +} + +/// Registers a topic and a websocket Subscription on it (R4 backport shapes, +/// the default FHIR version) and returns a binding token for the Subscription. +async fn binding_token(engine: &SubscriptionEngine) -> String { + engine + .on_resource_event(event( + "Basic", + "topic-1", + json!({ + "resourceType": "Basic", + "id": "topic-1", + "code": { + "coding": [{ + "system": "http://hl7.org/fhir/fhir-types", + "code": "SubscriptionTopic" + }] + }, + "extension": [{ + "url": "http://hl7.org/fhir/5.0/StructureDefinition/extension-SubscriptionTopic.url", + "valueUri": TOPIC_URL + }, { + "url": "http://hl7.org/fhir/4.3/StructureDefinition/extension-SubscriptionTopic.resourceTrigger", + "extension": [{ + "url": "resource", + "valueUri": "http://hl7.org/fhir/StructureDefinition/Encounter" + }, { + "url": "supportedInteraction", + "valueCode": "create" + }] + }] + }), + )) + .await; + engine + .on_resource_event(event( + "Subscription", + SUBSCRIPTION_ID, + json!({ + "resourceType": "Subscription", + "id": SUBSCRIPTION_ID, + "status": "requested", + "criteria": TOPIC_URL, + "channel": { + "type": "websocket", + "payload": "application/fhir+json" + } + }), + )) + .await; + assert!( + engine + .manager() + .get_subscription(TENANT_ID, SUBSCRIPTION_ID) + .is_some(), + "the websocket Subscription is registered" + ); + engine + .ws_token_manager() + .generate_token(TENANT_ID, SUBSCRIPTION_ID) + .expect("a binding token is issued") + .0 +} + +/// Sends the bind message and reads the handshake notification that answers +/// an accepted bind. +async fn bind(socket: &mut Client, token: &str) { + socket + .send(Message::Text(format!("bind-with-token {token}").into())) + .await + .expect("send bind message"); + let handshake = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .expect("handshake arrives"); + assert!( + matches!(handshake, Some(Ok(Message::Text(_)))), + "the bind is accepted and answered with the handshake notification, got {handshake:?}" + ); +} + +/// Waits for the server to drop the subscription's last bound client. +async fn no_client_is_bound(engine: &SubscriptionEngine) { + tokio::time::timeout(Duration::from_secs(5), async { + while engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID) != 0 { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the expired client is removed from the manager"); +} + +#[tokio::test] +async fn a_bound_stream_is_closed_when_its_token_expires() { + let (addr, engine) = serve(Some(principal(chrono::Duration::seconds(2)))).await; + let token = binding_token(&engine).await; + let mut socket = connect(addr).await; + + bind(&mut socket, &token).await; + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 1 + ); + + assert_eq!(closed(&mut socket).await, credential_expired()); + no_client_is_bound(&engine).await; + assert_eq!( + engine.ws_manager().send_to_subscription( + TENANT_ID, + SUBSCRIPTION_ID, + &json!({"resourceType": "Bundle"}) + ), + 0, + "nothing is delivered for the expired bind" + ); +} + +#[tokio::test] +async fn a_bind_with_an_expired_token_is_refused() { + let (addr, engine) = serve(Some(principal(chrono::Duration::seconds(-1)))).await; + let token = binding_token(&engine).await; + let mut socket = connect(addr).await; + + socket + .send(Message::Text(format!("bind-with-token {token}").into())) + .await + .expect("send bind message"); + + let first = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .expect("the server answers the bind"); + match first { + Some(Ok(Message::Close(Some(close)))) => { + assert_eq!(u16::from(close.code), 1008); + assert_eq!(close.reason.to_string(), "credential-expired"); + } + other => panic!("expected the close frame and no handshake, got {other:?}"), + } + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 0 + ); +} + +#[tokio::test] +async fn a_stream_stays_open_while_its_token_is_valid_or_there_is_none() { + for principal in [Some(principal(chrono::Duration::hours(1))), None] { + let (addr, engine) = serve(principal).await; + let token = binding_token(&engine).await; + let mut socket = connect(addr).await; + + bind(&mut socket, &token).await; + + assert!( + tokio::time::timeout(Duration::from_millis(1500), socket.next()) + .await + .is_err(), + "the server neither closes the stream nor sends anything further" + ); + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 1 + ); + } +} diff --git a/crates/subscriptions/README.md b/crates/subscriptions/README.md index 7c1c788c8f..e0c71c50dc 100644 --- a/crates/subscriptions/README.md +++ b/crates/subscriptions/README.md @@ -418,6 +418,8 @@ The WebSocket protocol is **unidirectional** (server → client) after binding. **Deadlines and queueing:** a connection that sends no bind message within 10 seconds is closed (`1008 bind-timeout`). Each bound client has a queue of 256 notifications; a client that stops reading its socket is given 30 seconds to accept a frame and is dropped once its queue is full, so a stalled client retains no further notifications in the server. It reconnects with a new binding token and replays missed events through `$events`. +**Credential lifetime:** with authentication enabled, a bound stream lives no longer than the bearer token sent on the WebSocket upgrade request. When that token expires the server closes the connection with `1008 credential-expired` and delivers nothing further to it; the client requests a new binding token, binds again with a current bearer token and catches up through `$events`. With authentication disabled a stream has no such deadline. + **Incoming message size:** the server reads only the bind message, so a client message or frame larger than 4 KiB is refused and the connection is closed with `1009 message-too-big`. Notifications the server sends are not limited by this. **Limits per subscription:** at most 16 clients are bound at a time; a further bind is closed with `1008 too-many-clients` until one disconnects. At most 16 binding tokens are outstanding (issued, unused, unexpired); a further `$get-ws-binding-token` answers `429` with `Retry-After` set to the token lifetime. Each notification is serialized once and every bound client's queue shares those bytes, so the memory a notification holds does not grow with the number of clients. diff --git a/crates/subscriptions/src/channels/ws_manager.rs b/crates/subscriptions/src/channels/ws_manager.rs index 1780d85a30..2d923c83c1 100644 --- a/crates/subscriptions/src/channels/ws_manager.rs +++ b/crates/subscriptions/src/channels/ws_manager.rs @@ -16,6 +16,7 @@ //! subscription has at most [`MAX_CLIENTS_PER_SUBSCRIPTION`] bound clients. use bytes::Bytes; +use chrono::{DateTime, Utc}; use dashmap::DashMap; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; @@ -37,11 +38,25 @@ pub type WsPayload = Bytes; /// Sender half given to a connected WebSocket client. pub type WsClientSender = mpsc::Sender; +/// One bound client of a subscription. +struct BoundClient { + id: String, + sender: WsClientSender, + /// When the credential that authorized the bind expires, if it has an + /// expiry. Nothing is delivered to the client from then on. + deadline: Option>, +} + +impl BoundClient { + fn is_past_deadline(&self, now: DateTime) -> bool { + self.deadline.is_some_and(|deadline| deadline <= now) + } +} + /// Manages connected WebSocket clients for all active subscriptions. pub struct WebSocketManager { /// Connected clients keyed by (tenant_id, subscription_id). - /// Each entry is a vec of (client_id, sender). - clients: DashMap<(String, String), Vec<(String, WsClientSender)>>, + clients: DashMap<(String, String), Vec>, } impl WebSocketManager { @@ -63,16 +78,46 @@ impl WebSocketManager { /// /// Returns `None` when the subscription already has /// [`MAX_CLIENTS_PER_SUBSCRIPTION`] connected clients. + /// + /// The client has no deadline; see + /// [`register_client_until`](Self::register_client_until). pub fn register_client( &self, tenant_id: &str, subscription_id: &str, ) -> Option<(String, mpsc::Receiver)> { + self.register_client_until(tenant_id, subscription_id, None) + } + + /// Registers a client like [`register_client`](Self::register_client), + /// bound until `deadline`: the time the credential that authorized the + /// bind expires, or `None` when it has no expiry. + /// + /// A client past its deadline is released the next time its subscription + /// is broadcast to or bound: its receiver closes and it receives nothing + /// further. + /// + /// Returns `None` when `deadline` has already passed, or when the + /// subscription has [`MAX_CLIENTS_PER_SUBSCRIPTION`] connected clients. + pub fn register_client_until( + &self, + tenant_id: &str, + subscription_id: &str, + deadline: Option>, + ) -> Option<(String, mpsc::Receiver)> { + let now = Utc::now(); + if deadline.is_some_and(|deadline| deadline <= now) { + warn!( + tenant_id, + subscription_id, "WebSocket bind refused: its credential has already expired" + ); + return None; + } let mut entry = self .clients .entry((tenant_id.to_string(), subscription_id.to_string())) .or_default(); - entry.retain(|(_, sender)| !sender.is_closed()); + entry.retain(|client| !client.sender.is_closed() && !client.is_past_deadline(now)); if entry.len() >= MAX_CLIENTS_PER_SUBSCRIPTION { warn!( tenant_id, @@ -84,7 +129,11 @@ impl WebSocketManager { } let (tx, rx) = mpsc::channel(CLIENT_QUEUE_CAPACITY); let client_id = Uuid::new_v4().to_string(); - entry.push((client_id.clone(), tx)); + entry.push(BoundClient { + id: client_id.clone(), + sender: tx, + deadline, + }); drop(entry); debug!( @@ -102,7 +151,7 @@ impl WebSocketManager { let key = (tenant_id.to_string(), subscription_id.to_string()); if let Some(mut entry) = self.clients.get_mut(&key) { - entry.retain(|(id, _)| id != client_id); + entry.retain(|client| client.id != client_id); let is_empty = entry.is_empty(); drop(entry); @@ -151,9 +200,21 @@ impl WebSocketManager { let mut delivered = 0; let initial_count = entry.len(); - // Send to all clients, removing those with closed or full channels. - entry.retain( - |(client_id, sender)| match sender.try_send(payload.clone()) { + let now = Utc::now(); + + // Send to all clients, removing those past their deadline and those + // with closed or full channels. + entry.retain(|client| { + if client.is_past_deadline(now) { + warn!( + tenant_id, + subscription_id, + client_id = %client.id, + "WebSocket client outlived the credential that bound it; dropping it" + ); + return false; + } + match client.sender.try_send(payload.clone()) { Ok(()) => { delivered += 1; true @@ -162,24 +223,26 @@ impl WebSocketManager { warn!( tenant_id, subscription_id, - client_id = %client_id, + client_id = %client.id, queued = CLIENT_QUEUE_CAPACITY, "WebSocket client is not draining its notifications; dropping it" ); false } Err(TrySendError::Closed(_)) => { - debug!(client_id = %client_id, "Pruning disconnected WebSocket client"); + debug!(client_id = %client.id, "Pruning disconnected WebSocket client"); false } - }, - ); + } + }); let pruned = initial_count - entry.len(); if pruned > 0 { warn!( tenant_id, - subscription_id, pruned, "Pruned disconnected or lagging WebSocket clients" + subscription_id, + pruned, + "Pruned disconnected, lagging or expired WebSocket clients" ); } @@ -385,6 +448,81 @@ mod tests { assert_eq!(queued, CLIENT_QUEUE_CAPACITY); } + /// A client bound until a deadline receives notifications before it and + /// none after it: the broadcast releases it and closes its receiver. + #[tokio::test] + async fn a_client_past_its_deadline_is_dropped_by_the_next_broadcast() { + let mgr = WebSocketManager::new(); + let deadline = Utc::now() + chrono::Duration::milliseconds(300); + let (_expiring, mut expiring_rx) = mgr + .register_client_until("t1", "sub-1", Some(deadline)) + .unwrap(); + let (_unbounded, mut unbounded_rx) = mgr.register_client("t1", "sub-1").unwrap(); + + let before = json!({"type": "event-notification", "n": 1}); + assert_eq!(mgr.send_to_subscription("t1", "sub-1", &before), 2); + assert_eq!(json(expiring_rx.recv().await.unwrap()), before); + assert_eq!(json(unbounded_rx.recv().await.unwrap()), before); + + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + + let after = json!({"type": "event-notification", "n": 2}); + assert_eq!( + mgr.send_to_subscription("t1", "sub-1", &after), + 1, + "only the client without a deadline receives it" + ); + assert_eq!(json(unbounded_rx.recv().await.unwrap()), after); + assert!(expiring_rx.recv().await.is_none()); + assert_eq!(mgr.client_count("t1", "sub-1"), 1); + } + + /// The last client of a subscription leaving through its deadline leaves + /// no entry behind. + #[tokio::test] + async fn a_subscription_whose_only_client_expired_has_no_clients() { + let mgr = WebSocketManager::new(); + let deadline = Utc::now() + chrono::Duration::milliseconds(100); + let (_id, mut rx) = mgr + .register_client_until("t1", "sub-1", Some(deadline)) + .unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + + let n = json!({"type": "event-notification"}); + assert_eq!(mgr.send_to_subscription("t1", "sub-1", &n), 0); + assert!(rx.recv().await.is_none()); + assert_eq!(mgr.client_count("t1", "sub-1"), 0); + } + + /// A bind whose credential has already expired is refused, and a client + /// past its deadline does not hold a place against the client cap. + #[tokio::test] + async fn an_expired_deadline_neither_binds_nor_holds_a_place() { + let mgr = WebSocketManager::new(); + let past = Utc::now() - chrono::Duration::seconds(1); + assert!( + mgr.register_client_until("t1", "sub-1", Some(past)) + .is_none() + ); + assert_eq!(mgr.client_count("t1", "sub-1"), 0); + + let deadline = Utc::now() + chrono::Duration::milliseconds(100); + let _held: Vec<_> = (0..MAX_CLIENTS_PER_SUBSCRIPTION) + .map(|i| { + mgr.register_client_until("t1", "sub-1", Some(deadline)) + .unwrap_or_else(|| panic!("client {i} fits")) + }) + .collect(); + assert!(mgr.register_client("t1", "sub-1").is_none()); + + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert!( + mgr.register_client("t1", "sub-1").is_some(), + "expired clients free their places" + ); + assert_eq!(mgr.client_count("t1", "sub-1"), 1); + } + #[test] fn test_send_to_nonexistent_subscription() { let mgr = WebSocketManager::new(); From cfed382436ebd669a94c401546ef2b38971f3d49 Mon Sep 17 00:00:00 2001 From: angela-helios Date: Mon, 30 Nov 2026 22:38:52 -0400 Subject: [PATCH 2/4] fix(subscriptions): cap WebSocket connections waiting to bind /ws/subscriptions/bind upgraded every request, so a peer could hold any number of connections that never send a bind message, and the memory they used stayed in the allocator arenas after they closed. The engine now holds one slot per connection waiting to bind (HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS, default 256). An upgrade past the limit is refused with 503 and Retry-After. The slot is given back when the bind message arrives, the connection closes, or the bind deadline passes. Every 64 closed connections the allocator is asked to return free memory to the OS. Closes #3069 --- .../skills/work-with-subscriptions/SKILL.md | 1 + .../skills/work-with-subscriptions/SKILL.md | 1 + README.md | 1 + crates/hfs/src/env_names.rs | 1 + crates/rest/src/handlers/ws.rs | 71 ++++- crates/rest/src/lib.rs | 6 + .../rest/tests/ws_unbound_connection_cap.rs | 252 ++++++++++++++++++ crates/subscriptions/README.md | 1 + crates/subscriptions/src/config.rs | 17 ++ crates/subscriptions/src/engine/mod.rs | 15 ++ 10 files changed, 360 insertions(+), 6 deletions(-) create mode 100644 crates/rest/tests/ws_unbound_connection_cap.rs diff --git a/.agents/skills/work-with-subscriptions/SKILL.md b/.agents/skills/work-with-subscriptions/SKILL.md index 5ff189c9ea..274411e13e 100644 --- a/.agents/skills/work-with-subscriptions/SKILL.md +++ b/.agents/skills/work-with-subscriptions/SKILL.md @@ -33,6 +33,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti | `HFS_SUBSCRIPTION_PERSIST_STATUS` | Write server-driven status transitions back into the stored `Subscription` (default `true`) | | `HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS` | Per-write timeout for that write-back (default `5000`) | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | Events remembered per subscription for `$events` (default `100`, `0` disables; in memory only, empty after a restart) | +| `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | WebSocket connections that may be waiting to bind at once (default `256`); further upgrades get `503` with `Retry-After` | | `HFS_SUBSCRIPTION_REHYDRATE` | Replay stored topics/subscriptions into the engine at startup (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | Re-run activation for stored `requested`/`error` subscriptions (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE_CONCURRENCY` | Cap on concurrent startup handshakes (default `8`) | diff --git a/.claude/skills/work-with-subscriptions/SKILL.md b/.claude/skills/work-with-subscriptions/SKILL.md index 5ff189c9ea..274411e13e 100644 --- a/.claude/skills/work-with-subscriptions/SKILL.md +++ b/.claude/skills/work-with-subscriptions/SKILL.md @@ -33,6 +33,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti | `HFS_SUBSCRIPTION_PERSIST_STATUS` | Write server-driven status transitions back into the stored `Subscription` (default `true`) | | `HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS` | Per-write timeout for that write-back (default `5000`) | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | Events remembered per subscription for `$events` (default `100`, `0` disables; in memory only, empty after a restart) | +| `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | WebSocket connections that may be waiting to bind at once (default `256`); further upgrades get `503` with `Retry-After` | | `HFS_SUBSCRIPTION_REHYDRATE` | Replay stored topics/subscriptions into the engine at startup (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | Re-run activation for stored `requested`/`error` subscriptions (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE_CONCURRENCY` | Cap on concurrent startup handshakes (default `8`) | diff --git a/README.md b/README.md index c122f509e0..4d761e8638 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,7 @@ JWT/bearer auth (`HFS_AUTH_*`, e.g. `HFS_AUTH_ENABLED`, `HFS_AUTH_JWKS_URL`, `HF | `HFS_SUBSCRIPTION_REHYDRATE` | `true` | Reload stored `Subscription`/`SubscriptionTopic` resources into the engine at startup, so subscriptions keep delivering across a restart | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | `true` | Re-run the activation handshake for stored `requested` subscriptions during rehydration | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | `100` | Events remembered per subscription for `GET Subscription/{id}/$events` (in memory, lost on restart); `0` disables the history | +| `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | `256` | WebSocket connections that may be waiting to send their bind message at once; an upgrade past the limit is refused with `503` and `Retry-After` | | `HFS_BULK_EXPORT_ENABLED` | `true` | Enable the [Bulk Data Export](crates/rest/README.md#bulk-data-export) `$export` operation; when `false`, all `$export` endpoints return `501` | | `HFS_BULK_EXPORT_OUTPUT_BACKEND` | `local-fs` | Bulk export output store: `local-fs` or `s3`. See the [rest crate README](crates/rest/README.md#bulk-data-export) for the full `HFS_BULK_EXPORT_*` table | | `HFS_BULK_SUBMIT_ENABLED` | `true` | Enable the [Bulk Data Submit](crates/rest/README.md#bulk-data-submit) `$bulk-submit` operation (HFS as Data Consumer — fetches a provider manifest and ingests it); when `false`, all `$bulk-submit` endpoints return `501`. Available on `sqlite`, `postgres` and `mongodb` (+ `-elasticsearch` composites) | diff --git a/crates/hfs/src/env_names.rs b/crates/hfs/src/env_names.rs index bfe92f473c..e7b56cc2be 100644 --- a/crates/hfs/src/env_names.rs +++ b/crates/hfs/src/env_names.rs @@ -302,6 +302,7 @@ const KNOWN: &[&str] = &[ "HFS_SUBSCRIPTION_SMTP_TIMEOUT_SECS", "HFS_SUBSCRIPTION_SMTP_USERNAME", "HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS", + "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS", "HFS_TENANT_REQUIRE_PROVISIONED", "HFS_TENANT_ROUTING_MODE", "HFS_TENANT_STRICT_VALIDATION", diff --git a/crates/rest/src/handlers/ws.rs b/crates/rest/src/handlers/ws.rs index 3d62cf1532..ab92379e64 100644 --- a/crates/rest/src/handlers/ws.rs +++ b/crates/rest/src/handlers/ws.rs @@ -12,8 +12,15 @@ //! outside the HTTP request timeout, and a peer that stops reading would //! otherwise park the handler in `send` for as long as it keeps the socket //! open while its notification queue fills. +//! +//! Connections that have not bound yet are limited in number +//! (`HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS`): an upgrade past the limit +//! is refused with `503` and `Retry-After`. The allocator keeps the memory +//! of closed connections in its arenas, so it is asked to return it to the OS +//! every [`TRIM_AFTER_CLOSED_CONNECTIONS`] closes. use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use axum::{ @@ -45,6 +52,29 @@ const MAX_INCOMING_MESSAGE_BYTES: usize = 4 * 1024; /// peer may be bound and not reading, so the send must not wait on it. const CLOSE_TIMEOUT: Duration = Duration::from_secs(5); +/// How many connections of this route close between two requests to return +/// freed memory to the OS. Fewer closes than this leave too little behind to +/// be worth walking every allocator arena. +const TRIM_AFTER_CLOSED_CONNECTIONS: usize = 64; + +/// Counts closed connections and says when a trim is due. +struct ClosedConnections(AtomicUsize); + +impl ClosedConnections { + const fn new() -> Self { + Self(AtomicUsize::new(0)) + } + + /// Records one closed connection. True on every + /// [`TRIM_AFTER_CLOSED_CONNECTIONS`]th call. + fn record(&self) -> bool { + let closed = self.0.fetch_add(1, Ordering::Relaxed).wrapping_add(1); + closed.is_multiple_of(TRIM_AFTER_CLOSED_CONNECTIONS) + } +} + +static CLOSED_CONNECTIONS: ClosedConnections = ClosedConnections::new(); + /// WebSocket binding handler. /// /// The client connects to `/ws/subscriptions/bind` and then sends @@ -64,6 +94,12 @@ where })?; let engine = Arc::clone(engine); + let unbound = engine.try_reserve_unbound_ws_connection().ok_or_else(|| { + warn!("Refusing WebSocket upgrade: too many connections are waiting to bind"); + RestError::ServiceUnavailable { + message: "Too many WebSocket connections are waiting to bind".to_string(), + } + })?; let base_url = state.public_base_url_for_request(&tenant); let request_tenant_id = tenant.tenant_id().to_string(); @@ -74,8 +110,11 @@ where // The library reads into a 128 KiB buffer per connection by default, // which no message this route accepts can fill. .read_buffer_size(MAX_INCOMING_MESSAGE_BYTES) - .on_upgrade(move |socket| { - handle_ws_connection(socket, engine, request_tenant_id, base_url) + .on_upgrade(move |socket| async move { + handle_ws_connection(socket, engine, request_tenant_id, base_url, unbound).await; + if CLOSED_CONNECTIONS.record() { + crate::memory_trim::release_free_memory(); + } })) } @@ -103,15 +142,20 @@ fn validate_binding_token_for_request( /// /// Waits for a `bind-with-token` message, sends a handshake notification, /// then streams events from the subscription engine until disconnect. +/// +/// `unbound` is the connection's slot among those waiting to bind. It is +/// given back once the bind message has arrived or the wait for it has ended. async fn handle_ws_connection( mut socket: WebSocket, engine: Arc, request_tenant_id: String, base_url: String, + unbound: tokio::sync::OwnedSemaphorePermit, ) { - let token = match receive_bind_token(&mut socket).await { - Some(token) => token, - None => return, + let token = receive_bind_token(&mut socket).await; + drop(unbound); + let Some(token) = token else { + return; }; // Validate and consume the binding token (single-use). @@ -397,9 +441,24 @@ async fn close_with_message_too_big(socket: &mut WebSocket) { #[cfg(test)] mod tests { use super::{ - BindingTokenRejection, parse_bind_with_token_message, validate_binding_token_for_request, + BindingTokenRejection, ClosedConnections, TRIM_AFTER_CLOSED_CONNECTIONS, + parse_bind_with_token_message, validate_binding_token_for_request, }; + #[test] + fn a_trim_is_due_once_per_batch_of_closed_connections() { + let closed = ClosedConnections::new(); + for round in 0..3 { + for _ in 1..TRIM_AFTER_CLOSED_CONNECTIONS { + assert!(!closed.record(), "round {round}: no trim before the batch"); + } + assert!( + closed.record(), + "round {round}: the batch's last close trims" + ); + } + } + #[test] fn test_parse_bind_with_token_message() { assert_eq!( diff --git a/crates/rest/src/lib.rs b/crates/rest/src/lib.rs index 72579d7898..e845e4afca 100644 --- a/crates/rest/src/lib.rs +++ b/crates/rest/src/lib.rs @@ -1388,6 +1388,10 @@ fn subscription_dispatch_config( "HFS_SUBSCRIPTION_HANDSHAKE_CONCURRENCY", &mut config.handshake_concurrency, ), + ( + "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS", + &mut config.ws_max_unbound_connections, + ), ] { *field = subscription_dispatch_limit(name, lookup(name).as_deref(), *field); } @@ -1756,6 +1760,7 @@ mod subscription_dispatch_config_tests { "HFS_SUBSCRIPTION_PER_SUBSCRIPTION_QUEUE_CAPACITY" => "9", "HFS_SUBSCRIPTION_DISPATCH_CONCURRENCY" => "2", "HFS_SUBSCRIPTION_HANDSHAKE_CONCURRENCY" => "1", + "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS" => "4", "HFS_SUBSCRIPTION_MAX_PENDING_NOTIFICATIONS_PER_TENANT" => "2", "HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE" => "0", _ => panic!("unknown dispatch setting: {name}"), @@ -1764,6 +1769,7 @@ mod subscription_dispatch_config_tests { ) }, ); + assert_eq!(config.ws_max_unbound_connections, 4); let engine = helios_subscriptions::SubscriptionEngine::new( config, "https://example.org/fhir".into(), diff --git a/crates/rest/tests/ws_unbound_connection_cap.rs b/crates/rest/tests/ws_unbound_connection_cap.rs new file mode 100644 index 0000000000..16e46c4b44 --- /dev/null +++ b/crates/rest/tests/ws_unbound_connection_cap.rs @@ -0,0 +1,252 @@ +//! `/ws/subscriptions/bind` upgrades a connection before it has shown a +//! binding token, so the connections waiting to bind are limited in number. +//! An upgrade past the limit is refused with `503` and `Retry-After`, and a +//! slot is given back when its connection binds, is refused, or closes. +#![cfg(feature = "subscriptions")] + +use std::sync::Arc; +use std::time::Duration; + +use chrono::Utc; +use futures::{SinkExt, StreamExt}; +use helios_fhir::FhirVersion; +use helios_persistence::backends::sqlite::SqliteBackend; +use helios_persistence::tenant::TenantId; +use helios_rest::{AppState, ServerConfig}; +use helios_subscriptions::{ + ResourceEvent, ResourceEventType, SubscriptionConfig, SubscriptionEngine, +}; +use serde_json::{Value, json}; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::{Error, Message}; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + +type Client = WebSocketStream>; + +/// The tenant `ServerConfig::for_testing()` resolves requests to. +const TENANT_ID: &str = "test-tenant"; +const TOPIC_URL: &str = "http://example.org/topic/encounter-create"; +const SUBSCRIPTION_ID: &str = "sub-ws-1"; + +/// Serves the FHIR routes with a subscription engine that lets `limit` +/// connections wait to bind. +async fn serve(limit: usize) -> (std::net::SocketAddr, Arc) { + let backend = Arc::new(SqliteBackend::in_memory().expect("in-memory sqlite")); + backend.init_schema().expect("init schema"); + let config = SubscriptionConfig { + supported_channel_types: vec!["websocket".to_string()], + ws_max_unbound_connections: limit, + ..Default::default() + }; + let engine = Arc::new(SubscriptionEngine::new( + config, + "http://localhost".to_string(), + )); + let state = AppState::new(backend, ServerConfig::for_testing()) + .with_subscription_engine(Arc::clone(&engine)); + let app = helios_rest::routing::fhir_routes::create_routes(state); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind loopback"); + let addr = listener.local_addr().expect("local addr"); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve"); + }); + (addr, engine) +} + +async fn try_connect(addr: std::net::SocketAddr) -> Result { + tokio_tungstenite::connect_async(format!("ws://{addr}/ws/subscriptions/bind")) + .await + .map(|(socket, _)| socket) +} + +async fn connect(addr: std::net::SocketAddr) -> Client { + try_connect(addr).await.expect("upgrade") +} + +/// Asserts that an upgrade is refused with `503` and a `Retry-After`. +async fn assert_refused(addr: std::net::SocketAddr) { + match try_connect(addr).await { + Err(Error::Http(response)) => { + assert_eq!(response.status().as_u16(), 503); + let retry_after = response + .headers() + .get("retry-after") + .expect("the refusal carries Retry-After") + .to_str() + .expect("Retry-After is text"); + assert!( + retry_after.parse::().is_ok(), + "Retry-After is delta-seconds, got {retry_after:?}" + ); + } + Err(other) => panic!("the upgrade is refused with an HTTP status, got {other:?}"), + Ok(_) => panic!("the upgrade is refused while every slot is held"), + } +} + +/// Connects once a slot is free. The server gives a slot back just after it +/// stops waiting for the bind message, which the client cannot observe. +async fn connect_once_a_slot_is_free(addr: std::net::SocketAddr) -> Client { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + match try_connect(addr).await { + Ok(socket) => return socket, + Err(Error::Http(response)) if response.status().as_u16() == 503 => { + tokio::time::sleep(Duration::from_millis(20)).await; + } + Err(other) => panic!("unexpected upgrade failure: {other:?}"), + } + } + }) + .await + .expect("a slot is given back") +} + +/// Reads until the server closes the connection and returns the code and +/// reason of its close frame. +async fn closed(socket: &mut Client) -> Option<(u16, String)> { + tokio::time::timeout(Duration::from_secs(5), async { + while let Some(frame) = socket.next().await { + match frame { + Ok(Message::Close(Some(close))) => { + return Some((close.code.into(), close.reason.to_string())); + } + Ok(Message::Close(None)) | Err(_) => return None, + Ok(_) => {} + } + } + None + }) + .await + .expect("the server ends the connection") +} + +fn event(resource_type: &str, id: &str, resource: Value) -> ResourceEvent { + ResourceEvent { + tenant_id: TenantId::new(TENANT_ID), + fhir_version: FhirVersion::default(), + resource_type: resource_type.to_string(), + resource_id: id.to_string(), + version_id: "1".to_string(), + event_type: ResourceEventType::Create, + resource: Some(resource), + previous_resource: None, + timestamp: Utc::now(), + } +} + +/// Registers a topic and a websocket Subscription on it (R4 backport shapes, +/// the default FHIR version) and returns a binding token for the Subscription. +async fn binding_token(engine: &SubscriptionEngine) -> String { + engine + .on_resource_event(event( + "Basic", + "topic-1", + json!({ + "resourceType": "Basic", + "id": "topic-1", + "code": { + "coding": [{ + "system": "http://hl7.org/fhir/fhir-types", + "code": "SubscriptionTopic" + }] + }, + "extension": [{ + "url": "http://hl7.org/fhir/5.0/StructureDefinition/extension-SubscriptionTopic.url", + "valueUri": TOPIC_URL + }, { + "url": "http://hl7.org/fhir/4.3/StructureDefinition/extension-SubscriptionTopic.resourceTrigger", + "extension": [{ + "url": "resource", + "valueUri": "http://hl7.org/fhir/StructureDefinition/Encounter" + }, { + "url": "supportedInteraction", + "valueCode": "create" + }] + }] + }), + )) + .await; + engine + .on_resource_event(event( + "Subscription", + SUBSCRIPTION_ID, + json!({ + "resourceType": "Subscription", + "id": SUBSCRIPTION_ID, + "status": "requested", + "criteria": TOPIC_URL, + "channel": { + "type": "websocket", + "payload": "application/fhir+json" + } + }), + )) + .await; + engine + .ws_token_manager() + .generate_token(TENANT_ID, SUBSCRIPTION_ID) + .expect("a binding token is issued") + .0 +} + +#[tokio::test] +async fn an_upgrade_past_the_limit_is_refused_until_a_waiting_connection_closes() { + let (addr, _engine) = serve(2).await; + + let mut first = connect(addr).await; + let _second = connect(addr).await; + assert_refused(addr).await; + assert_refused(addr).await; + + first.close(None).await.expect("close the first connection"); + let _third = connect_once_a_slot_is_free(addr).await; + assert_refused(addr).await; +} + +#[tokio::test] +async fn a_bound_client_does_not_hold_a_slot() { + let (addr, engine) = serve(1).await; + let token = binding_token(&engine).await; + + let mut bound = connect(addr).await; + assert_refused(addr).await; + bound + .send(Message::Text(format!("bind-with-token {token}").into())) + .await + .expect("send bind message"); + let handshake = tokio::time::timeout(Duration::from_secs(5), bound.next()) + .await + .expect("handshake arrives"); + assert!( + matches!(handshake, Some(Ok(Message::Text(_)))), + "the bind is accepted and answered with the handshake notification, got {handshake:?}" + ); + + let _waiting = connect(addr).await; + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 1, + "the bound client stays connected" + ); + assert_refused(addr).await; +} + +#[tokio::test] +async fn a_refused_bind_message_gives_the_slot_back() { + let (addr, _engine) = serve(1).await; + + let mut socket = connect(addr).await; + socket + .send(Message::Text("hello".into())) + .await + .expect("send a message that is not a bind"); + assert_eq!( + closed(&mut socket).await, + Some((1008, "expected-bind-with-token".to_string())) + ); + + let _next = connect_once_a_slot_is_free(addr).await; +} diff --git a/crates/subscriptions/README.md b/crates/subscriptions/README.md index 7c1c788c8f..6205d80d44 100644 --- a/crates/subscriptions/README.md +++ b/crates/subscriptions/README.md @@ -158,6 +158,7 @@ Comparators supported: `eq` (default), `in`. Native `filterBy.comparator` values | `HFS_SUBSCRIPTION_MAX_PENDING_NOTIFICATIONS_PER_TENANT` | half the global budget | Queued + active notifications for all of one tenant's subscriptions, so one tenant's slow receivers cannot shed the others'; kept between the per-subscription capacity and the global budget | | `HFS_SUBSCRIPTION_DISPATCH_CONCURRENCY` | `64` | Simultaneous channel attempts, shared by notifications and activation handshakes | | `HFS_SUBSCRIPTION_HANDSHAKE_CONCURRENCY` | `8` | Running activation flows, shared by live writes and startup rehydration | +| `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | `256` | WebSocket connections that may be waiting to send their bind message at once; an upgrade past the limit is refused with `503` and `Retry-After` | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | `100` | Events remembered per subscription for `$events` (number, timestamp, focus reference only; in memory, lost on restart); `0` disables the history | | `max_retries` *(config field)* | `10` | Delivery attempts per notification; `0` disables retries | | `retry_initial_delay` *(config field)* | `1s` | Base delay for delivery backoff | diff --git a/crates/subscriptions/src/config.rs b/crates/subscriptions/src/config.rs index 09476af647..2609727385 100644 --- a/crates/subscriptions/src/config.rs +++ b/crates/subscriptions/src/config.rs @@ -71,6 +71,12 @@ pub struct SubscriptionConfig { /// Lifetime of WebSocket binding tokens in seconds. pub ws_token_lifetime_secs: i64, + /// Maximum WebSocket connections that may be waiting to send their bind + /// message at once. A connection holds a slot from the upgrade request + /// until its bind message arrives or it closes; further upgrades are + /// refused while every slot is held. Bound clients do not count. + pub ws_max_unbound_connections: usize, + /// When `true`, rest-hook delivery to private/loopback/link-local IPs is /// permitted. Default `false`: the endpoint is chosen by whoever writes /// the Subscription. Set `HFS_SUBSCRIPTION_ALLOW_PRIVATE_ENDPOINTS=true` @@ -164,6 +170,7 @@ impl Default for SubscriptionConfig { off_threshold: 10, supported_channel_types: vec!["rest-hook".to_string()], ws_token_lifetime_secs: 30, + ws_max_unbound_connections: 256, allow_private_endpoints: false, smtp: None, messaging: None, @@ -206,6 +213,11 @@ impl SubscriptionConfig { &mut self.handshake_concurrency, defaults.handshake_concurrency, ), + ( + "ws_max_unbound_connections", + &mut self.ws_max_unbound_connections, + defaults.ws_max_unbound_connections, + ), ] { if *capacity == 0 || *capacity > tokio::sync::Semaphore::MAX_PERMITS { tracing::warn!( @@ -337,9 +349,14 @@ mod tests { per_subscription_queue_capacity: invalid, dispatch_concurrency: invalid, handshake_concurrency: invalid, + ws_max_unbound_connections: invalid, ..SubscriptionConfig::default() } .normalize_dispatch_limits(); + assert_eq!( + config.ws_max_unbound_connections, + default.ws_max_unbound_connections + ); assert_eq!(config.event_queue_capacity, default.event_queue_capacity); assert_eq!( config.max_pending_notifications, diff --git a/crates/subscriptions/src/engine/mod.rs b/crates/subscriptions/src/engine/mod.rs index 0ee951540a..6e5dba23ce 100644 --- a/crates/subscriptions/src/engine/mod.rs +++ b/crates/subscriptions/src/engine/mod.rs @@ -54,6 +54,8 @@ struct EngineCore { ws_manager: Arc, ws_channel: Arc, ws_token_manager: Arc, + /// One permit per WebSocket connection that may be waiting to bind. + ws_unbound_slots: Arc, email_channel: Option>, messaging_channel: Option>, config: SubscriptionConfig, @@ -130,6 +132,7 @@ impl SubscriptionEngine { let ws_manager = Arc::new(WebSocketManager::new()); let ws_channel = Arc::new(WebSocketChannel::new(Arc::clone(&ws_manager))); let ws_token_manager = Arc::new(WsBindingTokenManager::new(config.ws_token_lifetime_secs)); + let ws_unbound_slots = Arc::new(Semaphore::new(config.ws_max_unbound_connections)); let email_channel = match &config.smtp { Some(settings) => match EmailChannel::new(settings.clone()) { Ok(ch) => Some(Arc::new(ch)), @@ -166,6 +169,7 @@ impl SubscriptionEngine { ws_manager, ws_channel, ws_token_manager, + ws_unbound_slots, email_channel, messaging_channel, config, @@ -251,6 +255,17 @@ impl SubscriptionEngine { &self.core.ws_token_manager } + /// Reserves a slot for a WebSocket connection that has not bound yet, or + /// returns `None` when + /// [`SubscriptionConfig::ws_max_unbound_connections`] connections are + /// already waiting to bind. The slot is held until the returned permit is + /// dropped. + pub fn try_reserve_unbound_ws_connection(&self) -> Option { + Arc::clone(&self.core.ws_unbound_slots) + .try_acquire_owned() + .ok() + } + /// Called after a resource write has been committed. /// /// This method: From cd1b13527974b9e7adfbb9683c19b827487da2e9 Mon Sep 17 00:00:00 2001 From: angela-helios Date: Wed, 2 Dec 2026 13:03:42 -0400 Subject: [PATCH 3/4] fix(subscriptions): bound the WebSocket close frame and name a dropped client's reason Every close frame is sent within 5 seconds or given up on. A bound client that misses the send deadline or overflows its queue is closed with 1008 client-too-slow instead of a dropped connection. The bind deadline, send deadline and client queue size are configurable through HFS_SUBSCRIPTION_WS_*, and the README says what $events can and cannot recover. Closes #2723 --- .../skills/work-with-subscriptions/SKILL.md | 5 +- .../skills/work-with-subscriptions/SKILL.md | 5 +- README.md | 3 + crates/hfs/src/env_names.rs | 3 + crates/rest/src/handlers/ws.rs | 180 +++++++---- crates/rest/src/lib.rs | 14 + crates/rest/tests/ws_client_deadlines.rs | 304 ++++++++++++++++++ crates/subscriptions/README.md | 9 +- .../subscriptions/src/channels/ws_manager.rs | 107 +++++- crates/subscriptions/src/config.rs | 69 ++++ crates/subscriptions/src/engine/mod.rs | 9 +- 11 files changed, 616 insertions(+), 92 deletions(-) create mode 100644 crates/rest/tests/ws_client_deadlines.rs diff --git a/.agents/skills/work-with-subscriptions/SKILL.md b/.agents/skills/work-with-subscriptions/SKILL.md index 274411e13e..4606af89ca 100644 --- a/.agents/skills/work-with-subscriptions/SKILL.md +++ b/.agents/skills/work-with-subscriptions/SKILL.md @@ -14,7 +14,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti - The messaging channel is separately gated by `HFS_SUBSCRIPTION_MESSAGING_ENABLED`. - Endpoint safety (`channels/egress.rs`, rest-hook and messaging): endpoints that are, or resolve to, private/loopback addresses are refused unless `HFS_SUBSCRIPTION_ALLOW_PRIVATE_ENDPOINTS=true`, and redirects are never followed (a `3xx` is a permanent error). Tests that deliver to a loopback receiver set `SubscriptionConfig::allow_private_endpoints`. - Notification bundles follow the topic-based subscription spec; delivery failures retry with backoff (`engine/retry.rs`). -- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue and 30 s to accept each frame, and is dropped when it stops draining. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). +- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue and 30 s to accept each frame, and is closed (`1008 client-too-slow`) when it stops draining; all three limits are `HFS_SUBSCRIPTION_WS_*` variables. Every close frame is sent within 5 s or given up on. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). ## Channels (`crates/subscriptions/src/channels/`) @@ -34,6 +34,9 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti | `HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS` | Per-write timeout for that write-back (default `5000`) | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | Events remembered per subscription for `$events` (default `100`, `0` disables; in memory only, empty after a restart) | | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | WebSocket connections that may be waiting to bind at once (default `256`); further upgrades get `503` with `Retry-After` | +| `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | How long a WebSocket connection may take to bind (default `10000`) | +| `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | How long a bound WebSocket client may take to accept one frame (default `30000`) | +| `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | Notifications a bound WebSocket client may have waiting (default `256`) | | `HFS_SUBSCRIPTION_REHYDRATE` | Replay stored topics/subscriptions into the engine at startup (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | Re-run activation for stored `requested`/`error` subscriptions (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE_CONCURRENCY` | Cap on concurrent startup handshakes (default `8`) | diff --git a/.claude/skills/work-with-subscriptions/SKILL.md b/.claude/skills/work-with-subscriptions/SKILL.md index 274411e13e..4606af89ca 100644 --- a/.claude/skills/work-with-subscriptions/SKILL.md +++ b/.claude/skills/work-with-subscriptions/SKILL.md @@ -14,7 +14,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti - The messaging channel is separately gated by `HFS_SUBSCRIPTION_MESSAGING_ENABLED`. - Endpoint safety (`channels/egress.rs`, rest-hook and messaging): endpoints that are, or resolve to, private/loopback addresses are refused unless `HFS_SUBSCRIPTION_ALLOW_PRIVATE_ENDPOINTS=true`, and redirects are never followed (a `3xx` is a permanent error). Tests that deliver to a loopback receiver set `SubscriptionConfig::allow_private_endpoints`. - Notification bundles follow the topic-based subscription spec; delivery failures retry with backoff (`engine/retry.rs`). -- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue and 30 s to accept each frame, and is dropped when it stops draining. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). +- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue and 30 s to accept each frame, and is closed (`1008 client-too-slow`) when it stops draining; all three limits are `HFS_SUBSCRIPTION_WS_*` variables. Every close frame is sent within 5 s or given up on. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). ## Channels (`crates/subscriptions/src/channels/`) @@ -34,6 +34,9 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti | `HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS` | Per-write timeout for that write-back (default `5000`) | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | Events remembered per subscription for `$events` (default `100`, `0` disables; in memory only, empty after a restart) | | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | WebSocket connections that may be waiting to bind at once (default `256`); further upgrades get `503` with `Retry-After` | +| `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | How long a WebSocket connection may take to bind (default `10000`) | +| `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | How long a bound WebSocket client may take to accept one frame (default `30000`) | +| `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | Notifications a bound WebSocket client may have waiting (default `256`) | | `HFS_SUBSCRIPTION_REHYDRATE` | Replay stored topics/subscriptions into the engine at startup (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | Re-run activation for stored `requested`/`error` subscriptions (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE_CONCURRENCY` | Cap on concurrent startup handshakes (default `8`) | diff --git a/README.md b/README.md index 1f664dcde4..a9d5f797b5 100644 --- a/README.md +++ b/README.md @@ -461,6 +461,9 @@ JWT/bearer auth (`HFS_AUTH_*`, e.g. `HFS_AUTH_ENABLED`, `HFS_AUTH_JWKS_URL`, `HF | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | `true` | Re-run the activation handshake for stored `requested` subscriptions during rehydration | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | `100` | Events remembered per subscription for `GET Subscription/{id}/$events` (in memory, lost on restart); `0` disables the history | | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | `256` | WebSocket connections that may be waiting to send their bind message at once; an upgrade past the limit is refused with `503` and `Retry-After` | +| `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | `10000` | How long a WebSocket connection may take to send its bind message (`1008 bind-timeout` past it) | +| `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | `30000` | How long a bound WebSocket client may take to accept one frame, whatever its size (`1008 client-too-slow` past it); raise it for large `full-resource` notifications over slow links | +| `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | `256` | Notifications a bound WebSocket client may have waiting; a client whose queue overflows is closed (`1008 client-too-slow`) | | `HFS_BULK_EXPORT_ENABLED` | `true` | Enable the [Bulk Data Export](crates/rest/README.md#bulk-data-export) `$export` operation; when `false`, all `$export` endpoints return `501` | | `HFS_BULK_EXPORT_OUTPUT_BACKEND` | `local-fs` | Bulk export output store: `local-fs` or `s3`. See the [rest crate README](crates/rest/README.md#bulk-data-export) for the full `HFS_BULK_EXPORT_*` table | | `HFS_BULK_SUBMIT_ENABLED` | `true` | Enable the [Bulk Data Submit](crates/rest/README.md#bulk-data-submit) `$bulk-submit` operation (HFS as Data Consumer — fetches a provider manifest and ingests it); when `false`, all `$bulk-submit` endpoints return `501`. Available on `sqlite`, `postgres` and `mongodb` (+ `-elasticsearch` composites) | diff --git a/crates/hfs/src/env_names.rs b/crates/hfs/src/env_names.rs index d17560d030..707de45e67 100644 --- a/crates/hfs/src/env_names.rs +++ b/crates/hfs/src/env_names.rs @@ -305,7 +305,10 @@ const KNOWN: &[&str] = &[ "HFS_SUBSCRIPTION_SMTP_TIMEOUT_SECS", "HFS_SUBSCRIPTION_SMTP_USERNAME", "HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS", + "HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS", + "HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY", "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS", + "HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS", "HFS_TENANT_REQUIRE_PROVISIONED", "HFS_TENANT_ROUTING_MODE", "HFS_TENANT_STRICT_VALIDATION", diff --git a/crates/rest/src/handlers/ws.rs b/crates/rest/src/handlers/ws.rs index 1ac44ed4dc..79db548679 100644 --- a/crates/rest/src/handlers/ws.rs +++ b/crates/rest/src/handlers/ws.rs @@ -7,12 +7,19 @@ //! notification bundles as JSON text frames after the client sends a //! `bind-with-token ` message. //! -//! A connection that does not bind within [`BIND_TIMEOUT`], or does not -//! accept a frame within [`SEND_TIMEOUT`], is closed: an upgraded socket is +//! A connection that does not bind within +//! `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS`, or does not accept a frame within +//! `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS`, is closed: an upgraded socket is //! outside the HTTP request timeout, and a peer that stops reading would //! otherwise park the handler in `send` for as long as it keeps the socket //! open while its notification queue fills. //! +//! A bound client that misses the send deadline, or that the subscription +//! engine drops because its queue is full, is closed with code 1008 and the +//! reason `client-too-slow`. Every close frame is sent within +//! [`CLOSE_TIMEOUT`], so a peer that is not reading gets a dropped connection +//! instead. +//! //! Connections that have not bound yet are limited in number //! (`HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS`): an upgrade past the limit //! is refused with `503` and `Retry-After`. The allocator keeps the memory @@ -43,12 +50,6 @@ use crate::error::{RestError, RestResult}; use crate::extractors::TenantExtractor; use crate::state::AppState; -/// How long a connection may take to send its `bind-with-token` message. -const BIND_TIMEOUT: Duration = Duration::from_secs(10); - -/// How long a bound client may take to accept one frame. -const SEND_TIMEOUT: Duration = Duration::from_secs(30); - /// The largest message or frame the route reads from a client. The protocol /// reads one `bind-with-token ` message of a few dozen bytes and /// ignores everything after it, so the 64 MiB message and 16 MiB frame the @@ -56,11 +57,27 @@ const SEND_TIMEOUT: Duration = Duration::from_secs(30); /// buffer that much per connection. const MAX_INCOMING_MESSAGE_BYTES: usize = 4 * 1024; -/// How long the close frame for an oversized message or an expired credential -/// may take to send. The peer may be bound and not reading, so the send must -/// not wait on it. +/// How long a close frame may take to send. The peer may be bound and not +/// reading, so the send must not wait on it. const CLOSE_TIMEOUT: Duration = Duration::from_secs(5); +/// Code and reason of the close frame that ends a connection. +type Closing = (u16, &'static str); + +/// The token that authorized the upgrade expired. +const CREDENTIAL_EXPIRED: Closing = (1008, "credential-expired"); + +/// The client did not keep up with its notifications. +const CLIENT_TOO_SLOW: Closing = (1008, "client-too-slow"); + +/// The client tried to bind a second time. +const SINGLE_BIND_ONLY: Closing = (1008, "single-bind-only"); + +/// The client sent a message larger than [`MAX_INCOMING_MESSAGE_BYTES`]. The +/// oversized payload is left unread, so a peer still sending it may see a +/// reset instead. +const MESSAGE_TOO_BIG: Closing = (1009, "message-too-big"); + /// How many connections of this route close between two requests to return /// freed memory to the OS. Fewer closes than this leave too little behind to /// be worth walking every allocator arena. @@ -177,7 +194,7 @@ async fn handle_ws_connection( credential_expires_at: Option>, unbound: tokio::sync::OwnedSemaphorePermit, ) { - let token = receive_bind_token(&mut socket).await; + let token = receive_bind_token(&mut socket, engine.config().ws_bind_timeout).await; drop(unbound); let Some(token) = token else { return; @@ -224,7 +241,7 @@ async fn handle_ws_connection( subscription_id = %subscription_id, "WebSocket bind refused: the token that authorized the upgrade has expired" ); - close_with_credential_expired(&mut socket).await; + close(&mut socket, CREDENTIAL_EXPIRED).await; return; } @@ -238,6 +255,7 @@ async fn handle_ws_connection( return; }; let ws_manager = Arc::clone(engine.ws_manager()); + let send_timeout = engine.config().ws_send_timeout; info!( tenant_id = %tenant_id, @@ -253,12 +271,18 @@ async fn handle_ws_connection( if let Ok(bundle) = handshake_bundle { match serde_json::to_string(&bundle) { Ok(msg) => { - if send_within_deadline(&mut socket, msg.into()).await.is_err() { + if let Err(failure) = + send_within_deadline(&mut socket, msg.into(), send_timeout).await + { warn!( client_id = %client_id, "Failed to send handshake, client disconnected or not reading" ); + drop(rx); ws_manager.remove_client(&tenant_id, &subscription_id, &client_id); + if failure == SendFailure::Stalled { + close(&mut socket, CLIENT_TOO_SLOW).await; + } return; } } @@ -276,8 +300,9 @@ async fn handle_ws_connection( tokio::pin!(credential_expired); // Stream notifications. WebSocket is unidirectional (server → client), - // but we monitor the socket for close frames / disconnects. - loop { + // but we monitor the socket for close frames / disconnects. The loop ends + // with the close frame the client is owed, if any. + let closing = loop { tokio::select! { // The token that authorized the upgrade expired. () = &mut credential_expired => { @@ -286,8 +311,7 @@ async fn handle_ws_connection( subscription_id = %subscription_id, "The token that bound this WebSocket client expired; closing" ); - close_with_credential_expired(&mut socket).await; - break; + break Some(CREDENTIAL_EXPIRED); } // Notification from the subscription engine. notification = rx.recv() => { @@ -302,26 +326,26 @@ async fn handle_ws_connection( client_id = %client_id, "WebSocket client was released by the subscription engine; closing without delivering its backlog" ); - break; + break release_closing(rx.was_too_slow(), credential_expires_at); } Some(payload) => { match Utf8Bytes::try_from(payload) { - Ok(msg) => match send_within_deadline(&mut socket, msg).await { + Ok(msg) => match send_within_deadline(&mut socket, msg, send_timeout).await { Ok(()) => {} Err(SendFailure::Disconnected) => { debug!( client_id = %client_id, "Client disconnected during send" ); - break; + break None; } Err(SendFailure::Stalled) => { warn!( client_id = %client_id, - deadline_secs = SEND_TIMEOUT.as_secs(), + deadline_ms = send_timeout.as_millis() as u64, "Client did not accept a notification within the deadline; closing" ); - break; + break Some(CLIENT_TOO_SLOW); } }, Err(e) => { @@ -341,7 +365,7 @@ async fn handle_ws_connection( client_id = %client_id, "Notification channel closed" ); - break; + break release_closing(rx.was_too_slow(), credential_expires_at); } } } @@ -353,7 +377,7 @@ async fn handle_ws_connection( client_id = %client_id, "Client sent close frame or disconnected" ); - break; + break None; } Some(Ok(Message::Text(text))) => { if parse_bind_with_token_message(text.as_ref()).is_some() { @@ -361,8 +385,7 @@ async fn handle_ws_connection( client_id = %client_id, "Received additional bind-with-token message after initial bind" ); - close_with_policy_violation(&mut socket, "single-bind-only").await; - break; + break Some(SINGLE_BIND_ONLY); } // Ignore non-bind client messages. } @@ -375,18 +398,20 @@ async fn handle_ws_connection( error = %e, "WebSocket error" ); - if is_message_too_big(&e) { - close_with_message_too_big(&mut socket).await; - } - break; + break is_message_too_big(&e).then_some(MESSAGE_TOO_BIG); } } } } - } + }; - // Cleanup: remove this client from the manager. + // Cleanup: free the queued notifications and remove this client from the + // manager before the close frame, which may wait on the peer. + drop(rx); ws_manager.remove_client(&tenant_id, &subscription_id, &client_id); + if let Some(closing) = closing { + close(&mut socket, closing).await; + } info!( client_id = %client_id, subscription_id = %subscription_id, @@ -400,16 +425,35 @@ enum SendFailure { Stalled, } -/// Sends one text frame, giving up after [`SEND_TIMEOUT`]: a peer that stops -/// reading leaves `send` pending once the socket buffers are full. -async fn send_within_deadline(socket: &mut WebSocket, msg: Utf8Bytes) -> Result<(), SendFailure> { - match tokio::time::timeout(SEND_TIMEOUT, socket.send(Message::Text(msg))).await { +/// Sends one text frame, giving up after `deadline`: a peer that stops reading +/// leaves `send` pending once the socket buffers are full. +async fn send_within_deadline( + socket: &mut WebSocket, + msg: Utf8Bytes, + deadline: Duration, +) -> Result<(), SendFailure> { + match tokio::time::timeout(deadline, socket.send(Message::Text(msg))).await { Ok(Ok(())) => Ok(()), Ok(Err(_)) => Err(SendFailure::Disconnected), Err(_) => Err(SendFailure::Stalled), } } +/// The close frame owed to a client the subscription engine released: none +/// when the subscription went away. +fn release_closing( + too_slow: bool, + credential_expires_at: Option>, +) -> Option { + if credential_expires_at.is_some_and(|expires_at| expires_at <= Utc::now()) { + Some(CREDENTIAL_EXPIRED) + } else if too_slow { + Some(CLIENT_TOO_SLOW) + } else { + None + } +} + /// How long until `expires_at`, or zero once it has passed. fn time_until(expires_at: DateTime) -> Duration { (expires_at - Utc::now()).to_std().unwrap_or(Duration::ZERO) @@ -424,12 +468,12 @@ async fn credential_expiry(expires_at: Option>) { } } -async fn receive_bind_token(socket: &mut WebSocket) -> Option { - let first = match tokio::time::timeout(BIND_TIMEOUT, socket.recv()).await { +async fn receive_bind_token(socket: &mut WebSocket, deadline: Duration) -> Option { + let first = match tokio::time::timeout(deadline, socket.recv()).await { Ok(first) => first, Err(_) => { warn!( - deadline_secs = BIND_TIMEOUT.as_secs(), + deadline_ms = deadline.as_millis() as u64, "WebSocket connection sent no bind message within the deadline" ); close_with_policy_violation(socket, "bind-timeout").await; @@ -458,7 +502,7 @@ async fn receive_bind_token(socket: &mut WebSocket) -> Option { Some(Err(e)) => { warn!(error = %e, "WebSocket error before bind"); if is_message_too_big(&e) { - close_with_message_too_big(socket).await; + close(socket, MESSAGE_TOO_BIG).await; } None } @@ -472,24 +516,17 @@ fn parse_bind_with_token_message(message: &str) -> Option<&str> { if token.is_empty() { None } else { Some(token) } } -async fn close_with_policy_violation(socket: &mut WebSocket, reason: &str) { - let _ = socket - .send(Message::Close(Some(CloseFrame { - code: 1008, - reason: reason.to_string().into(), - }))) - .await; +/// Sends a close frame, giving up after [`CLOSE_TIMEOUT`]. +async fn close(socket: &mut WebSocket, (code, reason): Closing) { + let frame = Message::Close(Some(CloseFrame { + code, + reason: reason.into(), + })); + let _ = tokio::time::timeout(CLOSE_TIMEOUT, socket.send(frame)).await; } -/// Tells the peer its stream ended because the token that authorized it -/// expired (close code 1008). The peer may not be reading, so the send is -/// bounded by [`CLOSE_TIMEOUT`]. -async fn close_with_credential_expired(socket: &mut WebSocket) { - let close = Message::Close(Some(CloseFrame { - code: 1008, - reason: "credential-expired".into(), - })); - let _ = tokio::time::timeout(CLOSE_TIMEOUT, socket.send(close)).await; +async fn close_with_policy_violation(socket: &mut WebSocket, reason: &'static str) { + close(socket, (1008, reason)).await; } /// Whether `error` is the WebSocket layer refusing a message or frame larger @@ -500,17 +537,6 @@ fn is_message_too_big(error: &axum::Error) -> bool { .is_some_and(|source| matches!(source, tungstenite::Error::Capacity(_))) } -/// Tells the peer its message was refused for its size (close code 1009) -/// rather than leaving it with a dropped connection. The oversized payload is -/// left unread, so a peer still sending it may see a reset instead. -async fn close_with_message_too_big(socket: &mut WebSocket) { - let close = Message::Close(Some(CloseFrame { - code: 1009, - reason: "message-too-big".into(), - })); - let _ = tokio::time::timeout(CLOSE_TIMEOUT, socket.send(close)).await; -} - #[cfg(test)] mod tests { use std::time::Duration; @@ -518,10 +544,24 @@ mod tests { use chrono::Utc; use super::{ - BindingTokenRejection, ClosedConnections, TRIM_AFTER_CLOSED_CONNECTIONS, credential_expiry, - parse_bind_with_token_message, time_until, validate_binding_token_for_request, + BindingTokenRejection, CLIENT_TOO_SLOW, CREDENTIAL_EXPIRED, ClosedConnections, + TRIM_AFTER_CLOSED_CONNECTIONS, credential_expiry, parse_bind_with_token_message, + release_closing, time_until, validate_binding_token_for_request, }; + #[test] + fn a_released_client_is_told_why_unless_its_subscription_went_away() { + let past = Some(Utc::now() - chrono::Duration::seconds(1)); + let future = Some(Utc::now() + chrono::Duration::seconds(60)); + for valid in [None, future] { + assert_eq!(release_closing(true, valid), Some(CLIENT_TOO_SLOW)); + assert_eq!(release_closing(false, valid), None); + } + for too_slow in [true, false] { + assert_eq!(release_closing(too_slow, past), Some(CREDENTIAL_EXPIRED)); + } + } + #[test] fn a_trim_is_due_once_per_batch_of_closed_connections() { let closed = ClosedConnections::new(); diff --git a/crates/rest/src/lib.rs b/crates/rest/src/lib.rs index e845e4afca..09f2c77677 100644 --- a/crates/rest/src/lib.rs +++ b/crates/rest/src/lib.rs @@ -960,6 +960,14 @@ where "HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS", default_sub_config.status_write_timeout, ), + ws_bind_timeout: subscription_duration_ms_from_env( + "HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS", + default_sub_config.ws_bind_timeout, + ), + ws_send_timeout: subscription_duration_ms_from_env( + "HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS", + default_sub_config.ws_send_timeout, + ), ..default_sub_config }; let sub_config = @@ -1392,6 +1400,10 @@ fn subscription_dispatch_config( "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS", &mut config.ws_max_unbound_connections, ), + ( + "HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY", + &mut config.ws_client_queue_capacity, + ), ] { *field = subscription_dispatch_limit(name, lookup(name).as_deref(), *field); } @@ -1761,6 +1773,7 @@ mod subscription_dispatch_config_tests { "HFS_SUBSCRIPTION_DISPATCH_CONCURRENCY" => "2", "HFS_SUBSCRIPTION_HANDSHAKE_CONCURRENCY" => "1", "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS" => "4", + "HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY" => "5", "HFS_SUBSCRIPTION_MAX_PENDING_NOTIFICATIONS_PER_TENANT" => "2", "HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE" => "0", _ => panic!("unknown dispatch setting: {name}"), @@ -1770,6 +1783,7 @@ mod subscription_dispatch_config_tests { }, ); assert_eq!(config.ws_max_unbound_connections, 4); + assert_eq!(config.ws_client_queue_capacity, 5); let engine = helios_subscriptions::SubscriptionEngine::new( config, "https://example.org/fhir".into(), diff --git a/crates/rest/tests/ws_client_deadlines.rs b/crates/rest/tests/ws_client_deadlines.rs new file mode 100644 index 0000000000..b5302e8b07 --- /dev/null +++ b/crates/rest/tests/ws_client_deadlines.rs @@ -0,0 +1,304 @@ +//! The limits of a `/ws/subscriptions/bind` connection and the close frame +//! that names the one it ran into: `bind-timeout` for a connection that does +//! not bind, `client-too-slow` for a bound client that does not accept a frame +//! in time or lets its notification queue overflow. A peer that does not read +//! the close frame either is dropped without it. +#![cfg(feature = "subscriptions")] + +use std::sync::Arc; +use std::time::Duration; + +use chrono::Utc; +use futures::{SinkExt, StreamExt}; +use helios_fhir::FhirVersion; +use helios_persistence::backends::sqlite::SqliteBackend; +use helios_persistence::tenant::TenantId; +use helios_rest::{AppState, ServerConfig}; +use helios_subscriptions::{ + ResourceEvent, ResourceEventType, SubscriptionConfig, SubscriptionEngine, +}; +use serde_json::{Value, json}; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + +type Client = WebSocketStream>; + +/// The tenant `ServerConfig::for_testing()` resolves requests to. +const TENANT_ID: &str = "test-tenant"; +const TOPIC_URL: &str = "http://example.org/topic/encounter-create"; +const SUBSCRIPTION_ID: &str = "sub-ws-1"; + +/// How long the server tries to send a close frame. +const CLOSE_TIMEOUT: Duration = Duration::from_secs(5); + +/// Close code and reason of the frame that ended a connection. +type Closed = Option<(u16, String)>; + +fn policy_violation(reason: &str) -> Closed { + Some((1008, reason.to_string())) +} + +/// Serves the FHIR routes with a subscription engine on a loopback port. +async fn serve(config: SubscriptionConfig) -> (std::net::SocketAddr, Arc) { + let backend = Arc::new(SqliteBackend::in_memory().expect("in-memory sqlite")); + backend.init_schema().expect("init schema"); + let config = SubscriptionConfig { + supported_channel_types: vec!["websocket".to_string()], + ..config + }; + let engine = Arc::new(SubscriptionEngine::new( + config, + "http://localhost".to_string(), + )); + let state = AppState::new(backend, ServerConfig::for_testing()) + .with_subscription_engine(Arc::clone(&engine)); + let app = helios_rest::routing::fhir_routes::create_routes(state); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind loopback"); + let addr = listener.local_addr().expect("local addr"); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve"); + }); + (addr, engine) +} + +async fn connect(addr: std::net::SocketAddr) -> Client { + let (socket, _) = + tokio_tungstenite::connect_async(format!("ws://{addr}/ws/subscriptions/bind")) + .await + .expect("upgrade"); + socket +} + +/// Reads until the server ends the connection and returns how many +/// notifications arrived before that, and the code and reason of its close +/// frame, or `None` if it ended without one. +async fn read_to_end(socket: &mut Client) -> (usize, Closed) { + tokio::time::timeout(Duration::from_secs(20), async { + let mut notifications = 0; + while let Some(frame) = socket.next().await { + match frame { + Ok(Message::Close(Some(close))) => { + return ( + notifications, + Some((close.code.into(), close.reason.to_string())), + ); + } + Ok(Message::Close(None)) | Err(_) => break, + Ok(Message::Text(_)) => notifications += 1, + Ok(_) => {} + } + } + (notifications, None) + }) + .await + .expect("the server ends the connection") +} + +fn event( + resource_type: &str, + id: &str, + event_type: ResourceEventType, + resource: Option, +) -> ResourceEvent { + ResourceEvent { + tenant_id: TenantId::new(TENANT_ID), + fhir_version: FhirVersion::default(), + resource_type: resource_type.to_string(), + resource_id: id.to_string(), + version_id: "1".to_string(), + event_type, + resource, + previous_resource: None, + timestamp: Utc::now(), + } +} + +/// Registers a topic and a websocket Subscription on it (R4 backport shapes, +/// the default FHIR version) and returns a binding token for the Subscription. +async fn binding_token(engine: &SubscriptionEngine) -> String { + engine + .on_resource_event(event( + "Basic", + "topic-1", + ResourceEventType::Create, + Some(json!({ + "resourceType": "Basic", + "id": "topic-1", + "code": { + "coding": [{ + "system": "http://hl7.org/fhir/fhir-types", + "code": "SubscriptionTopic" + }] + }, + "extension": [{ + "url": "http://hl7.org/fhir/5.0/StructureDefinition/extension-SubscriptionTopic.url", + "valueUri": TOPIC_URL + }, { + "url": "http://hl7.org/fhir/4.3/StructureDefinition/extension-SubscriptionTopic.resourceTrigger", + "extension": [{ + "url": "resource", + "valueUri": "http://hl7.org/fhir/StructureDefinition/Encounter" + }, { + "url": "supportedInteraction", + "valueCode": "create" + }] + }] + })), + )) + .await; + engine + .on_resource_event(event( + "Subscription", + SUBSCRIPTION_ID, + ResourceEventType::Create, + Some(json!({ + "resourceType": "Subscription", + "id": SUBSCRIPTION_ID, + "status": "requested", + "criteria": TOPIC_URL, + "channel": { + "type": "websocket", + "payload": "application/fhir+json" + } + })), + )) + .await; + engine + .ws_token_manager() + .generate_token(TENANT_ID, SUBSCRIPTION_ID) + .expect("a binding token is issued") + .0 +} + +/// Connects, binds and reads the handshake notification. +async fn bound_client(addr: std::net::SocketAddr, engine: &SubscriptionEngine) -> Client { + let token = binding_token(engine).await; + let mut socket = connect(addr).await; + socket + .send(Message::Text(format!("bind-with-token {token}").into())) + .await + .expect("send bind message"); + let handshake = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .expect("handshake arrives"); + assert!( + matches!(handshake, Some(Ok(Message::Text(_)))), + "the bind is accepted and answered with the handshake notification, got {handshake:?}" + ); + socket +} + +/// Queues `count` notifications of about `size` bytes for the bound client. +fn notify(engine: &SubscriptionEngine, count: usize, size: usize) { + let notification = json!({"resourceType": "Bundle", "padding": "x".repeat(size)}); + for _ in 0..count { + engine + .ws_manager() + .send_to_subscription(TENANT_ID, SUBSCRIPTION_ID, ¬ification); + } +} + +/// Binds a client that does not read, sends it more than the socket buffers +/// hold, and returns once the server has given up on it. +async fn stalled_client(addr: std::net::SocketAddr, engine: &SubscriptionEngine) -> Client { + let socket = bound_client(addr, engine).await; + notify(engine, 6, 8 * 1024 * 1024); + tokio::time::timeout(Duration::from_secs(20), async { + while engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID) != 0 { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the stalled client is removed from the manager"); + socket +} + +fn short_send_timeout() -> SubscriptionConfig { + SubscriptionConfig { + ws_send_timeout: Duration::from_millis(500), + ..Default::default() + } +} + +#[tokio::test] +async fn a_connection_that_does_not_bind_in_time_is_closed() { + let (addr, _engine) = serve(SubscriptionConfig { + ws_bind_timeout: Duration::from_millis(200), + ..Default::default() + }) + .await; + let mut socket = connect(addr).await; + + assert_eq!( + read_to_end(&mut socket).await, + (0, policy_violation("bind-timeout")) + ); +} + +#[tokio::test] +async fn a_stalled_client_that_reads_again_is_told_it_was_too_slow() { + let (addr, engine) = serve(short_send_timeout()).await; + let mut socket = stalled_client(addr, &engine).await; + + let (notifications, closed) = read_to_end(&mut socket).await; + assert_eq!(closed, policy_violation("client-too-slow")); + assert!( + notifications < 6, + "the queued notifications are not delivered, got {notifications}" + ); +} + +#[tokio::test] +async fn a_stalled_client_that_never_reads_does_not_hold_the_close_frame() { + let (addr, engine) = serve(short_send_timeout()).await; + let mut socket = stalled_client(addr, &engine).await; + + tokio::time::sleep(CLOSE_TIMEOUT + Duration::from_secs(2)).await; + + let (_, closed) = read_to_end(&mut socket).await; + assert_eq!( + closed, None, + "the server gave up on the close frame and dropped the connection" + ); +} + +#[tokio::test] +async fn a_client_whose_queue_overflows_is_told_it_was_too_slow() { + let (addr, engine) = serve(SubscriptionConfig { + ws_client_queue_capacity: 2, + ..Default::default() + }) + .await; + let mut socket = bound_client(addr, &engine).await; + + notify(&engine, 3, 16); + + assert_eq!( + read_to_end(&mut socket).await, + (0, policy_violation("client-too-slow")) + ); + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 0 + ); +} + +#[tokio::test] +async fn a_deleted_subscription_does_not_call_its_client_too_slow() { + let (addr, engine) = serve(SubscriptionConfig::default()).await; + let mut socket = bound_client(addr, &engine).await; + + engine + .on_resource_event(event( + "Subscription", + SUBSCRIPTION_ID, + ResourceEventType::Delete, + None, + )) + .await; + + assert_eq!(read_to_end(&mut socket).await, (0, None)); +} diff --git a/crates/subscriptions/README.md b/crates/subscriptions/README.md index ae49fff6ba..ad46db687a 100644 --- a/crates/subscriptions/README.md +++ b/crates/subscriptions/README.md @@ -159,6 +159,9 @@ Comparators supported: `eq` (default), `in`. Native `filterBy.comparator` values | `HFS_SUBSCRIPTION_DISPATCH_CONCURRENCY` | `64` | Simultaneous channel attempts, shared by notifications and activation handshakes | | `HFS_SUBSCRIPTION_HANDSHAKE_CONCURRENCY` | `8` | Running activation flows, shared by live writes and startup rehydration | | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | `256` | WebSocket connections that may be waiting to send their bind message at once; an upgrade past the limit is refused with `503` and `Retry-After` | +| `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | `10000` | How long a WebSocket connection may take to send its bind message (`1008 bind-timeout` past it) | +| `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | `30000` | How long a bound WebSocket client may take to accept one frame, whatever its size (`1008 client-too-slow` past it); raise it for large `full-resource` notifications over slow links | +| `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | `256` | Notifications a bound WebSocket client may have waiting; a client whose queue overflows is closed (`1008 client-too-slow`) | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | `100` | Events remembered per subscription for `$events` (number, timestamp, focus reference only; in memory, lost on restart); `0` disables the history | | `max_retries` *(config field)* | `10` | Delivery attempts per notification; `0` disables retries | | `retry_initial_delay` *(config field)* | `1s` | Base delay for delivery backoff | @@ -417,7 +420,9 @@ After a successful bind message, the server sends a handshake notification bundl The WebSocket protocol is **unidirectional** (server → client) after binding. Additional bind messages on the same connection are rejected; close frames trigger graceful cleanup. -**Deadlines and queueing:** a connection that sends no bind message within 10 seconds is closed (`1008 bind-timeout`). Each bound client has a queue of 256 notifications; a client that stops reading its socket is given 30 seconds to accept a frame and is dropped once its queue is full, so a stalled client retains no further notifications in the server. It reconnects with a new binding token and replays missed events through `$events`. +**Deadlines and queueing:** a connection that sends no bind message within 10 seconds is closed (`1008 bind-timeout`). Each bound client has a queue of 256 notifications; a client that stops reading its socket is given 30 seconds to accept a frame and is dropped once its queue is full, so a stalled client retains no further notifications in the server. Both cases close the connection with `1008 client-too-slow` and discard the notifications still queued. The server waits at most 5 seconds for a close frame to be accepted; a client that still is not reading sees the connection drop without one. The two deadlines and the queue size are configurable (`HFS_SUBSCRIPTION_WS_*`, see [Configuration](#configuration)). + +**Catching up after a drop:** the client reconnects with a new binding token and reads the events it missed from `$events`. That is not a full replay: `$events` returns id-only references whatever the subscription's `content`, and only the latest `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` events (100 by default, fewer than the 256 notifications a full queue discards), kept in memory. A client that missed more than that, or that was away across a server restart, reads the resources it follows again. **Credential lifetime:** with authentication enabled, a bound stream lives no longer than the bearer token sent on the WebSocket upgrade request. When that token expires the server closes the connection with `1008 credential-expired` and delivers nothing further to it; the client requests a new binding token, binds again with a current bearer token and catches up through `$events`. With authentication disabled a stream has no such deadline. @@ -557,5 +562,5 @@ A Kafka-backed architecture addresses most of the single-instance and performanc - Batch and transaction bundle entries do not emit subscription events — only direct CRUD handlers (create, update, delete, patch) do - [`eventTrigger`](https://hl7.org/fhir/subscriptiontopic.html) is not supported — only `resourceTrigger` (create, update, delete) is implemented - The engine is in-memory only and single-instance — subscriptions and topics are not shared across cluster nodes or reloaded from storage on restart (see [Clustering](#clustering) above) -- WebSocket notifications are best-effort — if no clients are connected when an event fires the notification is silently dropped; there is no replay or queueing for late-connecting clients, and a connected client that stops reading is dropped once 256 notifications are queued for it +- WebSocket notifications are best-effort — if no clients are connected when an event fires the notification is silently dropped; there is no replay or queueing for late-connecting clients, and a connected client that stops reading is dropped once its queue (256 notifications by default) is full - Email and FHIR messaging channels are not yet implemented (planned for subsequent phases) diff --git a/crates/subscriptions/src/channels/ws_manager.rs b/crates/subscriptions/src/channels/ws_manager.rs index 2d923c83c1..ed99ceac40 100644 --- a/crates/subscriptions/src/channels/ws_manager.rs +++ b/crates/subscriptions/src/channels/ws_manager.rs @@ -4,27 +4,32 @@ //! crate uses this to broadcast notifications, while the REST crate uses //! it to register new connections from the WebSocket upgrade handler. //! -//! Each client has a bounded queue of [`CLIENT_QUEUE_CAPACITY`] -//! notifications. A client that stops reading its socket stops draining the -//! queue; once the queue is full the client is dropped rather than letting -//! every further matching write retain another bundle in the process until -//! the socket closes. The client reconnects and replays through `$events`. +//! Each client has a bounded queue of notifications +//! ([`CLIENT_QUEUE_CAPACITY`] unless configured otherwise). A client that +//! stops reading its socket stops draining the queue; once the queue is full +//! the client is dropped rather than letting every further matching write +//! retain another bundle in the process until the socket closes. The client +//! reconnects and reads what it missed from `$events`, which lists only the +//! most recent events, by reference. //! //! A notification is serialized once per broadcast and every client's queue //! holds a reference-counted handle to the same bytes, so the memory a //! broadcast retains does not grow with the number of clients. A //! subscription has at most [`MAX_CLIENTS_PER_SUBSCRIPTION`] bound clients. +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + use bytes::Bytes; use chrono::{DateTime, Utc}; use dashmap::DashMap; use tokio::sync::mpsc; -use tokio::sync::mpsc::error::TrySendError; +use tokio::sync::mpsc::error::{TryRecvError, TrySendError}; use tracing::{debug, warn}; use uuid::Uuid; -/// Notifications a bound client may have waiting before it counts as not -/// draining and is dropped. +/// Notifications a bound client may have waiting, by default, before it +/// counts as not draining and is dropped. pub const CLIENT_QUEUE_CAPACITY: usize = 256; /// Clients one subscription may have bound at a time. A further bind is @@ -38,6 +43,36 @@ pub type WsPayload = Bytes; /// Sender half given to a connected WebSocket client. pub type WsClientSender = mpsc::Sender; +/// Receiving half of a bound client's notification queue. +pub struct WsClientReceiver { + queue: mpsc::Receiver, + too_slow: Arc, +} + +impl WsClientReceiver { + /// The next queued notification, or `None` once the queue is empty and the + /// manager has released the client. Cancel safe. + pub async fn recv(&mut self) -> Option { + self.queue.recv().await + } + + /// The next notification if one is already queued. + pub fn try_recv(&mut self) -> Result { + self.queue.try_recv() + } + + /// Whether the manager has released the client. Notifications queued + /// before that may still be buffered. + pub fn is_closed(&self) -> bool { + self.queue.is_closed() + } + + /// Whether the manager released the client because its queue was full. + pub fn was_too_slow(&self) -> bool { + self.too_slow.load(Ordering::Acquire) + } +} + /// One bound client of a subscription. struct BoundClient { id: String, @@ -45,6 +80,8 @@ struct BoundClient { /// When the credential that authorized the bind expires, if it has an /// expiry. Nothing is delivered to the client from then on. deadline: Option>, + /// Shared with the client's [`WsClientReceiver`]. + too_slow: Arc, } impl BoundClient { @@ -57,6 +94,8 @@ impl BoundClient { pub struct WebSocketManager { /// Connected clients keyed by (tenant_id, subscription_id). clients: DashMap<(String, String), Vec>, + /// Notifications a client may have waiting. + queue_capacity: usize, } impl WebSocketManager { @@ -64,17 +103,26 @@ impl WebSocketManager { pub fn new() -> Self { Self { clients: DashMap::new(), + queue_capacity: CLIENT_QUEUE_CAPACITY, } } + /// Sets how many notifications a client registered from now on may have + /// waiting. Must be at least 1. + pub fn with_queue_capacity(mut self, queue_capacity: usize) -> Self { + self.queue_capacity = queue_capacity; + self + } + /// Registers a new WebSocket client for a subscription. /// /// Returns `(client_id, receiver)`. The caller (WebSocket handler) reads /// notifications from the receiver and forwards them over the socket. - /// The receiver is closed ([`mpsc::Receiver::is_closed`]) as soon as the - /// subscription is deregistered or the client let - /// [`CLIENT_QUEUE_CAPACITY`] notifications pile up, while the queued ones - /// are still buffered; the handler stops there instead of draining them. + /// The receiver is closed ([`WsClientReceiver::is_closed`]) as soon as the + /// subscription is deregistered or the client's queue overflows, while the + /// queued notifications are still buffered; the handler stops there + /// instead of draining them. [`WsClientReceiver::was_too_slow`] tells the + /// two apart. /// /// Returns `None` when the subscription already has /// [`MAX_CLIENTS_PER_SUBSCRIPTION`] connected clients. @@ -85,7 +133,7 @@ impl WebSocketManager { &self, tenant_id: &str, subscription_id: &str, - ) -> Option<(String, mpsc::Receiver)> { + ) -> Option<(String, WsClientReceiver)> { self.register_client_until(tenant_id, subscription_id, None) } @@ -104,7 +152,7 @@ impl WebSocketManager { tenant_id: &str, subscription_id: &str, deadline: Option>, - ) -> Option<(String, mpsc::Receiver)> { + ) -> Option<(String, WsClientReceiver)> { let now = Utc::now(); if deadline.is_some_and(|deadline| deadline <= now) { warn!( @@ -127,12 +175,14 @@ impl WebSocketManager { ); return None; } - let (tx, rx) = mpsc::channel(CLIENT_QUEUE_CAPACITY); + let (tx, queue) = mpsc::channel(self.queue_capacity); + let too_slow = Arc::new(AtomicBool::new(false)); let client_id = Uuid::new_v4().to_string(); entry.push(BoundClient { id: client_id.clone(), sender: tx, deadline, + too_slow: Arc::clone(&too_slow), }); drop(entry); @@ -143,7 +193,7 @@ impl WebSocketManager { "WebSocket client registered" ); - Some((client_id, rx)) + Some((client_id, WsClientReceiver { queue, too_slow })) } /// Removes a specific client by ID (called on disconnect). @@ -220,11 +270,12 @@ impl WebSocketManager { true } Err(TrySendError::Full(_)) => { + client.too_slow.store(true, Ordering::Release); warn!( tenant_id, subscription_id, client_id = %client.id, - queued = CLIENT_QUEUE_CAPACITY, + queued = self.queue_capacity, "WebSocket client is not draining its notifications; dropping it" ); false @@ -408,6 +459,25 @@ mod tests { // Receiver should return None (channel closed). assert!(rx1.recv().await.is_none()); + assert!( + !rx1.was_too_slow(), + "a deregistered subscription's client was not too slow" + ); + } + + /// The configured queue capacity replaces the default one. + #[tokio::test] + async fn a_client_is_dropped_at_the_configured_queue_capacity() { + let mgr = WebSocketManager::new().with_queue_capacity(2); + let (_id, rx) = mgr.register_client("t1", "sub-1").unwrap(); + + let n = json!({"type": "event-notification"}); + assert_eq!(mgr.send_to_subscription("t1", "sub-1", &n), 1); + assert_eq!(mgr.send_to_subscription("t1", "sub-1", &n), 1); + assert!(!rx.is_closed()); + assert_eq!(mgr.send_to_subscription("t1", "sub-1", &n), 0); + assert!(rx.is_closed()); + assert!(rx.was_too_slow()); } /// A client that stopped reading keeps its queued notifications until the @@ -438,7 +508,9 @@ mod tests { // still full: the signal the connection handler stops on, rather // than delivering the backlog (#2720). assert!(stalled_rx.is_closed()); + assert!(stalled_rx.was_too_slow()); assert!(!draining_rx.is_closed()); + assert!(!draining_rx.was_too_slow()); let mut queued = 0; while let Some(n) = stalled_rx.recv().await.map(json) { @@ -474,6 +546,7 @@ mod tests { ); assert_eq!(json(unbounded_rx.recv().await.unwrap()), after); assert!(expiring_rx.recv().await.is_none()); + assert!(!expiring_rx.was_too_slow()); assert_eq!(mgr.client_count("t1", "sub-1"), 1); } diff --git a/crates/subscriptions/src/config.rs b/crates/subscriptions/src/config.rs index 2609727385..75ab847f76 100644 --- a/crates/subscriptions/src/config.rs +++ b/crates/subscriptions/src/config.rs @@ -77,6 +77,19 @@ pub struct SubscriptionConfig { /// refused while every slot is held. Bound clients do not count. pub ws_max_unbound_connections: usize, + /// How long a WebSocket connection may take to send its bind message. + /// Zero is replaced by the default. + pub ws_bind_timeout: Duration, + + /// How long a bound WebSocket client may take to accept one frame, + /// whatever its size. A client past it is closed. Zero is replaced by the + /// default. + pub ws_send_timeout: Duration, + + /// Notifications a bound WebSocket client may have waiting. A client whose + /// queue is full when the next one arrives is closed. + pub ws_client_queue_capacity: usize, + /// When `true`, rest-hook delivery to private/loopback/link-local IPs is /// permitted. Default `false`: the endpoint is chosen by whoever writes /// the Subscription. Set `HFS_SUBSCRIPTION_ALLOW_PRIVATE_ENDPOINTS=true` @@ -171,6 +184,9 @@ impl Default for SubscriptionConfig { supported_channel_types: vec!["rest-hook".to_string()], ws_token_lifetime_secs: 30, ws_max_unbound_connections: 256, + ws_bind_timeout: Duration::from_secs(10), + ws_send_timeout: Duration::from_secs(30), + ws_client_queue_capacity: crate::channels::ws_manager::CLIENT_QUEUE_CAPACITY, allow_private_endpoints: false, smtp: None, messaging: None, @@ -218,6 +234,11 @@ impl SubscriptionConfig { &mut self.ws_max_unbound_connections, defaults.ws_max_unbound_connections, ), + ( + "ws_client_queue_capacity", + &mut self.ws_client_queue_capacity, + defaults.ws_client_queue_capacity, + ), ] { if *capacity == 0 || *capacity > tokio::sync::Semaphore::MAX_PERMITS { tracing::warn!( @@ -229,6 +250,27 @@ impl SubscriptionConfig { *capacity = fallback; } } + for (name, timeout, fallback) in [ + ( + "ws_bind_timeout", + &mut self.ws_bind_timeout, + defaults.ws_bind_timeout, + ), + ( + "ws_send_timeout", + &mut self.ws_send_timeout, + defaults.ws_send_timeout, + ), + ] { + if timeout.is_zero() { + tracing::warn!( + setting = name, + effective_ms = fallback.as_millis() as u64, + "Subscription WebSocket timeout is zero; using default" + ); + *timeout = fallback; + } + } if self.per_subscription_queue_capacity > self.max_pending_notifications { tracing::warn!( configured = self.per_subscription_queue_capacity, @@ -350,6 +392,7 @@ mod tests { dispatch_concurrency: invalid, handshake_concurrency: invalid, ws_max_unbound_connections: invalid, + ws_client_queue_capacity: invalid, ..SubscriptionConfig::default() } .normalize_dispatch_limits(); @@ -357,6 +400,10 @@ mod tests { config.ws_max_unbound_connections, default.ws_max_unbound_connections ); + assert_eq!( + config.ws_client_queue_capacity, + default.ws_client_queue_capacity + ); assert_eq!(config.event_queue_capacity, default.event_queue_capacity); assert_eq!( config.max_pending_notifications, @@ -371,6 +418,28 @@ mod tests { } } + #[test] + fn zero_websocket_timeouts_use_defaults() { + let default = SubscriptionConfig::default(); + let config = SubscriptionConfig { + ws_bind_timeout: Duration::ZERO, + ws_send_timeout: Duration::ZERO, + ..SubscriptionConfig::default() + } + .normalize_dispatch_limits(); + assert_eq!(config.ws_bind_timeout, default.ws_bind_timeout); + assert_eq!(config.ws_send_timeout, default.ws_send_timeout); + + let config = SubscriptionConfig { + ws_bind_timeout: Duration::from_millis(1), + ws_send_timeout: Duration::from_secs(600), + ..SubscriptionConfig::default() + } + .normalize_dispatch_limits(); + assert_eq!(config.ws_bind_timeout, Duration::from_millis(1)); + assert_eq!(config.ws_send_timeout, Duration::from_secs(600)); + } + #[test] fn subscriber_capacity_is_clamped_to_the_global_budget() { let config = SubscriptionConfig { diff --git a/crates/subscriptions/src/engine/mod.rs b/crates/subscriptions/src/engine/mod.rs index 6e5dba23ce..038b4eb8f9 100644 --- a/crates/subscriptions/src/engine/mod.rs +++ b/crates/subscriptions/src/engine/mod.rs @@ -129,7 +129,8 @@ impl SubscriptionEngine { let rest_hook_channel = Arc::new( RestHookChannel::new().with_private_endpoints_allowed(config.allow_private_endpoints), ); - let ws_manager = Arc::new(WebSocketManager::new()); + let ws_manager = + Arc::new(WebSocketManager::new().with_queue_capacity(config.ws_client_queue_capacity)); let ws_channel = Arc::new(WebSocketChannel::new(Arc::clone(&ws_manager))); let ws_token_manager = Arc::new(WsBindingTokenManager::new(config.ws_token_lifetime_secs)); let ws_unbound_slots = Arc::new(Semaphore::new(config.ws_max_unbound_connections)); @@ -239,6 +240,12 @@ impl SubscriptionEngine { &self.core.manager } + /// Returns the configuration the engine runs with, invalid limits already + /// replaced. + pub fn config(&self) -> &SubscriptionConfig { + &self.core.config + } + /// Returns a reference to the WebSocket manager. pub fn ws_manager(&self) -> &Arc { &self.core.ws_manager From 2aed850d8273b272f36833b8d9ae12b9a0592af8 Mon Sep 17 00:00:00 2001 From: angela-helios Date: Wed, 2 Dec 2026 13:12:27 -0400 Subject: [PATCH 4/4] fix(subscriptions): close a WebSocket client that stays behind without filling its queue A bound client that accepted every frame inside the send deadline and kept its queue under the cap could hold queued bundles for hours. Each notification must now be delivered within HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS (2 minutes by default) of being queued, or the client is closed with 1008 client-too-slow. Closes #3080 --- .../skills/work-with-subscriptions/SKILL.md | 3 +- .../skills/work-with-subscriptions/SKILL.md | 3 +- README.md | 1 + crates/hfs/src/env_names.rs | 1 + crates/rest/src/handlers/ws.rs | 70 +++++++++++++++++-- crates/rest/src/lib.rs | 4 ++ crates/rest/tests/ws_client_deadlines.rs | 65 ++++++++++++++++- crates/subscriptions/README.md | 5 +- .../subscriptions/src/channels/ws_manager.rs | 55 +++++++++++++-- crates/subscriptions/src/config.rs | 16 +++++ 10 files changed, 204 insertions(+), 19 deletions(-) diff --git a/.agents/skills/work-with-subscriptions/SKILL.md b/.agents/skills/work-with-subscriptions/SKILL.md index 4606af89ca..e0a08dfe51 100644 --- a/.agents/skills/work-with-subscriptions/SKILL.md +++ b/.agents/skills/work-with-subscriptions/SKILL.md @@ -14,7 +14,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti - The messaging channel is separately gated by `HFS_SUBSCRIPTION_MESSAGING_ENABLED`. - Endpoint safety (`channels/egress.rs`, rest-hook and messaging): endpoints that are, or resolve to, private/loopback addresses are refused unless `HFS_SUBSCRIPTION_ALLOW_PRIVATE_ENDPOINTS=true`, and redirects are never followed (a `3xx` is a permanent error). Tests that deliver to a loopback receiver set `SubscriptionConfig::allow_private_endpoints`. - Notification bundles follow the topic-based subscription spec; delivery failures retry with backoff (`engine/retry.rs`). -- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue and 30 s to accept each frame, and is closed (`1008 client-too-slow`) when it stops draining; all three limits are `HFS_SUBSCRIPTION_WS_*` variables. Every close frame is sent within 5 s or given up on. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). +- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue, 30 s to accept each frame and 2 min from queueing to take each notification, and is closed (`1008 client-too-slow`) when it stops draining or stays behind; all four limits are `HFS_SUBSCRIPTION_WS_*` variables. Every close frame is sent within 5 s or given up on. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). ## Channels (`crates/subscriptions/src/channels/`) @@ -36,6 +36,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | WebSocket connections that may be waiting to bind at once (default `256`); further upgrades get `503` with `Retry-After` | | `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | How long a WebSocket connection may take to bind (default `10000`) | | `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | How long a bound WebSocket client may take to accept one frame (default `30000`) | +| `HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS` | How long after it was queued a notification may still be undelivered to a bound WebSocket client (default `120000`) | | `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | Notifications a bound WebSocket client may have waiting (default `256`) | | `HFS_SUBSCRIPTION_REHYDRATE` | Replay stored topics/subscriptions into the engine at startup (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | Re-run activation for stored `requested`/`error` subscriptions (default `true`) | diff --git a/.claude/skills/work-with-subscriptions/SKILL.md b/.claude/skills/work-with-subscriptions/SKILL.md index 4606af89ca..e0a08dfe51 100644 --- a/.claude/skills/work-with-subscriptions/SKILL.md +++ b/.claude/skills/work-with-subscriptions/SKILL.md @@ -14,7 +14,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti - The messaging channel is separately gated by `HFS_SUBSCRIPTION_MESSAGING_ENABLED`. - Endpoint safety (`channels/egress.rs`, rest-hook and messaging): endpoints that are, or resolve to, private/loopback addresses are refused unless `HFS_SUBSCRIPTION_ALLOW_PRIVATE_ENDPOINTS=true`, and redirects are never followed (a `3xx` is a permanent error). Tests that deliver to a loopback receiver set `SubscriptionConfig::allow_private_endpoints`. - Notification bundles follow the topic-based subscription spec; delivery failures retry with backoff (`engine/retry.rs`). -- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue and 30 s to accept each frame, and is closed (`1008 client-too-slow`) when it stops draining; all three limits are `HFS_SUBSCRIPTION_WS_*` variables. Every close frame is sent within 5 s or given up on. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). +- WebSocket subscriptions use binding tokens (`ws_token`) managed per connection (`ws_manager`). A connection must bind within 10 s; a bound client has a 256-notification queue, 30 s to accept each frame and 2 min from queueing to take each notification, and is closed (`1008 client-too-slow`) when it stops draining or stays behind; all four limits are `HFS_SUBSCRIPTION_WS_*` variables. Every close frame is sent within 5 s or given up on. A subscription takes at most 16 bound clients (`1008 too-many-clients` past it) and 16 outstanding binding tokens (`429`); a notification is serialized once and its bytes shared by every client queue (#2721). ## Channels (`crates/subscriptions/src/channels/`) @@ -36,6 +36,7 @@ Use this when working in `helios-subscriptions`, the FHIR topic-based Subscripti | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | WebSocket connections that may be waiting to bind at once (default `256`); further upgrades get `503` with `Retry-After` | | `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | How long a WebSocket connection may take to bind (default `10000`) | | `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | How long a bound WebSocket client may take to accept one frame (default `30000`) | +| `HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS` | How long after it was queued a notification may still be undelivered to a bound WebSocket client (default `120000`) | | `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | Notifications a bound WebSocket client may have waiting (default `256`) | | `HFS_SUBSCRIPTION_REHYDRATE` | Replay stored topics/subscriptions into the engine at startup (default `true`) | | `HFS_SUBSCRIPTION_REHYDRATE_HANDSHAKE` | Re-run activation for stored `requested`/`error` subscriptions (default `true`) | diff --git a/README.md b/README.md index a9d5f797b5..e415c2aecf 100644 --- a/README.md +++ b/README.md @@ -463,6 +463,7 @@ JWT/bearer auth (`HFS_AUTH_*`, e.g. `HFS_AUTH_ENABLED`, `HFS_AUTH_JWKS_URL`, `HF | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | `256` | WebSocket connections that may be waiting to send their bind message at once; an upgrade past the limit is refused with `503` and `Retry-After` | | `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | `10000` | How long a WebSocket connection may take to send its bind message (`1008 bind-timeout` past it) | | `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | `30000` | How long a bound WebSocket client may take to accept one frame, whatever its size (`1008 client-too-slow` past it); raise it for large `full-resource` notifications over slow links | +| `HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS` | `120000` | How long after it was queued a notification may still be undelivered to a bound WebSocket client (`1008 client-too-slow` past it), however few are waiting; also bounds the send of one frame, so keep it above the send timeout | | `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | `256` | Notifications a bound WebSocket client may have waiting; a client whose queue overflows is closed (`1008 client-too-slow`) | | `HFS_BULK_EXPORT_ENABLED` | `true` | Enable the [Bulk Data Export](crates/rest/README.md#bulk-data-export) `$export` operation; when `false`, all `$export` endpoints return `501` | | `HFS_BULK_EXPORT_OUTPUT_BACKEND` | `local-fs` | Bulk export output store: `local-fs` or `s3`. See the [rest crate README](crates/rest/README.md#bulk-data-export) for the full `HFS_BULK_EXPORT_*` table | diff --git a/crates/hfs/src/env_names.rs b/crates/hfs/src/env_names.rs index 707de45e67..20d667d470 100644 --- a/crates/hfs/src/env_names.rs +++ b/crates/hfs/src/env_names.rs @@ -307,6 +307,7 @@ const KNOWN: &[&str] = &[ "HFS_SUBSCRIPTION_STATUS_WRITE_TIMEOUT_MS", "HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS", "HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY", + "HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS", "HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS", "HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS", "HFS_TENANT_REQUIRE_PROVISIONED", diff --git a/crates/rest/src/handlers/ws.rs b/crates/rest/src/handlers/ws.rs index 79db548679..d51b1791d4 100644 --- a/crates/rest/src/handlers/ws.rs +++ b/crates/rest/src/handlers/ws.rs @@ -14,7 +14,12 @@ //! otherwise park the handler in `send` for as long as it keeps the socket //! open while its notification queue fills. //! -//! A bound client that misses the send deadline, or that the subscription +//! A notification must reach a bound client within +//! `HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS` of being queued, so a client that +//! accepts every frame in time but stays behind cannot hold its queued +//! notifications in memory. +//! +//! A bound client that misses either deadline, or that the subscription //! engine drops because its queue is full, is closed with code 1008 and the //! reason `client-too-slow`. Every close frame is sent within //! [`CLOSE_TIMEOUT`], so a peer that is not reading gets a dropped connection @@ -256,6 +261,7 @@ async fn handle_ws_connection( }; let ws_manager = Arc::clone(engine.ws_manager()); let send_timeout = engine.config().ws_send_timeout; + let delivery_timeout = engine.config().ws_delivery_timeout; info!( tenant_id = %tenant_id, @@ -314,7 +320,7 @@ async fn handle_ws_connection( break Some(CREDENTIAL_EXPIRED); } // Notification from the subscription engine. - notification = rx.recv() => { + notification = rx.recv_queued() => { match notification { // The manager released this client: it let its queue // fill and was dropped, or the subscription went away. @@ -328,9 +334,22 @@ async fn handle_ws_connection( ); break release_closing(rx.was_too_slow(), credential_expires_at); } - Some(payload) => { - match Utf8Bytes::try_from(payload) { - Ok(msg) => match send_within_deadline(&mut socket, msg, send_timeout).await { + Some(notification) => { + let Some(deadline) = send_deadline( + notification.queued_at.elapsed(), + send_timeout, + delivery_timeout, + ) else { + warn!( + client_id = %client_id, + subscription_id = %subscription_id, + deadline_ms = delivery_timeout.as_millis() as u64, + "A notification was not delivered to the client within the deadline after it was queued; closing" + ); + break Some(CLIENT_TOO_SLOW); + }; + match Utf8Bytes::try_from(notification.payload) { + Ok(msg) => match send_within_deadline(&mut socket, msg, deadline).await { Ok(()) => {} Err(SendFailure::Disconnected) => { debug!( @@ -342,7 +361,7 @@ async fn handle_ws_connection( Err(SendFailure::Stalled) => { warn!( client_id = %client_id, - deadline_ms = send_timeout.as_millis() as u64, + deadline_ms = deadline.as_millis() as u64, "Client did not accept a notification within the deadline; closing" ); break Some(CLIENT_TOO_SLOW); @@ -425,6 +444,21 @@ enum SendFailure { Stalled, } +/// How long the send of a notification that was queued `waited` ago may take: +/// the send timeout, or what is left of the delivery timeout if that is less. +/// `None` once nothing is left of it. +/// +/// Notifications are sent in the order they were queued, so bounding the one +/// being sent also bounds every one behind it. +fn send_deadline( + waited: Duration, + send_timeout: Duration, + delivery_timeout: Duration, +) -> Option { + let remaining = delivery_timeout.saturating_sub(waited); + (!remaining.is_zero()).then(|| remaining.min(send_timeout)) +} + /// Sends one text frame, giving up after `deadline`: a peer that stops reading /// leaves `send` pending once the socket buffers are full. async fn send_within_deadline( @@ -546,7 +580,7 @@ mod tests { use super::{ BindingTokenRejection, CLIENT_TOO_SLOW, CREDENTIAL_EXPIRED, ClosedConnections, TRIM_AFTER_CLOSED_CONNECTIONS, credential_expiry, parse_bind_with_token_message, - release_closing, time_until, validate_binding_token_for_request, + release_closing, send_deadline, time_until, validate_binding_token_for_request, }; #[test] @@ -562,6 +596,28 @@ mod tests { } } + #[test] + fn a_send_is_bounded_by_both_the_send_and_the_delivery_timeout() { + let send = Duration::from_secs(30); + let delivery = Duration::from_secs(120); + assert_eq!(send_deadline(Duration::ZERO, send, delivery), Some(send)); + assert_eq!( + send_deadline(Duration::from_secs(90), send, delivery), + Some(send) + ); + assert_eq!( + send_deadline(Duration::from_secs(119), send, delivery), + Some(Duration::from_secs(1)), + "what is left of the delivery timeout" + ); + for overdue in [120, 121, 7200] { + assert_eq!( + send_deadline(Duration::from_secs(overdue), send, delivery), + None + ); + } + } + #[test] fn a_trim_is_due_once_per_batch_of_closed_connections() { let closed = ClosedConnections::new(); diff --git a/crates/rest/src/lib.rs b/crates/rest/src/lib.rs index 09f2c77677..c0ac929c6c 100644 --- a/crates/rest/src/lib.rs +++ b/crates/rest/src/lib.rs @@ -968,6 +968,10 @@ where "HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS", default_sub_config.ws_send_timeout, ), + ws_delivery_timeout: subscription_duration_ms_from_env( + "HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS", + default_sub_config.ws_delivery_timeout, + ), ..default_sub_config }; let sub_config = diff --git a/crates/rest/tests/ws_client_deadlines.rs b/crates/rest/tests/ws_client_deadlines.rs index b5302e8b07..a83fdbcf6e 100644 --- a/crates/rest/tests/ws_client_deadlines.rs +++ b/crates/rest/tests/ws_client_deadlines.rs @@ -1,7 +1,7 @@ //! The limits of a `/ws/subscriptions/bind` connection and the close frame //! that names the one it ran into: `bind-timeout` for a connection that does //! not bind, `client-too-slow` for a bound client that does not accept a frame -//! in time or lets its notification queue overflow. A peer that does not read +//! in time, stays behind, or lets its notification queue overflow. A peer that does not read //! the close frame either is dropped without it. #![cfg(feature = "subscriptions")] @@ -76,6 +76,11 @@ async fn connect(addr: std::net::SocketAddr) -> Client { /// notifications arrived before that, and the code and reason of its close /// frame, or `None` if it ended without one. async fn read_to_end(socket: &mut Client) -> (usize, Closed) { + read_slowly_to_end(socket, Duration::ZERO).await +} + +/// Like [`read_to_end`], waiting `pause` after each notification. +async fn read_slowly_to_end(socket: &mut Client, pause: Duration) -> (usize, Closed) { tokio::time::timeout(Duration::from_secs(20), async { let mut notifications = 0; while let Some(frame) = socket.next().await { @@ -87,7 +92,10 @@ async fn read_to_end(socket: &mut Client) -> (usize, Closed) { ); } Ok(Message::Close(None)) | Err(_) => break, - Ok(Message::Text(_)) => notifications += 1, + Ok(Message::Text(_)) => { + notifications += 1; + tokio::time::sleep(pause).await; + } Ok(_) => {} } } @@ -286,6 +294,59 @@ async fn a_client_whose_queue_overflows_is_told_it_was_too_slow() { ); } +/// Reads one notification every 100 ms, each well inside the send deadline, +/// and never has more than 24 of the 256 allowed waiting. +#[tokio::test] +async fn a_slow_reader_that_stays_under_the_queue_capacity_is_closed() { + let (addr, engine) = serve(SubscriptionConfig { + ws_delivery_timeout: Duration::from_millis(500), + ..Default::default() + }) + .await; + let mut socket = bound_client(addr, &engine).await; + + notify(&engine, 24, 4 * 1024 * 1024); + + let (notifications, closed) = read_slowly_to_end(&mut socket, Duration::from_millis(100)).await; + assert_eq!(closed, policy_violation("client-too-slow")); + assert!( + notifications < 24, + "the queued notifications are not all delivered, got {notifications}" + ); + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 0 + ); +} + +/// The delivery deadline counts from each notification, not from the bind or +/// from the first one. +#[tokio::test] +async fn a_client_that_keeps_up_outlives_the_delivery_deadline() { + let (addr, engine) = serve(SubscriptionConfig { + ws_delivery_timeout: Duration::from_secs(1), + ..Default::default() + }) + .await; + let mut socket = bound_client(addr, &engine).await; + + for i in 0..20 { + notify(&engine, 1, 16); + let frame = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .expect("the notification arrives"); + assert!( + matches!(frame, Some(Ok(Message::Text(_)))), + "notification {i} is delivered, got {frame:?}" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!( + engine.ws_manager().client_count(TENANT_ID, SUBSCRIPTION_ID), + 1 + ); +} + #[tokio::test] async fn a_deleted_subscription_does_not_call_its_client_too_slow() { let (addr, engine) = serve(SubscriptionConfig::default()).await; diff --git a/crates/subscriptions/README.md b/crates/subscriptions/README.md index ad46db687a..28d2a57de1 100644 --- a/crates/subscriptions/README.md +++ b/crates/subscriptions/README.md @@ -161,6 +161,7 @@ Comparators supported: `eq` (default), `in`. Native `filterBy.comparator` values | `HFS_SUBSCRIPTION_WS_MAX_UNBOUND_CONNECTIONS` | `256` | WebSocket connections that may be waiting to send their bind message at once; an upgrade past the limit is refused with `503` and `Retry-After` | | `HFS_SUBSCRIPTION_WS_BIND_TIMEOUT_MS` | `10000` | How long a WebSocket connection may take to send its bind message (`1008 bind-timeout` past it) | | `HFS_SUBSCRIPTION_WS_SEND_TIMEOUT_MS` | `30000` | How long a bound WebSocket client may take to accept one frame, whatever its size (`1008 client-too-slow` past it); raise it for large `full-resource` notifications over slow links | +| `HFS_SUBSCRIPTION_WS_DELIVERY_TIMEOUT_MS` | `120000` | How long after it was queued a notification may still be undelivered to a bound WebSocket client (`1008 client-too-slow` past it), however few are waiting; also bounds the send of one frame, so keep it above the send timeout | | `HFS_SUBSCRIPTION_WS_CLIENT_QUEUE_CAPACITY` | `256` | Notifications a bound WebSocket client may have waiting; a client whose queue overflows is closed (`1008 client-too-slow`) | | `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` | `100` | Events remembered per subscription for `$events` (number, timestamp, focus reference only; in memory, lost on restart); `0` disables the history | | `max_retries` *(config field)* | `10` | Delivery attempts per notification; `0` disables retries | @@ -420,7 +421,7 @@ After a successful bind message, the server sends a handshake notification bundl The WebSocket protocol is **unidirectional** (server → client) after binding. Additional bind messages on the same connection are rejected; close frames trigger graceful cleanup. -**Deadlines and queueing:** a connection that sends no bind message within 10 seconds is closed (`1008 bind-timeout`). Each bound client has a queue of 256 notifications; a client that stops reading its socket is given 30 seconds to accept a frame and is dropped once its queue is full, so a stalled client retains no further notifications in the server. Both cases close the connection with `1008 client-too-slow` and discard the notifications still queued. The server waits at most 5 seconds for a close frame to be accepted; a client that still is not reading sees the connection drop without one. The two deadlines and the queue size are configurable (`HFS_SUBSCRIPTION_WS_*`, see [Configuration](#configuration)). +**Deadlines and queueing:** a connection that sends no bind message within 10 seconds is closed (`1008 bind-timeout`). Each bound client has a queue of 256 notifications; a client that stops reading its socket is given 30 seconds to accept a frame and is dropped once its queue is full, so a stalled client retains no further notifications in the server. A client that reads slowly without filling its queue is bounded by time: a notification not delivered within 2 minutes of being queued ends the connection. All three cases close the connection with `1008 client-too-slow` and discard the notifications still queued. The server waits at most 5 seconds for a close frame to be accepted; a client that still is not reading sees the connection drop without one. The three deadlines and the queue size are configurable (`HFS_SUBSCRIPTION_WS_*`, see [Configuration](#configuration)). **Catching up after a drop:** the client reconnects with a new binding token and reads the events it missed from `$events`. That is not a full replay: `$events` returns id-only references whatever the subscription's `content`, and only the latest `HFS_SUBSCRIPTION_EVENT_HISTORY_SIZE` events (100 by default, fewer than the 256 notifications a full queue discards), kept in memory. A client that missed more than that, or that was away across a server restart, reads the resources it follows again. @@ -562,5 +563,5 @@ A Kafka-backed architecture addresses most of the single-instance and performanc - Batch and transaction bundle entries do not emit subscription events — only direct CRUD handlers (create, update, delete, patch) do - [`eventTrigger`](https://hl7.org/fhir/subscriptiontopic.html) is not supported — only `resourceTrigger` (create, update, delete) is implemented - The engine is in-memory only and single-instance — subscriptions and topics are not shared across cluster nodes or reloaded from storage on restart (see [Clustering](#clustering) above) -- WebSocket notifications are best-effort — if no clients are connected when an event fires the notification is silently dropped; there is no replay or queueing for late-connecting clients, and a connected client that stops reading is dropped once its queue (256 notifications by default) is full +- WebSocket notifications are best-effort — if no clients are connected when an event fires the notification is silently dropped; there is no replay or queueing for late-connecting clients, and a connected client that stops reading is dropped once its queue (256 notifications by default) is full or a notification has been undelivered for 2 minutes (by default) - Email and FHIR messaging channels are not yet implemented (planned for subsequent phases) diff --git a/crates/subscriptions/src/channels/ws_manager.rs b/crates/subscriptions/src/channels/ws_manager.rs index ed99ceac40..92e6b79a38 100644 --- a/crates/subscriptions/src/channels/ws_manager.rs +++ b/crates/subscriptions/src/channels/ws_manager.rs @@ -12,6 +12,10 @@ //! reconnects and reads what it missed from `$events`, which lists only the //! most recent events, by reference. //! +//! A client that keeps its queue below that limit can still be far behind, so +//! each queued notification carries the time it was queued and the connection +//! handler closes a client that does not take one in time. +//! //! A notification is serialized once per broadcast and every client's queue //! holds a reference-counted handle to the same bytes, so the memory a //! broadcast retains does not grow with the number of clients. A @@ -25,6 +29,7 @@ use chrono::{DateTime, Utc}; use dashmap::DashMap; use tokio::sync::mpsc; use tokio::sync::mpsc::error::{TryRecvError, TrySendError}; +use tokio::time::Instant; use tracing::{debug, warn}; use uuid::Uuid; @@ -40,12 +45,21 @@ pub const MAX_CLIENTS_PER_SUBSCRIPTION: usize = 16; /// bytes. pub type WsPayload = Bytes; +/// A notification in a client's queue. +#[derive(Debug, Clone)] +pub struct QueuedNotification { + /// The serialized notification bundle. + pub payload: WsPayload, + /// When the notification was queued for the client. + pub queued_at: Instant, +} + /// Sender half given to a connected WebSocket client. -pub type WsClientSender = mpsc::Sender; +pub type WsClientSender = mpsc::Sender; /// Receiving half of a bound client's notification queue. pub struct WsClientReceiver { - queue: mpsc::Receiver, + queue: mpsc::Receiver, too_slow: Arc, } @@ -53,12 +67,18 @@ impl WsClientReceiver { /// The next queued notification, or `None` once the queue is empty and the /// manager has released the client. Cancel safe. pub async fn recv(&mut self) -> Option { + Some(self.recv_queued().await?.payload) + } + + /// Like [`recv`](Self::recv), with the time the notification was queued. + /// Cancel safe. + pub async fn recv_queued(&mut self) -> Option { self.queue.recv().await } /// The next notification if one is already queued. pub fn try_recv(&mut self) -> Result { - self.queue.try_recv() + Ok(self.queue.try_recv()?.payload) } /// Whether the manager has released the client. Notifications queued @@ -234,8 +254,11 @@ impl WebSocketManager { let Some(mut entry) = self.clients.get_mut(&key) else { return 0; }; - let payload = match serde_json::to_vec(notification) { - Ok(json) => Bytes::from(json), + let notification = match serde_json::to_vec(notification) { + Ok(json) => QueuedNotification { + payload: Bytes::from(json), + queued_at: Instant::now(), + }, Err(e) => { warn!( tenant_id, @@ -264,7 +287,7 @@ impl WebSocketManager { ); return false; } - match client.sender.try_send(payload.clone()) { + match client.sender.try_send(notification.clone()) { Ok(()) => { delivered += 1; true @@ -480,6 +503,26 @@ mod tests { assert!(rx.was_too_slow()); } + /// A queued notification keeps the time it was queued, however long the + /// client leaves it in the queue. + #[tokio::test(start_paused = true)] + async fn a_queued_notification_carries_the_time_it_was_queued() { + let mgr = WebSocketManager::new(); + let (_id, mut rx) = mgr.register_client("t1", "sub-1").unwrap(); + + let n = json!({"type": "event-notification"}); + mgr.send_to_subscription("t1", "sub-1", &n); + tokio::time::advance(std::time::Duration::from_secs(5)).await; + mgr.send_to_subscription("t1", "sub-1", &n); + tokio::time::advance(std::time::Duration::from_secs(2)).await; + + let first = rx.recv_queued().await.unwrap(); + assert_eq!(first.queued_at.elapsed().as_secs(), 7); + assert_eq!(json(first.payload), n); + let second = rx.recv_queued().await.unwrap(); + assert_eq!(second.queued_at.elapsed().as_secs(), 2); + } + /// A client that stopped reading keeps its queued notifications until the /// queue is full, then is dropped: nothing more is retained for it, and /// the handler sees the channel end after the queued ones. diff --git a/crates/subscriptions/src/config.rs b/crates/subscriptions/src/config.rs index 75ab847f76..f6e9c88512 100644 --- a/crates/subscriptions/src/config.rs +++ b/crates/subscriptions/src/config.rs @@ -86,6 +86,12 @@ pub struct SubscriptionConfig { /// default. pub ws_send_timeout: Duration, + /// How long after it was queued a notification may still be undelivered to + /// a bound WebSocket client. A client past it is closed, however few + /// notifications it has waiting. It also bounds the send of one frame. + /// Zero is replaced by the default. + pub ws_delivery_timeout: Duration, + /// Notifications a bound WebSocket client may have waiting. A client whose /// queue is full when the next one arrives is closed. pub ws_client_queue_capacity: usize, @@ -186,6 +192,7 @@ impl Default for SubscriptionConfig { ws_max_unbound_connections: 256, ws_bind_timeout: Duration::from_secs(10), ws_send_timeout: Duration::from_secs(30), + ws_delivery_timeout: Duration::from_secs(120), ws_client_queue_capacity: crate::channels::ws_manager::CLIENT_QUEUE_CAPACITY, allow_private_endpoints: false, smtp: None, @@ -261,6 +268,11 @@ impl SubscriptionConfig { &mut self.ws_send_timeout, defaults.ws_send_timeout, ), + ( + "ws_delivery_timeout", + &mut self.ws_delivery_timeout, + defaults.ws_delivery_timeout, + ), ] { if timeout.is_zero() { tracing::warn!( @@ -424,20 +436,24 @@ mod tests { let config = SubscriptionConfig { ws_bind_timeout: Duration::ZERO, ws_send_timeout: Duration::ZERO, + ws_delivery_timeout: Duration::ZERO, ..SubscriptionConfig::default() } .normalize_dispatch_limits(); assert_eq!(config.ws_bind_timeout, default.ws_bind_timeout); assert_eq!(config.ws_send_timeout, default.ws_send_timeout); + assert_eq!(config.ws_delivery_timeout, default.ws_delivery_timeout); let config = SubscriptionConfig { ws_bind_timeout: Duration::from_millis(1), ws_send_timeout: Duration::from_secs(600), + ws_delivery_timeout: Duration::from_millis(2), ..SubscriptionConfig::default() } .normalize_dispatch_limits(); assert_eq!(config.ws_bind_timeout, Duration::from_millis(1)); assert_eq!(config.ws_send_timeout, Duration::from_secs(600)); + assert_eq!(config.ws_delivery_timeout, Duration::from_millis(2)); } #[test]