Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions src/workerd/server/factory/worker-factory-rpc.c++
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
#include <workerd/server/actor-id-impl.h>
#include <workerd/util/mimetype.h>

#include <capnp/rpc.capnp.h>
#include <capnp/serialize-async.h>
#include <kj/compat/http.h>

namespace workerd::server {
Expand Down Expand Up @@ -193,6 +195,141 @@ kj::Promise<void> 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<ServerHandle> server,
::rust::Box<PeerSession> session,
capnp::HttpOverCapnpFactory& httpOverCapnpFactory)
: server(kj::mv(server)),
session(kj::mv(session)),
httpOverCapnpFactory(httpOverCapnpFactory) {}

kj::Promise<void> 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<WorkerdBootstrapImpl>(kj::mv(target), httpOverCapnpFactory));
return kj::READY_NOW;
}

private:
::rust::Box<ServerHandle> server;
::rust::Box<PeerSession> 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<void> closing)
: inner(inner),
closing(closing.fork()) {}

// Why the session was closed, if it was closed this way.
kj::Maybe<const kj::Exception&> getReason() const {
return reason;
}

kj::Promise<size_t> 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<void> write(kj::ArrayPtr<const kj::byte> buffer) override {
return inner.write(buffer);
}
kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const kj::byte>> pieces) override {
return inner.write(pieces);
}
kj::Promise<void> 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<void> closing;
kj::Maybe<kj::Exception> 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<void> readUntilClosed(kj::AsyncInputStream& stream) {
auto scratch = kj::heapArray<kj::byte>(4096);
while (co_await stream.tryRead(scratch.begin(), 1, scratch.size()) > 0) {}
}
} // namespace

kj::Promise<void> factory_accept_cluster_peer(const WorkerFactory& factory,
kj::Own<kj::AsyncIoStream> stream,
::rust::Box<PeerSession> peer,
::rust::Box<ResultTask> closing) {
auto& impl = factory.getImpl();
ClosingStream session(*stream, result_task_run(kj::mv(closing)));
{
capnp::TwoPartyServer rpcServer(rpc::WorkerdDebugPort::Client(kj::heap<ClusterPeerPortImpl>(
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<capnp::rpc::Message>().initAbort();
abort.setReason(reason.getDescription());
abort.setType(static_cast<capnp::rpc::Exception::Type>(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

Expand Down
5 changes: 5 additions & 0 deletions src/workerd/server/factory/worker-factory.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ struct ActorNamespaceHandle;
struct ActorHooks;
struct Committer;
struct ResultTask;
struct PeerSession;
struct KeepAlive;
struct MovedHook;
struct WorkerInterfaceList;
Expand Down Expand Up @@ -408,6 +409,10 @@ kj::Promise<void> factory_accept_bootstrap(const WorkerFactory& factory,
::rust::Box<SubrequestChannel> target);
kj::Promise<void> factory_accept_debug_port(
const WorkerFactory& factory, kj::Own<kj::AsyncIoStream> stream);
kj::Promise<void> factory_accept_cluster_peer(const WorkerFactory& factory,
kj::Own<kj::AsyncIoStream> stream,
::rust::Box<PeerSession> session,
::rust::Box<ResultTask> closing);

// The client side of a capnp-over-HTTP-CONNECT connection.
class RpcClient final {
Expand Down
88 changes: 77 additions & 11 deletions src/workerd/server/server/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -426,26 +427,33 @@ 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<ActorIdHandle>, persistent: Persistent) -> Rc<dyn Channel> {
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<ActorIdHandle>) -> Rc<dyn Channel> {
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<ActorIdHandle>,
session: Option<Rc<Count>>,
) -> Rc<dyn Channel> {
self.channel_for(id, false, true, session)
}

fn channel_for(
&self,
id: KjOwn<ActorIdHandle>,
persistent: Persistent,
remote: bool,
session: Option<Rc<Count>>,
) -> Rc<dyn Channel> {
if self.cluster().is_some() {
return Rc::new(RoutedChannel {
namespace: Weak::clone(&self.this),
id,
persistent,
remote,
session,
bound: Rc::default(),
});
}
Expand Down Expand Up @@ -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<Rc<Count>>,
bound: Rc<RefCell<Option<Rc<Resolved>>>>,
}

/// 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<Instant>) -> 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<ActorIdHandle>,
remote: bool,
relay_by: Option<Instant>,
key: &str,
) -> Result<Result<Resolved>> {
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,
Expand All @@ -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<Instant> = None;
let resolved = loop {
// A resolution over a session known to be down would fail unsent: resolve again.
let live = bound
Expand All @@ -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,
Expand All @@ -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(..))
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -2340,6 +2402,10 @@ pub async fn hand_off_all(namespaces: &[Rc<ActorNamespace>], 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<Heat> = handoffs.iter().flatten().map(|(heat, _)| *heat).collect();
let order = cluster_logic::handoff::busiest_first(&heats, cluster::now_ms());
let ordered: Vec<_> = order
Expand Down
22 changes: 22 additions & 0 deletions src/workerd/server/server/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -652,6 +653,16 @@ pub mod ffi {
factory: &WorkerFactory,
stream: KjOwn<AsyncIoStream>,
) -> 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<AsyncIoStream>,
session: Box<PeerSession>,
closing: Box<ResultTask>,
) -> Result<()>;
/// The client side of a capnp-over-HTTP-CONNECT connection to an external server.
type RpcClient;
fn new_rpc_client(
Expand Down Expand Up @@ -887,6 +898,17 @@ pub mod ffi {
class_name: &str,
actor_id: &str,
) -> Result<Box<SubrequestChannel>>;
/// 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<Box<SubrequestChannel>>;
/// 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;
Expand Down
Loading
Loading