From aebd6deb91149d4da2b641d9435792e84bc17e17 Mon Sep 17 00:00:00 2001 From: Bert Belder Date: Tue, 17 Nov 2026 17:38:42 -0800 Subject: [PATCH] Close peer sessions as moved when a cluster node stops A stopping node exited as soon as no peer request it had started was in flight. A peer's call that it had not started yet, still unread on the session or not yet routed to an object, was cut off with the process. The forwarder saw "Peer disconnected", which it treats as a request that may have run, so the client got a 500 instead of a retry. The node now ends its peers' sessions itself, once its own listeners have finished: * It starts no peer request from then on: one that reaches RoutedChannel is answered `moved`, before anything runs, and a new CONNECT is refused with 503, which the dialing peer reports as not delivered. The debug port's requests are still served, and counted until they end. * Each session counts the requests started on it, and closes once that count is zero, so a long-lived request holds only its own session open, up to the connections deadline. * A session closes with `moved` as the reason. A ClosingStream fails its reads, so capnp disconnects with that exception and sends it as an Abort, unless the connection is idle on its side. The node then sends an Abort itself, since an idle side may still have the peer's unread calls, which the peer would otherwise fail as plain disconnects. The peer fails every call it still has out on the session as `moved`, sends each again where the object runs now, and shuts its side. * The node reads on until the peer's EOF, so no unread data turns the close into a reset that could drop the Abort, but for about a second at most, so a peer that never closes holds up the stop little. The KJ timer that bounds it advances only when the loop runs out of work; the connections deadline bounds the stop in any case. Every call the Abort fails was not started: the node starts nothing after the cutoff, and closes a session only once everything started on it has finished. A peer's request that waited here for its object's handoff is sent on to where the object went only until the in-flight deadline, the time work in flight on the object had. Released later, as when a handoff runs late, it is answered `moved` before anything runs, and the peer sends it there itself. Relayed, it could still be running when the connections deadline cuts it off, as a call that may have run, which the peer cannot send again. The deadline is checked again as the relay starts, and bounds resolving where the object went, which can wait on the bucket or a peer's dial: resolving runs nothing on the object, so `moved` is still safe then. Each such answer is logged, as is the start of the handoffs. The debug port's requests are still sent on, since its clients do not retry on `moved`. The cluster port no longer serves the whole debug port. It exposed getEntrypoint (any service, stateless entrypoints included) and getActor for ephemeral and non-clustered namespaces, none of which was counted, so a peer could have started side-effecting work that a stop would then Abort as `moved` after it ran. Peers only ever call getActor on clustered namespaces, so a peer session now gets ClusterPeerPortImpl: getActor for clustered namespaces only, with every request counted on the session, and getEntrypoint unimplemented. The debug port listener is unchanged. The new cluster test runs two lanes of increments, one at a time each, on stubs bound to the stopping node, across its exit, so that a call lands while the node stops. It checks that each call applied exactly once: every call succeeds, the counts have no repeats or gaps, and the final count matches. It also holds an idle session to the stopping node, and checks that the node's own Abort carries the reason. Without this change, with that idle check left out, it fails in 20 of 20 runs: 18 on "Network connection lost", 2 on a node that never found a gap to exit in. With it, it passes 20 of 20. Another test holds a request on a DO past the in-flight deadline, so that its handoff ends late. Once the DO reports the request running on the stopping node, and that node logs that its handoffs started, the test sends a peer's request that waits for the handoff. It checks from the stopping node's log that the peer's request was answered `moved`, and that it ran where the DO went. Relayed instead, it fails in 10 of 10 runs on "Network connection lost"; with the `moved` answer it passes 40 of 40. --- .../server/factory/worker-factory-rpc.c++ | 137 +++++++++++++++ src/workerd/server/factory/worker-factory.h | 5 + src/workerd/server/server/actor.rs | 88 ++++++++-- src/workerd/server/server/bridge.rs | 22 +++ src/workerd/server/server/cluster.rs | 143 ++++++++++++--- src/workerd/server/server/config.rs | 31 +++- src/workerd/server/server/run.rs | 5 +- .../server/tests/cluster/cluster-test.mjs | 166 +++++++++++++++++- .../server/tests/cluster/cluster-worker.js | 46 ++++- src/workerd/server/workerd.capnp | 7 +- 10 files changed, 609 insertions(+), 41 deletions(-) diff --git a/src/workerd/server/factory/worker-factory-rpc.c++ b/src/workerd/server/factory/worker-factory-rpc.c++ index 0140383c545..3258c08eeb4 100644 --- a/src/workerd/server/factory/worker-factory-rpc.c++ +++ b/src/workerd/server/factory/worker-factory-rpc.c++ @@ -12,6 +12,8 @@ #include #include +#include +#include #include namespace workerd::server { @@ -193,6 +195,141 @@ kj::Promise factory_accept_debug_port( co_await rpcServer.accept(*stream); } +// ======================================================================================= +// Cluster peers + +namespace { +// What a cluster peer's session serves: the debug port's interface, with only `getActor`, for the +// actors of clustered namespaces. Every request on one of those is counted on the session, so that +// a stopping instance knows which it started (`ClusterNode::stop_peer_sessions`); `getEntrypoint` +// is unimplemented. +class ClusterPeerPortImpl final: public rpc::WorkerdDebugPort::Server { + public: + ClusterPeerPortImpl(::rust::Box server, + ::rust::Box session, + capnp::HttpOverCapnpFactory& httpOverCapnpFactory) + : server(kj::mv(server)), + session(kj::mv(session)), + httpOverCapnpFactory(httpOverCapnpFactory) {} + + kj::Promise getActor(GetActorContext context) override { + auto params = context.getParams(); + auto target = subrequest_channel_into_kj(server->resolve_peer_actor(*session, + toRust(params.getService()), toRust(params.getEntrypoint()), toRust(params.getActorId()))); + context.initResults(capnp::MessageSize{4, 1}) + .setActor(kj::heap(kj::mv(target), httpOverCapnpFactory)); + return kj::READY_NOW; + } + + private: + ::rust::Box server; + ::rust::Box session; + capnp::HttpOverCapnpFactory& httpOverCapnpFactory; +}; + +// The stream a peer's session runs over. Once `closing` fails, every read does, with its +// exception: the session then disconnects with it as its reason, which the RPC system sends the +// peer unless the session is idle (see below). Its write side then stays open, for the caller to +// end (`getReason()`). +class ClosingStream final: public kj::AsyncIoStream { + public: + ClosingStream(kj::AsyncIoStream& inner, kj::Promise closing) + : inner(inner), + closing(closing.fork()) {} + + // Why the session was closed, if it was closed this way. + kj::Maybe getReason() const { + return reason; + } + + kj::Promise tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { + auto failed = closing.addBranch().then( + []() -> size_t { KJ_FAIL_REQUIRE("a session's closing future resolved without a reason"); }, + // A stream outlives the reads it returns (kj::AsyncInputStream's contract). + // NOLINTNEXTLINE(workerd-unsafe-continuation-capture) + [this](kj::Exception&& e) -> size_t { + if (reason == kj::none) reason = e.clone(); + kj::throwFatalException(kj::mv(e)); + }); + return inner.tryRead(buffer, minBytes, maxBytes).exclusiveJoin(kj::mv(failed)); + } + kj::Promise write(kj::ArrayPtr buffer) override { + return inner.write(buffer); + } + kj::Promise write(kj::ArrayPtr> pieces) override { + return inner.write(pieces); + } + kj::Promise whenWriteDisconnected() override { + return inner.whenWriteDisconnected(); + } + void shutdownWrite() override { + if (reason == kj::none) inner.shutdownWrite(); + } + void abortRead() override { + inner.abortRead(); + } + + private: + kj::AsyncIoStream& inner; + kj::ForkedPromise closing; + kj::Maybe reason; +}; + +// How long a session this instance closed waits for the peer to close its side, once the reason +// is sent, so a peer that does not close it holds up the stop little. About this long: the KJ +// timer advances only when the loop runs out of work, and on a loop that stays busy this runs +// past it. The connections deadline bounds the stop in any case. +constexpr kj::Duration PEER_CLOSE_TIMEOUT = 1 * kj::SECONDS; + +// Reads `stream` until the peer closes it. +kj::Promise readUntilClosed(kj::AsyncInputStream& stream) { + auto scratch = kj::heapArray(4096); + while (co_await stream.tryRead(scratch.begin(), 1, scratch.size()) > 0) {} +} +} // namespace + +kj::Promise factory_accept_cluster_peer(const WorkerFactory& factory, + kj::Own stream, + ::rust::Box peer, + ::rust::Box closing) { + auto& impl = factory.getImpl(); + ClosingStream session(*stream, result_task_run(kj::mv(closing))); + { + capnp::TwoPartyServer rpcServer(rpc::WorkerdDebugPort::Client(kj::heap( + impl.getServer().server_clone(), kj::mv(peer), impl.httpOverCapnpFactory))); + co_await rpcServer.accept(session); + } + KJ_IF_SOME(reason, session.getReason()) { + // Closed by this instance. The RPC system sends no reason when the session is idle, with no + // call or capability outstanding either way. Idle on this side does not mean idle on the + // peer's, which may have sent calls this side has not read, and fails those with a plain + // disconnect if it reads no reason. So the reason goes again here; a peer that read it once + // ignores what follows. The peer fails every call it still has out on the session with it, + // and shuts its side too. Read on until then, so that the stream closes with nothing of the + // peer's unread, which would reset the connection and might discard the reason before the + // peer read it; but for about PEER_CLOSE_TIMEOUT at most. + KJ_TRY { + capnp::MallocMessageBuilder message; + auto abort = message.initRoot().initAbort(); + abort.setReason(reason.getDescription()); + abort.setType(static_cast(reason.getType())); + auto details = reason.getDetails(); + auto out = abort.initDetails(details.size()); + for (auto i: kj::indices(details)) { + out[i].setDetailId(details[i].id); + out[i].setData(details[i].value); + } + co_await capnp::writeMessage(*stream, message); + stream->shutdownWrite(); + co_await readUntilClosed(*stream).exclusiveJoin(impl.timer.afterDelay(PEER_CLOSE_TIMEOUT)); + } + KJ_CATCH(e) { + // The peer is gone. + (void)e; + } + } +} + // ======================================================================================= // RPC client diff --git a/src/workerd/server/factory/worker-factory.h b/src/workerd/server/factory/worker-factory.h index 3c9ec30a7c9..87f3a58254c 100644 --- a/src/workerd/server/factory/worker-factory.h +++ b/src/workerd/server/factory/worker-factory.h @@ -57,6 +57,7 @@ struct ActorNamespaceHandle; struct ActorHooks; struct Committer; struct ResultTask; +struct PeerSession; struct KeepAlive; struct MovedHook; struct WorkerInterfaceList; @@ -408,6 +409,10 @@ kj::Promise factory_accept_bootstrap(const WorkerFactory& factory, ::rust::Box target); kj::Promise factory_accept_debug_port( const WorkerFactory& factory, kj::Own stream); +kj::Promise factory_accept_cluster_peer(const WorkerFactory& factory, + kj::Own stream, + ::rust::Box session, + ::rust::Box closing); // The client side of a capnp-over-HTTP-CONNECT connection. class RpcClient final { diff --git a/src/workerd/server/server/actor.rs b/src/workerd/server/server/actor.rs index 06bdf8cdf26..2e0f6bfa5f9 100644 --- a/src/workerd/server/server/actor.rs +++ b/src/workerd/server/server/actor.rs @@ -63,6 +63,7 @@ use crate::channels::WorkerInterface; use crate::channels::attach; use crate::cluster::ClusterNode; use crate::cluster::Committer; +use crate::cluster::Count; use crate::cluster::Deadlines; use crate::cluster::Owned; use crate::cluster::Owner; @@ -426,12 +427,17 @@ impl ActorNamespace { /// The channel of the actor with `id`, started on first use. `persistent` is recorded on the /// channel: whether stubs to it may be stored. pub fn channel(&self, id: KjOwn, persistent: Persistent) -> Rc { - self.channel_for(id, persistent, false) + self.channel_for(id, persistent, false, None) } - /// The channel of the actor with `id` for a peer's or the debug port's request. - pub fn peer_channel(&self, id: KjOwn) -> Rc { - self.channel_for(id, false, true) + /// The channel of the actor with `id` for the debug port's request, or with `session` a + /// peer's, which counts the requests started on it. + pub fn peer_channel( + &self, + id: KjOwn, + session: Option>, + ) -> Rc { + self.channel_for(id, false, true, session) } fn channel_for( @@ -439,6 +445,7 @@ impl ActorNamespace { id: KjOwn, persistent: Persistent, remote: bool, + session: Option>, ) -> Rc { if self.cluster().is_some() { return Rc::new(RoutedChannel { @@ -446,6 +453,7 @@ impl ActorNamespace { id, persistent, remote, + session, bound: Rc::default(), }); } @@ -826,9 +834,45 @@ struct RoutedChannel { persistent: Persistent, /// Whether its requests come from a peer (or the debug port). remote: bool, + /// The peer's session, which counts the requests started on it. + session: Option>, bound: Rc>>>, } +/// Answers `moved` to a peer's request for the object `key` that waited for its handoff, past +/// the time to relay it (`ClusterNode::handed_off_relay_deadline`). +fn handed_off(key: &str) -> crate::Error { + tracing::info!( + "cluster: {key}: a peer's request that waited for its handoff is answered moved" + ); + moved("the Durable Object was handed off") +} + +/// Whether `deadline` passed. +fn passed(deadline: Option) -> bool { + deadline.is_some_and(|deadline| Instant::now() >= deadline) +} + +/// Resolves the object `id` of `namespace` for a request (`ActorNamespace::resolve`), which a +/// relay of a request that waited for its handoff must have started by `relay_by`. Resolving runs +/// nothing on the object, so a resolution that outlasts that is answered `moved` still: the outer +/// error; the inner one is the resolution's. +async fn resolve_by( + namespace: &ActorNamespace, + id: KjOwn, + remote: bool, + relay_by: Option, + key: &str, +) -> Result> { + let resolving = namespace.resolve(id, remote); + match relay_by { + Some(by) => tokio::time::timeout_at(by, resolving) + .await + .map_err(|_| handed_off(key)), + None => Ok(resolving.await), + } +} + impl Channel for RoutedChannel { fn start_request( &self, @@ -855,14 +899,23 @@ impl Channel for RoutedChannel { ffi::stamp_current_actor_cause(metadata.as_mut()); } let cause = Cause::of_request(&metadata); - let counted = remote.then(|| namespace.cluster().map(|node| node.peer_request())); + let peer = remote && self.session.is_some(); + let counted = match namespace.cluster() { + Some(node) if remote => Some(node.peer_request(self.session.as_ref())?), + _ => None, + }; Ok(PromisedInterface::new(async move { // A peer's request that waited for a handoff is sent on to where the object went, so - // that it does not outlast its caller's retries. It binds nothing, so that the peer's - // next request is answered `moved` and finds the object itself (`resolve`). Any request - // a draining instance sends to a peer names it, so that the peer does not route it back - // here on a route from before the handoff. + // that it does not outlast its caller's retries, while there is time for it: until + // `ClusterNode::handed_off_relay_deadline`, as it is resolved and as it starts. After + // that it is answered `moved`, nothing having run. The debug port's requests are always + // sent on. It binds nothing, so that the peer's next request is answered `moved` and + // finds the object itself (`resolve`). Any request a draining instance sends to a peer + // names it, so that the peer does not route it back here on a route from before the + // handoff. let mut forward = false; + // When a relay of a peer's request that waited for a handoff must have started by. + let mut relay_by: Option = None; let resolved = loop { // A resolution over a session known to be down would fail unsent: resolve again. let live = bound @@ -872,8 +925,9 @@ impl Channel for RoutedChannel { let resolved = if let Some(resolved) = live.filter(|_| !forward) { resolved } else { - let resolved = namespace.resolve(ffi::actor_id_clone(&id), remote && !forward); - let resolved = Rc::new(resolved.await.map_err(not_delivered)?); + let id = ffi::actor_id_clone(&id); + let resolved = resolve_by(&namespace, id, remote && !forward, relay_by, &key); + let resolved = Rc::new(resolved.await?.map_err(not_delivered)?); let mut bound = bound.borrow_mut(); match &*bound { _ if forward => resolved, @@ -896,6 +950,12 @@ impl Channel for RoutedChannel { // Nothing ran: once the object is gone, the request follows it. let _ = handoff.wait_for(|done| *done).await; forget(&bound, &resolved); + if peer && let Some(node) = namespace.cluster() { + relay_by = node.handed_off_relay_deadline(); + if passed(relay_by) { + return Err(handed_off(&key)); + } + } forward = remote; }; if matches!(&*resolved, Resolved::Remote(..)) @@ -923,6 +983,8 @@ impl Channel for RoutedChannel { Err(e) } }, + // Checked again as it starts: resolving can take long. + Resolved::Remote(..) if passed(relay_by) => Err(handed_off(&hook.key)), Resolved::Remote(connection, _) => Ok(ffi::worker_interface_watch_peer( attach(connection.start_request(metadata), Rc::clone(connection)), Box::new(hook), @@ -2340,6 +2402,10 @@ pub async fn hand_off_all(namespaces: &[Rc], deadlines: Deadline .flat_map(|ns| ns.handoffs(deadlines.in_flight, &slots)) .map(Some) .collect(); + tracing::info!( + "cluster: stopping: handing off Durable Objects: {}", + handoffs.len() + ); let heats: Vec = handoffs.iter().flatten().map(|(heat, _)| *heat).collect(); let order = cluster_logic::handoff::busiest_first(&heats, cluster::now_ms()); let ordered: Vec<_> = order diff --git a/src/workerd/server/server/bridge.rs b/src/workerd/server/server/bridge.rs index 77c12d778f8..45f9d896d8e 100644 --- a/src/workerd/server/server/bridge.rs +++ b/src/workerd/server/server/bridge.rs @@ -28,6 +28,7 @@ pub use crate::channels::SubrequestChannel; pub use crate::channels::WorkerInterfaceList; pub use crate::channels::WorkerStub; pub use crate::cluster::Committer; +pub use crate::cluster::PeerSession; pub use crate::cluster::ResultTask; pub use crate::cluster::result_task_run; pub use crate::entry::PendingCommand; @@ -652,6 +653,16 @@ pub mod ffi { factory: &WorkerFactory, stream: KjOwn, ) -> Result<()>; + /// Serves a cluster peer's session: the debug port's interface with only `getActor`, + /// for clustered namespaces (`resolve_peer_actor`). Once `closing` fails, the session + /// disconnects with its error, which fails every call the peer still has out on it; it + /// resolves once the peer shut its side of the connection too. + async fn factory_accept_cluster_peer( + factory: &WorkerFactory, + stream: KjOwn, + session: Box, + closing: Box, + ) -> Result<()>; /// The client side of a capnp-over-HTTP-CONNECT connection to an external server. type RpcClient; fn new_rpc_client( @@ -887,6 +898,17 @@ pub mod ffi { class_name: &str, actor_id: &str, ) -> Result>; + /// A cluster peer's `getActor`: an actor of a clustered namespace, by its hex id, whose + /// requests `session` counts. + fn resolve_peer_actor( + self: &ServerHandle, + session: &PeerSession, + service_name: &str, + class_name: &str, + actor_id: &str, + ) -> Result>; + /// A session a cluster peer has open here (`ClusterNode`). + type PeerSession; /// A worker's I/O channel table for one request: what its bindings reach. type ChannelFactory; diff --git a/src/workerd/server/server/cluster.rs b/src/workerd/server/server/cluster.rs index 616b3f42131..869ae13c8ec 100644 --- a/src/workerd/server/server/cluster.rs +++ b/src/workerd/server/server/cluster.rs @@ -82,8 +82,13 @@ pub struct ClusterNode { alarms_interval: Duration, /// Set once this instance drains. deadlines: Cell>, - /// The requests peers have in flight here. - peer_requests: Rc, + /// The requests the debug port has in flight here; a peer's are its session's. + peer_requests: Rc, + /// The sessions peers have open here (`PeerConnection::connect`). + peer_sessions: Rc, + /// Set once this instance stops its peers' sessions (`stop_peer_sessions`): from then on it + /// starts none of their requests, and accepts no session. + refusing_peers: Rc, /// Whether the application's listeners are being served (`Serving`). serving: Cell, } @@ -99,9 +104,9 @@ pub struct Deadlines { pub stop: Instant, } -/// A count of requests, and its waiters for it to reach zero. +/// A count, and its waiters for it to reach zero. #[derive(Default)] -struct PeerRequests { +pub struct Count { count: Cell, none: Notify, } @@ -115,10 +120,10 @@ impl Drop for Serving { } } -/// A request a peer has in flight here, from its start until its interface is dropped. -pub struct PeerRequest(Rc); +/// One of a `Count`, until it is dropped. +pub struct Counted(Rc); -impl Drop for PeerRequest { +impl Drop for Counted { fn drop(&mut self) { let count = self.0.count.get() - 1; self.0.count.set(count); @@ -128,6 +133,53 @@ impl Drop for PeerRequest { } } +impl Count { + /// Counts one until the guard is dropped. + fn add(self: &Rc) -> Counted { + self.count.set(self.count.get() + 1); + Counted(Rc::clone(self)) + } + + /// Resolves once the count is zero. + async fn none(&self) { + loop { + let none = self.none.notified(); + if self.count.get() == 0 { + return; + } + none.await; + } + } +} + +/// A flag that is set once, and its waiters for it. +#[derive(Default)] +struct Signal { + set: Cell, + notify: Notify, +} + +impl Signal { + fn is_set(&self) -> bool { + self.set.get() + } + + fn set(&self) { + self.set.set(true); + self.notify.notify_waiters(); + } + + async fn wait(&self) { + loop { + let set = self.notify.notified(); + if self.set.get() { + return; + } + set.await; + } + } +} + /// How often an instance tidies its alarm index and adopts dead peers' alarms. const ALARMS_INTERVAL: Duration = Duration::from_secs(5); @@ -435,6 +487,8 @@ impl ClusterNode { alarms_interval: ALARMS_INTERVAL / divisor, deadlines: Cell::new(None), peer_requests: Rc::default(), + peer_sessions: Rc::default(), + refusing_peers: Rc::default(), serving: Cell::new(false), })) } @@ -487,24 +541,39 @@ impl ClusterNode { released } - /// Counts a request a peer makes here until the guard is dropped. - pub fn peer_request(&self) -> PeerRequest { - let requests = Rc::clone(&self.peer_requests); - requests.count.set(requests.count.get() + 1); - PeerRequest(requests) + /// When a relay of a peer's request that waited here for its object's handoff must start by, + /// once this instance stops; none before. Sent on, the request does not outlast its caller's + /// retries; but a call this instance relays when its connections deadline comes is cut off as + /// one that may have run, which the peer cannot send again. So it relays only while the call + /// has the time work in flight on an object being handed off has had, until the `in_flight` + /// deadline; from then on it answers `moved`, and the peer sends the request where the object + /// went itself. + pub fn handed_off_relay_deadline(&self) -> Option { + self.deadlines.get().map(|deadlines| deadlines.in_flight) } - /// Resolves once no peer has a request in flight here. - pub async fn peer_requests_done(&self) { - loop { - let none = self.peer_requests.none.notified(); - if self.peer_requests.count.get() == 0 { - return; - } - none.await; + /// Starts a request a peer makes here, or the debug port: counted on the peer's `session`, + /// or else on this instance, until the guard is dropped. Once this instance stops its peers' + /// sessions it answers a peer's `moved` instead, before anything runs, and the peer sends the + /// request where the object runs now. The debug port's requests are served as before. + pub fn peer_request(&self, session: Option<&Rc>) -> Result { + match session { + Some(_) if self.refusing_peers.is_set() => Err(moved("this instance is stopping")), + Some(session) => Ok(session.add()), + None => Ok(self.peer_requests.add()), } } + /// Ends its peers' sessions, once it serves nothing else. It starts none of their requests + /// from now on, and closes each session once the requests it started on it have ended: the + /// peer reads `moved` as its reason, which fails every call it still has out on the session, + /// none of which started here, as `moved` too, so it sends them again where the objects run + /// now. Resolves once every session has closed, and the debug port's requests have ended. + pub async fn stop_peer_sessions(&self) { + self.refusing_peers.set(); + futures::join!(self.peer_requests.none(), self.peer_sessions.none()); + } + pub fn add_namespace(&self, unique_key: &str, namespace: Weak) { let hash = cluster::namespace_hash(unique_key); self.namespaces.borrow_mut().insert(hash, namespace); @@ -804,9 +873,34 @@ impl Handler for PeerConnection { connect.reject(403, "Forbidden", HeadersRef::from(&empty), Some(0))?; return Ok(()); } + let node = &self.node; + // A stopping instance's sessions close (`ClusterNode::stop_peer_sessions`). Refused, the + // peer sends its requests elsewhere: none were sent. + if node.refusing_peers.is_set() { + let headers = HeadersRef::from(&empty); + connect.reject(503, "Service Unavailable", headers, Some(0))?; + return Ok(()); + } + let _open = node.peer_sessions.add(); let tunnel = connect.accept(200, "OK", HeadersRef::from(&empty))?; - // A peer holds the cluster key, so it gets the debug port's interface. - Ok(ffi::factory_accept_debug_port(self.node.factory.raw(), tunnel.into_kj()).await?) + let requests = Rc::::default(); + let session = Box::new(PeerSession { + requests: Rc::clone(&requests), + }); + // Closes once the instance stops its peers' sessions and no request started on this one + // is in flight. + let refusing = Rc::clone(&node.refusing_peers); + let closing = Box::new(ResultTask( + async move { + refusing.wait().await; + requests.none().await; + Err(moved("this instance stopped")) + } + .boxed_local(), + )); + // A peer holds the cluster key, so it reaches the clustered objects here. + let factory = node.factory.raw(); + Ok(ffi::factory_accept_cluster_peer(factory, tunnel.into_kj(), session, closing).await?) } } @@ -825,6 +919,11 @@ fn capnp(e: &capnp::Error) -> crate::Error { kj::failed!("{e}") } +/// A session a peer has open here: the requests started on it, each counted until it ends. +pub struct PeerSession { + pub(crate) requests: Rc, +} + /// A Rust future C++ awaits (`result_task_run`). pub struct ResultTask(pub LocalBoxFuture<'static, Result<()>>); diff --git a/src/workerd/server/server/config.rs b/src/workerd/server/server/config.rs index 1d2cda8f1bf..3d8d37882fb 100644 --- a/src/workerd/server/server/config.rs +++ b/src/workerd/server/server/config.rs @@ -55,6 +55,7 @@ use crate::channels::SubrequestChannel; use crate::channels::TokenUsage; use crate::channels::WorkerInterface; use crate::cluster::ClusterNode; +use crate::cluster::PeerSession; use crate::listen::loopback::Loopback; use crate::loader::WorkerLoaderNamespace; use crate::services::DiskDirectoryService; @@ -1964,12 +1965,40 @@ impl ServerHandle { ) })?; Ok(SubrequestChannel::new(match namespace.unique_key() { - Some(_) => namespace.peer_channel(ffi::actor_id_from_hex(actor_id)?), + Some(_) => namespace.peer_channel(ffi::actor_id_from_hex(actor_id)?, None), None => namespace.channel_by_name(actor_id, false), })) } } +impl ServerHandle { + pub(crate) fn resolve_peer_actor( + &self, + session: &PeerSession, + service_name: &str, + class_name: &str, + actor_id: &str, + ) -> Result> { + let server = self.server()?; + let namespace = server + .debug_service(service_name)? + .as_worker() + .and_then(|worker| worker.namespace(class_name)) + .filter(|namespace| namespace.cluster().is_some()) + .ok_or_else(|| { + kj::failed!( + "jsg.Error: no clustered Durable Object class \"{class_name}\" in \ + \"{service_name}\"" + ) + })?; + let id = ffi::actor_id_from_hex(actor_id)?; + let session = Rc::clone(&session.requests); + Ok(SubrequestChannel::new( + namespace.peer_channel(id, Some(session)), + )) + } +} + impl Server { /// The service a debug-port request names. fn debug_service(&self, service_name: &str) -> Result<&Service> { diff --git a/src/workerd/server/server/run.rs b/src/workerd/server/server/run.rs index 4726c6980fd..5fe3423e4e2 100644 --- a/src/workerd/server/server/run.rs +++ b/src/workerd/server/server/run.rs @@ -457,7 +457,8 @@ pub async fn run( // `preventEviction` or not, while it serves on: a request for one waits for it and // then goes where it runs next. Then it leaves the cluster, so peers take over what // it did not hand off, accepts requests until the grace period ends, as load - // balancers may still send some, and lets its connections, peers' among them, finish. + // balancers may still send some, and lets its connections finish, its peers' sessions + // last (`ClusterNode::stop_peer_sessions`). if let Some(node) = server.cluster() { let deadlines = node.start_draining(); let workers = server @@ -510,7 +511,7 @@ pub async fn run( if !serving.is_terminated() { serving.as_mut().await?; } - node.peer_requests_done().await; + node.stop_peer_sessions().await; Ok::<_, crate::Error>(()) }; let finished = tokio::time::timeout_at(deadlines.connections, finished); diff --git a/src/workerd/server/tests/cluster/cluster-test.mjs b/src/workerd/server/tests/cluster/cluster-test.mjs index 9b33528603e..fade9b1ea4e 100644 --- a/src/workerd/server/tests/cluster/cluster-test.mjs +++ b/src/workerd/server/tests/cluster/cluster-test.mjs @@ -22,7 +22,8 @@ // breaks, while a fresh stub reaches the re-instantiated DO. One whose // owner drains follows the DO to its next owner, also once that owner // exited, and a request that may have run on the drained owner is not -// replayed there. +// replayed there, while one that reached it as it stopped, not started, +// is sent again. // 9. Facets and their deletions survive a takeover. // 10. Draining cancels a running onHibernate handler. // 11. A fresh cluster serves its bucket's deployment, Durable Objects @@ -33,7 +34,8 @@ // services or conflicts with another. // 12. A node stopping under load hands its DOs to its peers, two at once // too: requests that arrive meanwhile wait for a DO's handoff and follow -// it, JS RPC calls and other DOs' calls included, the calls of a +// it, JS RPC calls and other DOs' calls included, a peer's request +// released late is answered moved rather than sent on, the calls of a // handoff's work are not held, and a DO whose handoff outlasts its // deadline moves once the node left. A rolling restart of the cluster, // paced by the nodes' readiness, fails, loses and replays no request. @@ -1930,6 +1932,108 @@ test( } ); +test( + 'cluster: calls a peer has on the way to a node that stops are sent again', + SIGTERM_DRAINS, + async () => { + await withCluster(2, async ({ nodes, nodeKeys }) => { + const first = await fetchJson(nodes[0].httpPort, '/increment?name=late'); + assert.strictEqual(first.body.nodeId, nodes[0].nodeId); + assert.strictEqual(first.body.count, 1); + const n = 256; + const held = await fetchJson( + nodes[1].httpPort, + `/hold-stubs?name=holder&target=late&n=${n}` + ); + assert.strictEqual(held.status, 200, JSON.stringify(held.body)); + assert.strictEqual(held.body.nodeId, nodes[1].nodeId); + assert.deepStrictEqual(held.body.reached, Array(n).fill(nodes[0].nodeId)); + + // A session node 0 holds nothing of: a peer's CONNECT that sends + // nothing. As node 0 closes it, it still tells the peer why, and waits + // for the peer to close its side. + const idle = connect(nodes[0].clusterPort, '127.0.0.1'); + await new Promise((resolve) => idle.once('connect', resolve)); + const auth = clusterAuth( + nodeKeys.get(nodes[0].nodeId), + `127.0.0.1:${nodes[0].clusterPort}` + ); + idle.write( + `CONNECT cluster:1 HTTP/1.1\r\nhost: cluster:1\r\ncf-cluster-auth: ${auth}\r\n\r\n` + ); + let told = ''; + let answered; + const answer = new Promise((resolve) => (answered = resolve)); + const closed = new Promise((resolve) => { + idle.on('data', (data) => { + told += data.toString('latin1'); + if (told.includes('\r\n\r\n')) answered(); + if (told.includes('this instance stopped')) idle.end(); + }); + idle.on('end', () => idle.end()); + idle.on('close', resolve); + idle.on('error', resolve); + }).finally(() => answered()); + await answer; + assert.match(told, /^HTTP\/1\.1 200 /); + + // From shortly before node 0's grace period ends until it has exited, + // two lanes of increments, a call at a time in each, each on a stub that + // reached node 0, so that each goes to node 0 whatever node 0 is doing. + // Node 0 stops once no call is in flight there, and the next call lands + // as it stops. Node 0 finishes the calls it started, and each it did not + // is sent again, and finds the DO on node 1: each call applies once. + let exited = false; + const exit = nodes[0] + .stop({ signal: 'SIGTERM', timeoutMs: 10_000 }) + .finally(() => (exited = true)); + await sleep(GRACE_MS - 250); + const call = (i) => + fetchJson( + nodes[1].httpPort, + `/call-stub-n?name=holder&i=${i}&path=/increment`, + { timeoutMs: HANG_TIMEOUT_MS } + ); + const lanes = [[], []]; + let next = 0; + const lane = async (calls) => { + // Until it made two calls since node 0 exited. + for (let since = 0; next < n && since < 2;) { + if (exited) since++; + calls.push(await call(next++)); + } + }; + await Promise.all([lane(lanes[0]), sleep(5).then(() => lane(lanes[1]))]); + assert(exited, `node 0 still ran after ${n} calls`); + assert.deepStrictEqual(await exit, { code: 0, signal: null }); + await closed; + assert(told.includes('this instance stopped'), JSON.stringify(told)); + + const counts = []; + for (const calls of lanes) { + for (const { status, body } of calls) { + assert.strictEqual(status, 200, JSON.stringify(body)); + counts.push(body.target.count); + } + const own = calls.map(({ body }) => body.target.count); + assert.deepStrictEqual( + own, + [...own].sort((x, y) => x - y) + ); + } + const all = counts.length; + assert.deepStrictEqual( + [...counts].sort((x, y) => x - y), + Array.from({ length: all }, (_, i) => i + 2) + ); + const state = await fetchJson(nodes[1].httpPort, '/get?name=late', { + timeoutMs: HANG_TIMEOUT_MS, + }); + assert.strictEqual(state.body.count, all + 1); + }); + } +); + // Load on the DOs `names`: for each, one `/increment` at a time, each sent to // the next of the nodes `serving()` lists (indices into `nodes`), until // `finish()`. It resolves to the counts each DO's responses carried, in order, @@ -2077,6 +2181,64 @@ test( } ); +test( + "cluster: a peer's request a DO's late handoff releases is answered moved", + SIGTERM_DRAINS, + async () => { + await withCluster( + 2, + async ({ nodes }) => { + await fetchJson(nodes[0].httpPort, '/increment?name=late'); + // Through the peer, and cancelled when the handoff's time for + // requests in flight runs out, 2 s into the 4 s stop. + const held = fetchJson( + nodes[1].httpPort, + '/hold-increment?name=late&ms=15000', + { timeoutMs: 30_000 } + ); + await until( + async () => { + const { body } = await fetchJson( + nodes[0].httpPort, + '/holding?name=late' + ); + return body.nodeId === nodes[0].nodeId && body.holding === 1; + }, + 10_000, + 'the held request never ran on node 0' + ); + const exit = nodes[0].stop({ signal: 'SIGTERM', timeoutMs: 30_000 }); + // Logged once node 0 marks its objects as being handed off: from then + // on a request for one waits for its handoff. + await nodes[0].waitForStderr(/cluster: stopping: handing off/, 10_000); + // Through the peer too: it waits for the handoff, which ends past that. + // Sent on from there, it would still run when the stopping node's + // connections deadline cuts it off; answered moved, the peer runs it + // where the DO went. + const peer = await fetchJson( + nodes[1].httpPort, + '/hold-increment?name=late&ms=2000', + { timeoutMs: 30_000 } + ); + // It went to node 0, waited there, and was answered moved. + assert.match( + nodes[0].stderr, + /a peer's request that waited for its handoff is answered moved/ + ); + assert.strictEqual(peer.status, 200, JSON.stringify(peer.body)); + assert.deepStrictEqual( + [peer.body.nodeId, peer.body.count], + [nodes[1].nodeId, 2] + ); + const cut = await held; + assert.strictEqual(cut.status, 500, JSON.stringify(cut.body)); + assert.deepStrictEqual(await exit, { code: 0, signal: null }); + }, + { configName: 'shortStop' } + ); + } +); + test( "cluster: a stopping node's DOs finish calls to themselves and across nodes", SIGTERM_DRAINS, diff --git a/src/workerd/server/tests/cluster/cluster-worker.js b/src/workerd/server/tests/cluster/cluster-worker.js index 00b482f22a4..eb4aea2a8ad 100644 --- a/src/workerd/server/tests/cluster/cluster-worker.js +++ b/src/workerd/server/tests/cluster/cluster-worker.js @@ -32,9 +32,16 @@ // `path`, or with `rpc` set its identity() method. Returns // the target's response. A failure is reported with the // error's `retryable`. +// /hold-stubs Like /hold-stub, `n` stubs at once, each to the DO named +// by `target`, kept for /call-stub-n. Returns the node each +// reached. +// /call-stub-n Calls /identity, or the path given by `path`, on the stub +// /hold-stubs keeps at index `i`. Returns the target's +// response, or `{ error }` with status 500. // /hold Waits one second before responding, so that the test can // break the DO while this request is still in flight. // /hold-increment Waits `ms` (default 1000), then increments. +// /holding Returns how many /hold-increment requests are waiting. // /chain?targets=T Waits `ms` (default 0), sends /chain with the rest of the // DO names `targets` lists, separated by commas, to the // first, then increments: a call through other DOs, or @@ -274,6 +281,8 @@ export class Counter extends DurableObject { this.env = env; // See /hold-stub. Maps target DO name -> stub. this.heldStubs = new Map(); + // See /holding. + this.holding = 0; state.blockConcurrencyWhile(async () => { if (await state.storage.get(BREAK_ON_CONSTRUCT)) { @@ -368,6 +377,34 @@ export class Counter extends DurableObject { { status: 500 } ); } + } else if (url.pathname === '/hold-stubs') { + const target = url.searchParams.get('target'); + const n = Number(url.searchParams.get('n')); + this.heldStubList = Array.from({ length: n }, () => + this.env.COUNTER.get(this.env.COUNTER.idFromName(target)) + ); + const reached = await Promise.all( + this.heldStubList.map( + async (stub) => + (await (await stub.fetch('http://do/identity')).json()).nodeId + ) + ); + return Response.json({ nodeId, id: idHex, reached }); + } else if (url.pathname === '/call-stub-n') { + const stub = this.heldStubList[Number(url.searchParams.get('i'))]; + try { + const response = await stub.fetch( + 'http://do' + (url.searchParams.get('path') ?? '/identity') + ); + if (!response.ok) return response; + return Response.json({ + nodeId, + id: idHex, + target: await response.json(), + }); + } catch (err) { + return Response.json({ error: String(err) }, { status: 500 }); + } } else if (url.pathname === '/vend-stub') { const kind = url.searchParams.get('kind'); const target = url.searchParams.get('target'); @@ -406,10 +443,17 @@ export class Counter extends DurableObject { await scheduler.wait(1000); return Response.json({ nodeId, id: idHex }); } else if (url.pathname === '/hold-increment') { - await scheduler.wait(Number(url.searchParams.get('ms') ?? '1000')); + this.holding++; + try { + await scheduler.wait(Number(url.searchParams.get('ms') ?? '1000')); + } finally { + this.holding--; + } const count = ((await this.state.storage.get('count')) ?? 0) + 1; await this.state.storage.put('count', count); return Response.json({ count, nodeId, id: idHex }); + } else if (url.pathname === '/holding') { + return Response.json({ holding: this.holding, nodeId, id: idHex }); } else if (url.pathname === '/chain') { await scheduler.wait(Number(url.searchParams.get('ms') ?? '0')); const [next, ...rest] = (url.searchParams.get('targets') ?? '') diff --git a/src/workerd/server/workerd.capnp b/src/workerd/server/workerd.capnp index 841206636bc..2d524cf639c 100644 --- a/src/workerd/server/workerd.capnp +++ b/src/workerd/server/workerd.capnp @@ -276,8 +276,11 @@ struct ClusterConfig { # then go where it runs next. While a Durable Object serves a call of a handoff's work, all the # calls it makes count as that work. Then the instance leaves the cluster, keeps accepting # requests until at least five seconds after SIGTERM (or until the handoff deadline, if that comes - # sooner), as load balancers take a while to stop sending them, lets its connections finish, and - # stops its containers' Docker containers. + # sooner), as load balancers take a while to stop sending them, lets its connections finish, its + # peers' last, and then stops its containers' Docker containers. Once its other connections have + # finished, it starts none of its peers' requests, and closes each peer's connection once the + # requests it started on that connection have ended, so that the peer sends those it did not + # start where their Durable Objects run next. # # The time is spent in order: until half of it, requests in flight on an object being handed off # may finish, and are then cancelled, failing as requests that may have run, which are not sent