diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index c8b50a32..0fdc43b6 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -54,7 +54,7 @@ use crate::{ }, consts::{ DEFAULT_EVENT_QUEUE_CAPACITY, DEFAULT_RUNTIME_HEALTH_CHECK_ENDPOINT, - DISPATCHER_COMMAND_BUFFER, + DISPATCHER_COMMAND_BUFFER, WS_CONNECTION_DEFAULT_HANDLER_CONCURRENCY, }, consumer_handler::{ ConsumerEventHandler, EventQueueConsumerEventHandler, SharedConsumerEventHandler, @@ -444,6 +444,10 @@ impl Application { .map(|_| websocket_config.auth_strategy.clone()), connection_auth_guard_names: websocket_config.connection_auth_guard.clone(), connection_auth_guards: self.custom_auth_guards.clone(), + handler_concurrency: self + .runtime_config + .ws_handler_concurrency + .unwrap_or(WS_CONNECTION_DEFAULT_HANDLER_CONCURRENCY), cors: api_config.cors.clone(), resource_store: resource_store.clone(), }), diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index df5b387a..9e3809f3 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -194,6 +194,14 @@ pub struct RuntimeConfig { /// for the suggested default the WebSocket runtime protocol names, which is 3. /// Set via `CELERITY_WS_ACK_MAX_ATTEMPTS`. pub ws_ack_max_attempts: Option, + /// How many of one connection's messages may be handled at the same time. + /// + /// Leave unset for eight. Set it to one for a connection whose messages have + /// to be handled in the order they arrived, at the cost of capping the + /// connection at one handler's worth of latency per message. Bounds one + /// connection rather than the process. + /// Set via `CELERITY_WS_HANDLER_CONCURRENCY`. + pub ws_handler_concurrency: Option, } impl RuntimeConfig { @@ -363,6 +371,7 @@ impl RuntimeConfig { let ws_ack_timeout_ms = ws_ack_timeout_ms_from_env(env); let ws_ack_max_attempts = ws_ack_max_attempts_from_env(env); + let ws_handler_concurrency = ws_handler_concurrency_from_env(env); RuntimeConfig { blueprint_config_path, @@ -393,6 +402,7 @@ impl RuntimeConfig { deploy_target, ws_ack_timeout_ms, ws_ack_max_attempts, + ws_handler_concurrency, } } @@ -450,6 +460,24 @@ pub fn ws_ack_max_attempts_from_env(env: &impl EnvVars) -> Option { }) } +/// Reads how many of a connection's messages may be handled at the same time. +/// +/// See [`ws_ack_timeout_ms_from_env`] for why this is not only read in +/// [`RuntimeConfig::from_env`]. +pub fn ws_handler_concurrency_from_env(env: &impl EnvVars) -> Option { + env.var("CELERITY_WS_HANDLER_CONCURRENCY").ok().map(|val| { + let concurrency: usize = val + .parse() + .expect("Invalid WebSocket handler concurrency, must be a whole number"); + assert!( + concurrency > 0, + "Invalid WebSocket handler concurrency, a connection has to handle at least one \ + message at a time" + ); + concurrency + }) +} + #[derive(Debug)] pub struct AppConfig { pub api: Option, @@ -857,4 +885,27 @@ mod tests { fn test_an_ack_timeout_that_is_not_a_number_is_refused() { RuntimeConfig::from_env(&env(&[("CELERITY_WS_ACK_TIMEOUT_MS", "ten seconds")])); } + + #[test] + fn test_handler_concurrency_is_left_to_the_runtime_when_unset() { + assert_eq!( + RuntimeConfig::from_env(&env(&[])).ws_handler_concurrency, + None + ); + } + + #[test] + fn test_handler_concurrency_is_read_from_the_environment() { + let config = RuntimeConfig::from_env(&env(&[("CELERITY_WS_HANDLER_CONCURRENCY", "8")])); + + assert_eq!(config.ws_handler_concurrency, Some(8)); + } + + /// Nothing at all would leave a connection unable to handle anything, + /// rather than meaning handle nothing in parallel. + #[test] + #[should_panic(expected = "one message at a time")] + fn test_no_handler_concurrency_at_all_is_refused() { + RuntimeConfig::from_env(&env(&[("CELERITY_WS_HANDLER_CONCURRENCY", "0")])); + } } diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index e130bb82..d8c58750 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -127,6 +127,21 @@ pub const WS_CONNECTION_WORK_SHED_GRACE_MS: u64 = 1_000; // enough for work that is nearly done to land. pub const WS_CONNECTION_DRAIN_GRACE_MS: u64 = 5_000; +// How many of one connection's messages may be handled at the same time. +// +// More than one, because the same API deploys here or to a serverless gateway, +// which runs a function per message with nothing between them. Handling one at +// a time would make this the only target that puts a connection's messages in a +// queue, and an application built against that would carry an ordering +// dependency it cannot see until it is deployed somewhere that does not honour +// it. A deployment that needs them in order asks for one. +// +// Bounds one connection rather than the process. What bounds the process is the +// credit a handler grants its stream, and what stops a connection's messages +// taking all of that is the default per tag limit, which keeps a place for the +// tags nothing else can stand in for, the disconnect handler among them. +pub const WS_CONNECTION_DEFAULT_HANDLER_CONCURRENCY: usize = 8; + // The `retryAfter` hint sent in the close frame when a connection is shed for // outrunning its handlers. // @@ -136,6 +151,35 @@ pub const WS_CONNECTION_DRAIN_GRACE_MS: u64 = 5_000; // their own jitter. pub const WS_CONNECTION_SATURATED_RETRY_AFTER_MS: u64 = 5_000; +// How long a cancelled event is left with its handler before the runtime takes +// back what it was holding. +// +// Credit and a per tag place are consumed when an event is dispatched and +// returned when the handler answers, including when it answers late. A handler +// that never answers would otherwise hold both for the life of the process, so +// a stream would lose a place every time one hung and would eventually stop +// dispatching altogether. +// +// Taking them back is not a statement that the handler stopped, since nothing +// can make it stop. It says the runtime will no longer keep room for an answer +// it asked to be abandoned. Long enough for a handler that honours a +// cancellation to unwind and answer, which is the case that should not be +// treated as a hang. +pub const HANDLER_CANCEL_RECLAIM_GRACE_SECS: u64 = 5; + +// How long the runtime remembers an event whose place it took back. +// +// A result carrying no credit is a handler withholding, asking for nothing +// further until it grants again. Arriving after the place was taken back, that +// asks for a place the runtime has already returned, so the return has to be +// undone or the handler is sent work it said it could not take. Remembering +// which events those were is what makes that possible. +// +// Bounded because a handler that never answers would otherwise be remembered +// for good, and generous because the answer being late is the whole reason +// there is anything to remember. +pub const HANDLER_RECLAIM_MEMORY_SECS: u64 = 60; + // How many dispatcher commands may be queued before a handler stream waits. // Commands are small and are drained by a single task, so this only needs to // absorb bursts of results arriving together. diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs index 03af5bce..b0e706ec 100644 --- a/libs/runtime/core/src/dispatcher.rs +++ b/libs/runtime/core/src/dispatcher.rs @@ -34,7 +34,10 @@ use tokio::{ use tracing::{debug, info, warn}; use crate::{ - consts::{HANDLER_ATTACH_GRACE_SECS, MAX_DERIVED_DRAIN_TIMEOUT_SECS}, + consts::{ + HANDLER_ATTACH_GRACE_SECS, HANDLER_CANCEL_RECLAIM_GRACE_SECS, HANDLER_RECLAIM_MEMORY_SECS, + MAX_DERIVED_DRAIN_TIMEOUT_SECS, + }, event_queue::{EventQueueReceivers, HandlerTimeouts, InFlightEntry, InFlightTable}, types::{CancelReason, CancelRequest, EventData, EventOutcome, EventTuple, UnservableReason}, }; @@ -82,8 +85,9 @@ pub struct StreamRegistration { pub handler_tags: Vec, /// How many events may be in flight to this stream at once. pub initial_credit: u32, - /// Optional per-tag concurrency caps. A tag with no entry is bounded only - /// by the credit window. + /// Optional per-tag concurrency caps. A tag with no entry is bounded by the + /// credit window and by a default cap, which keeps a place for the other + /// tags so that no one of them can take the window entirely. pub limits: HashMap, /// Where dispatched events and the frames concerning them are sent. pub dispatch_tx: mpsc::Sender, @@ -155,10 +159,39 @@ impl StreamState { if self.draining || self.credit == 0 || !self.tags.contains(handler_tag) { return false; } - match self.limits.get(handler_tag) { - Some(cap) => self.in_flight.get(handler_tag).copied().unwrap_or(0) < *cap, - None => true, + if let Some(cap) = self.limits.get(handler_tag) { + if self.in_flight.get(handler_tag).copied().unwrap_or(0) >= *cap { + return false; + } } + self.credit.saturating_sub(1) >= self.reserved_for_other_tags(handler_tag) + } + + /// How many places have to be left for the tags holding nothing. + /// + /// Counted against the tags holding nothing rather than against all of + /// them, so it shrinks as they are served and the last tag to arrive is not + /// asked to leave room for tags already busy. A fixed share cannot manage + /// that. Give three tags a window of four and two places each, and the + /// first two take everything between them. + /// + /// Never more than half the window, since a stream serving many tags on a + /// small one cannot keep a place for each of them, and holding the window + /// half empty for tags that may send nothing would cost whichever tag + /// carries the traffic more than the starvation it avoids. + fn reserved_for_other_tags(&self, handler_tag: &str) -> u32 { + let idle = self + .tags + .iter() + .filter(|tag| tag.as_str() != handler_tag) + .filter(|tag| self.in_flight.get(*tag).copied().unwrap_or(0) == 0) + .count() as u32; + // Taken as it stands rather than as it was declared, since a grant may + // have resized the window since the stream attached. Saturating because + // credit does, and a grant arriving while events are held can carry the + // sum past a u32. + let window = self.credit.saturating_add(self.holding.len() as u32); + idle.min(window / 2) } } @@ -180,6 +213,25 @@ pub struct Dispatcher { /// Publishes whether any stream is attached, for readiness probes and for /// the startup deadline a supervising runtime applies. readiness: watch::Sender, + /// Events that have been cancelled and the moment the runtime stops keeping + /// room for an answer to them. + /// + /// Every entry is given the same grace period, so they are added in the order they + /// fall due and the earliest is always the front. + reclaims: VecDeque<(Instant, String)>, + /// How long a cancelled event is left with its handler before what it holds + /// is taken back. + reclaim_grace: Duration, + /// Events whose place has been taken back, kept so that a handler answering + /// late can still withhold the place rather than be sent more work. + /// + /// Ordered by when they stop being remembered, which is the same span for + /// each, so the earliest is always the front. + reclaimed: VecDeque<(Instant, String)>, + /// The same events, for looking one up when a late answer names it. + reclaimed_ids: HashSet, + /// How long a taken back event is remembered. Shortened by tests. + reclaim_memory: Duration, } /// Whether a handlers executable is attached and able to be given work. @@ -279,6 +331,11 @@ impl Dispatcher { timeouts, drain_timeout, readiness: watch::Sender::new(false), + reclaims: VecDeque::new(), + reclaim_grace: Duration::from_secs(HANDLER_CANCEL_RECLAIM_GRACE_SECS), + reclaimed: VecDeque::new(), + reclaimed_ids: HashSet::new(), + reclaim_memory: Duration::from_secs(HANDLER_RECLAIM_MEMORY_SECS), } } @@ -321,10 +378,20 @@ impl Dispatcher { // Recomputed each pass because attaching a stream can make a queue // servable again, and dispatching can empty one. let shed_at = self.next_shed_deadline(); + let reclaim_at = match (self.reclaims.front(), self.reclaimed.front()) { + (Some((due, _)), Some((forget, _))) => Some(*due.min(forget)), + (Some((due, _)), None) => Some(*due), + (None, Some((forget, _))) => Some(*forget), + (None, None) => None, + }; tokio::select! { _ = &mut shutdown_rx => break, _ = sleep_until_or_never(shed_at) => self.shed_unservable(), + _ = sleep_until_or_never(reclaim_at) => { + self.reclaim_abandoned(); + self.dispatch_ready().await; + } taken = events.recv() => match taken { Some((result_tx, event)) => { self.enqueue(QueuedEvent { @@ -376,6 +443,13 @@ impl Dispatcher { return; }; + // Whatever the handler does with the cancellation, the runtime stops + // keeping room for an answer to it once the grace period passes. A handler + // that honours it and answers releases what it holds the ordinary way, + // well within the grace period. + self.reclaims + .push_back((Instant::now() + self.reclaim_grace, event_id.clone())); + // A caller that went away leaves an entry nobody will ever read, so it // is released here rather than being held until its deadline, which // would also produce a second cancellation for the same event. A @@ -397,6 +471,61 @@ impl Dispatcher { } } + /// Takes back what cancelled events are still holding, once the grace period for + /// answering has passed. + /// + /// An event the handler answered in time is already gone from `holders`, so + /// what is left here is what nothing came back for. Doing this is what + /// keeps a handler that ignores cancellation from shrinking its stream's + /// window one event at a time until it dispatches nothing at all. + fn reclaim_abandoned(&mut self) { + let now = Instant::now(); + while self + .reclaims + .front() + .is_some_and(|(due_at, _)| *due_at <= now) + { + let Some((_, event_id)) = self.reclaims.pop_front() else { + break; + }; + let Some(stream_id) = self.holders.remove(&event_id) else { + continue; + }; + let Some(stream) = self.streams.get_mut(&stream_id) else { + continue; + }; + let Some(handler_tag) = stream.holding.remove(&event_id) else { + continue; + }; + if let Some(count) = stream.in_flight.get_mut(&handler_tag) { + *count = count.saturating_sub(1); + } + stream.credit = stream.credit.saturating_add(1); + warn!( + stream_id, + %event_id, + %handler_tag, + "no answer to a cancelled event within the grace, taking back the place \ + it was holding" + ); + // Remembered so that an answer arriving later can still withhold + // the place, which is the handler saying it cannot take more. + self.reclaimed + .push_back((now + self.reclaim_memory, event_id.clone())); + self.reclaimed_ids.insert(event_id); + } + + while self + .reclaimed + .front() + .is_some_and(|(forget_at, _)| *forget_at <= now) + { + if let Some((_, event_id)) = self.reclaimed.pop_front() { + self.reclaimed_ids.remove(&event_id); + } + } + } + /// Stops dispatching, tells attached streams to finish, and waits for what /// is already in flight. /// @@ -526,13 +655,26 @@ impl Dispatcher { credit_grant, } => { self.holders.remove(&event_id); + let taken_back = self.reclaimed_ids.remove(&event_id); if let Some(stream) = self.streams.get_mut(&stream_id) { if let Some(handler_tag) = stream.holding.remove(&event_id) { if let Some(count) = stream.in_flight.get_mut(&handler_tag) { *count = count.saturating_sub(1); } + stream.credit = stream.credit.saturating_add(credit_grant); + } else if taken_back && credit_grant == 0 { + // The place is already back, so a grant would grow the + // window past what the handler declared and is dropped. + // No grant is a handler withholding though, and it means + // the same whenever it arrives, so the place goes back + // to the handler's account rather than the runtime's. + stream.credit = stream.credit.saturating_sub(1); + debug!( + stream_id, + %event_id, + "a late answer withheld the place that was taken back" + ); } - stream.credit = stream.credit.saturating_add(credit_grant); } } DispatcherCommand::Grant { @@ -879,7 +1021,10 @@ mod tests { let (command_tx, command_rx) = mpsc::channel(16); let (shutdown_tx, shutdown_rx) = oneshot::channel(); - let dispatcher = Dispatcher::new(handles.in_flight.clone(), timeouts(), drain_timeout); + let mut dispatcher = Dispatcher::new(handles.in_flight.clone(), timeouts(), drain_timeout); + // The real grace is measured in seconds, which no test can wait out. + dispatcher.reclaim_grace = Duration::from_millis(100); + dispatcher.reclaim_memory = Duration::from_secs(30); let readiness = dispatcher.readiness(); tokio::spawn(dispatcher.run(receivers, command_rx, shutdown_rx)); @@ -1586,4 +1731,314 @@ mod tests { assert!(!attached); } + + /// Three tags on a window of four, which a fixed share of two apiece cannot + /// serve: the first two take everything between them and the third is not + /// slow, it is stopped. + #[tokio::test] + async fn a_window_too_small_to_share_evenly_still_reaches_every_tag() { + let harness = start(64); + let mut stream = attach(&harness, 1, &["a", "b", "c"], 4, HashMap::new()).await; + + for tag in ["a", "b"] { + for index in 0..4 { + harness + .queue + .enqueue( + event(&format!("{tag}-{index}"), tag), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + } + let mut taken = Vec::new(); + while let Some(dispatched) = recv_dispatch(&mut stream).await { + taken.push(dispatched.event.id); + } + + harness + .queue + .enqueue(event("c-0", "c"), admission_wait(Duration::from_secs(60))) + .await + .unwrap(); + let third = recv_dispatch(&mut stream).await; + assert_eq!( + third.map(|dispatched| dispatched.event.id), + Some("c-0".to_string()), + "the third tag was left nothing, the other two took {taken:?}" + ); + } + + /// Nothing to leave room for, so the whole window is available. + #[tokio::test] + async fn a_stream_serving_one_tag_gives_it_the_whole_window() { + let harness = start(64); + let mut stream = attach(&harness, 1, &["only"], 4, HashMap::new()).await; + + for index in 0..6 { + harness + .queue + .enqueue( + event(&format!("only-{index}"), "only"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + let mut taken = 0; + while recv_dispatch(&mut stream).await.is_some() { + taken += 1; + } + assert_eq!(taken, 4, "one tag alone should be able to fill the window"); + } + + /// A tag the handler declared no limit for still cannot take the window. + /// + /// The reclaim would eventually free the places a stalled tag holds, so + /// this is what keeps the other tags dispatching in the meantime rather + /// than waiting out a grace before they can be served at all. + #[tokio::test] + async fn a_tag_with_no_declared_limit_still_leaves_room_for_the_others() { + let harness = start(64); + let mut stream = attach(&harness, 1, &["hot", "cold"], 4, HashMap::new()).await; + + // More of the hot tag than the window holds, and none of them answered. + for index in 0..8 { + harness + .queue + .enqueue( + event(&format!("hot-{index}"), "hot"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + let mut hot = 0; + while let Some(dispatched) = recv_dispatch(&mut stream).await { + assert!(dispatched.event.id.starts_with("hot-")); + hot += 1; + } + assert!( + hot < 4, + "the hot tag took {hot} of a window of 4, leaving nothing for the other tag" + ); + + // The cold tag has never been served and nothing has answered, so the + // only reason it can be dispatched is the place held back for it. + harness + .queue + .enqueue( + event("cold-0", "cold"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + let cold = recv_dispatch(&mut stream) + .await + .expect("a tag that has taken nothing should still have a place"); + assert_eq!(cold.event.id, "cold-0"); + } + + /// A handler that never answers a cancellation does not keep what it was + /// holding. + /// + /// Credit and a per tag place come back when a handler answers, so a + /// handler that ignores a cancellation would otherwise leave a stream one + /// place smaller for good, and enough of them would stop it dispatching + /// anything at all. + #[tokio::test] + async fn takes_back_what_a_cancelled_event_was_holding_when_nothing_answers() { + let harness = start(32); + // One place, so what happens to it is the whole of what this observes. + let mut stream = attach(&harness, 1, &["work"], 1, HashMap::new()).await; + + harness + .queue + .enqueue( + event("event-1", "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + let dispatched = recv_dispatch(&mut stream) + .await + .expect("the first event should be dispatched"); + assert_eq!(dispatched.event.id, "event-1"); + + harness + .queue + .enqueue( + event("event-2", "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!( + recv_dispatch(&mut stream).await.is_none(), + "the window is held by the first event, so the second should wait" + ); + + // The caller has gone. The handler is told to stop and never answers, + // which is what a hung or crashed handler looks like from here. + drop(harness.queue.cancel_on_drop("event-1".to_string())); + match recv(&mut stream).await { + Some(StreamFrame::Cancel { event_id, .. }) => assert_eq!(event_id, "event-1"), + other => panic!("expected a cancellation, got {other:?}"), + } + + tokio::time::sleep(Duration::from_millis(250)).await; + + let second = recv_dispatch(&mut stream) + .await + .expect("the place the cancelled event held should have come back"); + assert_eq!(second.event.id, "event-2"); + } + + /// An answer that arrives after the runtime gave up waiting does not put a + /// place back that has already been taken back. + /// + /// The handler declares its own limits here, generously, so that credit is + /// the only thing bounding what can be in flight. Without that the per tag + /// limit hides an inflated window rather than the test finding it. + #[tokio::test] + async fn does_not_credit_an_answer_that_comes_after_the_place_was_taken_back() { + let harness = start(32); + let mut stream = attach( + &harness, + 1, + &["work"], + 2, + HashMap::from([("work".to_string(), 10)]), + ) + .await; + + for index in 0..2 { + harness + .queue + .enqueue( + event(&format!("held-{index}"), "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + for _ in 0..2 { + recv_dispatch(&mut stream) + .await + .expect("both events should be dispatched, which is the whole window"); + } + + drop(harness.queue.cancel_on_drop("held-0".to_string())); + match recv(&mut stream).await { + Some(StreamFrame::Cancel { .. }) => {} + other => panic!("expected a cancellation, got {other:?}"), + } + tokio::time::sleep(Duration::from_millis(250)).await; + + // The handler answers late, returning the credit it believes it still + // holds. That place is already back, so this must add nothing. + harness + .commands + .send(DispatcherCommand::Completed { + stream_id: 1, + event_id: "held-0".to_string(), + credit_grant: 1, + }) + .await + .unwrap(); + + for index in 0..2 { + harness + .queue + .enqueue( + event(&format!("later-{index}"), "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + + assert!( + recv_dispatch(&mut stream).await.is_some(), + "the place the cancelled event held should have come back" + ); + assert!( + recv_dispatch(&mut stream).await.is_none(), + "a late answer should not grow the window past what the handler declared" + ); + } + + /// A handler answering late with no credit is still withholding, and the + /// place the runtime took back on its behalf goes back to it. + /// + /// No credit on a result means stop dispatching until a later grant. The + /// runtime returned that place when nothing answered in time, so honouring + /// the withhold means undoing its own return rather than ignoring what the + /// handler asked for and sending it work it said it could not take. + #[tokio::test] + async fn honours_a_withhold_that_arrives_after_the_place_was_taken_back() { + let harness = start(32); + let mut stream = attach( + &harness, + 1, + &["work"], + 2, + HashMap::from([("work".to_string(), 10)]), + ) + .await; + + for index in 0..2 { + harness + .queue + .enqueue( + event(&format!("held-{index}"), "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + for _ in 0..2 { + recv_dispatch(&mut stream) + .await + .expect("both events should be dispatched, which is the whole window"); + } + + drop(harness.queue.cancel_on_drop("held-0".to_string())); + match recv(&mut stream).await { + Some(StreamFrame::Cancel { .. }) => {} + other => panic!("expected a cancellation, got {other:?}"), + } + tokio::time::sleep(Duration::from_millis(250)).await; + + // Late, and withholding. The place the runtime returned is the one the + // handler is saying it does not want. + harness + .commands + .send(DispatcherCommand::Completed { + stream_id: 1, + event_id: "held-0".to_string(), + credit_grant: 0, + }) + .await + .unwrap(); + // Waited for rather than raced. A withhold governs what is dispatched + // after it is read, and work already waiting when the place came back + // may have gone out before it arrived, which is what being late costs. + tokio::time::sleep(Duration::from_millis(100)).await; + + harness + .queue + .enqueue( + event("later-0", "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + assert!( + recv_dispatch(&mut stream).await.is_none(), + "a handler that withheld should not be sent more work, however late it said so" + ); + } } diff --git a/libs/runtime/core/src/generated/celerity.runtime.v1.rs b/libs/runtime/core/src/generated/celerity.runtime.v1.rs index 9c720863..332c51dd 100644 --- a/libs/runtime/core/src/generated/celerity.runtime.v1.rs +++ b/libs/runtime/core/src/generated/celerity.runtime.v1.rs @@ -157,6 +157,14 @@ pub mod dispatch { /// /// May arrive for an event that has already completed, which handlers must /// ignore rather than treat as an error. +/// +/// A cancelled event should still be answered with a Result, which is what +/// returns the place it holds in the credit window. The runtime waits a short +/// grace period and then takes that place back itself, since a handler that has hung or +/// died would otherwise shrink the window for the life of the process. That is +/// not a claim that the handler stopped, only that the runtime will no longer keep +/// room for an answer it asked to be abandoned, a handler that answers +/// promptly never meets it. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct Cancel { #[prost(string, tag = "1")] @@ -357,6 +365,11 @@ pub struct Result { /// to stop dispatching to this stream until a later CreditGrant. SDKs should /// default to 1 and must send this even when the handler panics, since a /// missed grant drains the window and stalls the stream silently. + /// + /// When the runtime has already taken the place back, having cancelled the + /// event and waited out the grace period, a grant here is ignored, since + /// returning the same place twice would grow the window. Zero still withholds, + /// and the runtime gives up the place it returned. #[prost(uint32, tag = "2")] pub credit_grant: u32, #[prost(oneof = "result::Outcome", tags = "10, 11, 12, 13, 14, 15")] diff --git a/libs/runtime/core/src/transform_config.rs b/libs/runtime/core/src/transform_config.rs index 2b2850a4..ed791bf3 100644 --- a/libs/runtime/core/src/transform_config.rs +++ b/libs/runtime/core/src/transform_config.rs @@ -1496,6 +1496,7 @@ mod tests { deploy_target: None, ws_ack_timeout_ms: None, ws_ack_max_attempts: None, + ws_handler_concurrency: None, } } diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 175fc03b..6d60a545 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -36,7 +36,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use tokio::{ sync::{mpsc, mpsc::error::SendTimeoutError, Mutex}, - task::JoinHandle, + task::{JoinHandle, JoinSet}, }; use tracing::{debug, error, field, info, info_span, warn, Instrument}; @@ -78,6 +78,8 @@ pub(crate) struct WebSocketAppState { pub connection_auth_guard_names: Option>, pub connection_auth_guards: Arc>>>, + // How many of this connection's messages may be handled at the same time. + pub handler_concurrency: usize, pub cors: Option, pub resource_store: Arc, // What the node has already seen from its clients, so a message resent @@ -367,14 +369,11 @@ async fn handle_socket( return; } - // Messages are processed off this loop, one at a time, by a worker for - // this connection. One at a time because that is how they were handled - // before, inline in this loop, and a fix for the loop stalling should - // not quietly start running an application's messages in parallel. - // Ordering is not something the platform promises, a serverless target - // runs a function per message with nothing between them, so this is - // about leaving behaviour alone rather than a guarantee being made. - // The point here is only that reading no longer waits for handling. + // Messages are processed off this loop by a worker for this + // connection, several at a time unless the deployment asks for one. The + // protocol promises nothing about ordering and a serverless target runs + // a function per message with nothing between them, so handling them in + // order here would be a guarantee only this target could keep. // // Bounded, so a client that outruns its handlers is pushed back on // rather than growing a queue without limit. Once the buffer is full @@ -388,6 +387,7 @@ async fn handle_socket( socket_ref.clone(), connection_id.clone(), state.clone(), + state.handler_concurrency, ); let mut connection_alive = true; @@ -725,26 +725,65 @@ fn create_connect_message( } } -/// Runs a connection's messages, one at a time, off its read loop. +/// Runs a connection's messages off its read loop, up to `concurrency` of them +/// at a time. +/// +/// A close is settled here rather than alongside the messages it follows, so +/// the connection ends after them however many were in flight. fn spawn_message_worker( mut work_rx: mpsc::Receiver<(Message, Option, WebSocketRequestContext)>, socket_ref: Arc>, connection_id: String, state: WebSocketAppState, + concurrency: usize, ) -> JoinHandle<()> { tokio::spawn(async move { + let mut in_flight = JoinSet::new(); + while let Some((message, parsed, request_ctx)) = work_rx.recv().await { - if process_message(message, parsed, connection_id.clone(), request_ctx, &state) - .await - .is_break() - { - // The connection is finished, and the read loop is waiting on a - // socket that may never produce anything again. Closing it is - // what wakes the loop so the connection can be torn down. - close_connection(socket_ref.clone()).await; - return; + // Only an application message is worth running beside another. A + // close ends the connection and the rest carry no handler, so they + // wait for what came before them and are settled here. At a + // concurrency of one nothing is ever in flight and this is the only + // path, which is what keeps the default exactly as it was. + let alongside_others = + concurrency > 1 && matches!(message, Message::Text(_) | Message::Binary(_)); + + if !alongside_others { + while in_flight.join_next().await.is_some() {} + if process_message(message, parsed, connection_id.clone(), request_ctx, &state) + .await + .is_break() + { + // The connection is finished, and the read loop is waiting on a + // socket that may never produce anything again. Closing it is + // what wakes the loop so the connection can be torn down. + close_connection(socket_ref.clone()).await; + return; + } + continue; + } + + // Waits for room rather than queueing behind it, so the buffer the + // read loop pushes back on stays the one thing bounding how far a + // client can run ahead. + while in_flight.len() >= concurrency { + in_flight.join_next().await; } + + let connection_id = connection_id.clone(); + let state = state.clone(); + in_flight.spawn(async move { + // Only a close asks for the connection to end, and a close is + // never spawned, so there is no outcome to read here. + let _ = process_message(message, parsed, connection_id, request_ctx, &state).await; + }); } + + // The read loop has finished with this connection. What is still + // running is left to finish, since teardown waits on this task and + // bounds that wait itself. + while in_flight.join_next().await.is_some() {} }) } diff --git a/libs/runtime/core/tests/common/ipc.rs b/libs/runtime/core/tests/common/ipc.rs index a68da4d9..ebae80c9 100644 --- a/libs/runtime/core/tests/common/ipc.rs +++ b/libs/runtime/core/tests/common/ipc.rs @@ -17,9 +17,15 @@ use celerity_runtime_core::{ }, }; use tokio::{net::UnixStream, sync::mpsc}; + use tokio_stream::StreamExt; use tonic::transport::{Endpoint, Uri}; +/// The credit the stub handler declares, which is how many events the runtime +/// may have in flight to it at once. Named because a test that fills the window +/// has to know what filling it means. +pub const HANDLER_INITIAL_CREDIT: u32 = 8; + pub fn ipc_env( service_name: &str, fixture: &str, @@ -143,7 +149,7 @@ impl HandlerStub { .iter() .map(|handler| handler.handler_tag.clone()) .collect(), - initial_credit: 8, + initial_credit: HANDLER_INITIAL_CREDIT, sdk_version: "test/0.1".to_string(), limits: vec![], })), diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 24054dd2..a1910631 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -17,7 +17,9 @@ use celerity_runtime_core::{ consts::CELERITY_WS_CAPABILITIES_SIGNAL, ipc_proto::{self as proto}, }; -use common::ipc::{ipc_env, socket_path, start_runtime, websocket_ack, HandlerStub}; +use common::ipc::{ + ipc_env, socket_path, start_runtime, websocket_ack, HandlerStub, HANDLER_INITIAL_CREDIT, +}; use futures::SinkExt; use serde_json::json; use tokio_stream::StreamExt; @@ -1284,6 +1286,185 @@ async fn settles_a_message_acknowledged_with_an_escaped_event_name() { let _ = tokio::fs::remove_file(&socket).await; } +/// A connection handles its messages beside each other unless it is asked for +/// one at a time. +/// +/// The handler is left holding the first message, never answering it, so the +/// second can only reach it if something is running the two side by side. +/// Paired with the test below, which is the same run asking for order, so what +/// each proves is read against the other. +#[test_log::test(tokio::test)] +async fn handles_messages_beside_each_other_by_default() { + let dispatched = dispatches_seen_while_the_first_is_held("ipc-ws-concurrent", &[]).await; + + assert_eq!( + dispatched, 2, + "a second message should not wait for a handler that is still going" + ); +} + +/// The order a serverless target cannot give, for an application that needs it +/// and accepts being capped at one handler's worth of latency per message. +#[test_log::test(tokio::test)] +async fn handles_one_message_at_a_time_when_asked_to() { + let dispatched = dispatches_seen_while_the_first_is_held( + "ipc-ws-serial", + &[("CELERITY_WS_HANDLER_CONCURRENCY", "1")], + ) + .await; + + assert_eq!( + dispatched, 1, + "a second message should wait for the first when order was asked for" + ); +} + +/// Sends two messages to a handler that never answers, and reports how many of +/// them reached it. +/// +/// The handler holding the first is what makes the count mean something. An +/// answer would free the worker and both would arrive whatever the concurrency. +/// +/// The two second wait below is short for the same reason. The first message +/// stops holding its place fifteen seconds in, ten for the handler timeout and +/// five more for the cancellation grace perios, and a second message arriving after +/// that would mean a place came free rather than two being handled at once. +async fn dispatches_seen_while_the_first_is_held( + name: &str, + overrides: &[(&'static str, &str)], +) -> usize { + let socket = socket_path(name); + let env_vars = ipc_env( + name, + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + &socket, + overrides, + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + // Never answered, so the runtime is still waiting on the first message when + // the second arrives. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + for text in ["first", "second"] { + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": text } }).to_string(), + )) + .await + .unwrap(); + } + + let mut dispatched = 0; + while tokio::time::timeout(Duration::from_secs(2), handler.next_dispatch()) + .await + .ok() + .flatten() + .is_some() + { + dispatched += 1; + } + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; + dispatched +} + +/// A connection can be left unable to finish tearing down by work other +/// connections are holding. +/// +/// Credit is one window per handler stream, refused to every tag once it runs +/// out, and it comes back only when a handler answers. Handlers that never +/// answer therefore take the window away permanently, and the disconnect +/// handler is dispatched through the same window as the messages that consumed +/// it. Each connection here holds a single message, which is all the current +/// default allows, so this is reachable without any concurrency being raised. +#[test_log::test(tokio::test)] +async fn tears_a_connection_down_while_other_connections_hold_the_credit() { + let socket = socket_path("ipc-ws-credit-starve"); + let env_vars = ipc_env( + "ipc-ws-credit-starve", + "tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml", + &socket, + &[], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + // Never answered, and a cancel is ignored the way a hung handler would. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + // As many connections as the stream has credit, each holding one message. + let mut connections = Vec::new(); + for _ in 0..HANDLER_INITIAL_CREDIT { + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hold" } }).to_string(), + )) + .await + .unwrap(); + connections.push(socket_conn); + } + + // Taken until they stop coming rather than counted, since how many reach + // the handler at once is the cap's business and not this test's. + let mut held = 0; + while tokio::time::timeout(Duration::from_secs(2), handler.next_dispatch()) + .await + .ok() + .flatten() + .is_some() + { + held += 1; + } + assert!( + held > 0, + "the connections should have reached the handler at all" + ); + + // Whatever reached the handler is now held by work that will never answer. + let mut closing = connections.pop().unwrap(); + let _ = closing.close(None).await; + + // The messages above fall due after a second and their places are taken + // back five seconds after that, so nothing the reclaim frees can arrive + // before six seconds in. This window closes well before then, which is what + // makes this the place held for the disconnect handler rather than a place + // that happened to come free. Teardown should not have to wait out a grace period. + let disconnected = tokio::time::timeout(Duration::from_secs(2), async { + while let Some(dispatch) = handler.next_dispatch().await { + if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { + if message.route == "$disconnect" { + return true; + } + } + } + false + }) + .await; + + assert_eq!( + disconnected, + Ok(true), + "a connection that has gone should still run its disconnect handler, or it stays \ + in the registry and counted for the life of the process" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + /// A guard that lets any non-empty token through, since what is under test is /// what the runtime says once a guard has passed rather than how it decides. #[derive(Debug)] diff --git a/libs/runtime/proto/celerity/runtime/v1/runtime.proto b/libs/runtime/proto/celerity/runtime/v1/runtime.proto index 02c3fd8f..99aab0d3 100644 --- a/libs/runtime/proto/celerity/runtime/v1/runtime.proto +++ b/libs/runtime/proto/celerity/runtime/v1/runtime.proto @@ -118,6 +118,14 @@ message Dispatch { // // May arrive for an event that has already completed, which handlers must // ignore rather than treat as an error. +// +// A cancelled event should still be answered with a Result, which is what +// returns the place it holds in the credit window. The runtime waits a short +// grace period and then takes that place back itself, since a handler that has hung or +// died would otherwise shrink the window for the life of the process. That is +// not a claim that the handler stopped, only that the runtime will no longer keep +// room for an answer it asked to be abandoned, a handler that answers +// promptly never meets it. message Cancel { string id = 1; @@ -242,6 +250,11 @@ message Result { // to stop dispatching to this stream until a later CreditGrant. SDKs should // default to 1 and must send this even when the handler panics, since a // missed grant drains the window and stalls the stream silently. + // + // When the runtime has already taken the place back, having cancelled the + // event and waited out the grace period, a grant here is ignored, since + // returning the same place twice would grow the window. Zero still withholds, + // and the runtime gives up the place it returned. uint32 credit_grant = 2; oneof outcome { diff --git a/libs/runtime/sdk/bindgen-ffi/src/application.rs b/libs/runtime/sdk/bindgen-ffi/src/application.rs index fb7bdd7a..34fdb2e9 100644 --- a/libs/runtime/sdk/bindgen-ffi/src/application.rs +++ b/libs/runtime/sdk/bindgen-ffi/src/application.rs @@ -8,7 +8,8 @@ use celerity_helpers::{ use celerity_runtime_core::{ application::Application as RuntimeApp, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ClientIpSource, RuntimeConfig, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, + ClientIpSource, RuntimeConfig, }, errors::{ApplicationStartError, ConfigError}, }; @@ -69,6 +70,7 @@ pub unsafe fn application_create(core_runtime_config: CoreRuntimeConfig) -> *mut deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), + ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), }, Box::new(ProcessEnvVars::new()), ), diff --git a/libs/runtime/sdk/node/src/lib.rs b/libs/runtime/sdk/node/src/lib.rs index d9a9ac26..b891372d 100644 --- a/libs/runtime/sdk/node/src/lib.rs +++ b/libs/runtime/sdk/node/src/lib.rs @@ -30,11 +30,11 @@ use celerity_runtime_core::{ auth_custom::{AuthGuardHandler, AuthGuardValidateError, AuthGuardValidateInput}, auth_http::AuthContext, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ApiConfig, AppConfig, ClientIpSource, - ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, - EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, HttpConfig, - HttpHandlerDefinition, RuntimeConfig, ScheduleConfig, SchedulesConfig, WebSocketConfig, - WebSocketHandlerDefinition, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, + ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, + CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, + GuardHandlerDefinition, GuardsConfig, HttpConfig, HttpHandlerDefinition, RuntimeConfig, + ScheduleConfig, SchedulesConfig, WebSocketConfig, WebSocketHandlerDefinition, }, consts::{ DEFAULT_RESOURCE_STORE_CACHE_ENTRY_TTL, DEFAULT_RESOURCE_STORE_CLEANUP_INTERVAL, @@ -1333,6 +1333,7 @@ impl CoreRuntimeApplication { deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), + ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), }; let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); CoreRuntimeApplication { diff --git a/libs/runtime/sdk/python/src/lib.rs b/libs/runtime/sdk/python/src/lib.rs index e1c93d14..30c2bbf2 100644 --- a/libs/runtime/sdk/python/src/lib.rs +++ b/libs/runtime/sdk/python/src/lib.rs @@ -25,10 +25,10 @@ use celerity_runtime_core::{ application::Application, auth_http::AuthContext, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ApiConfig, AppConfig, ClientIpSource, - ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, - EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, RuntimeConfig, - ScheduleConfig, SchedulesConfig, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, + ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, + CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, + GuardHandlerDefinition, GuardsConfig, RuntimeConfig, ScheduleConfig, SchedulesConfig, }, request::{MatchedRoute, RequestId, ResolvedClientIp, ResolvedUserAgent}, telemetry_utils::extract_trace_context, @@ -514,6 +514,7 @@ impl CoreRuntimeApplication { deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), + ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), }; println!("Creating CoreRuntimeApplication with config: {native_runtime_config:?}"); let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new()));