Single-threaded (!Send) client & server: tonic::local - #2806
Open
artsiomkaltovich wants to merge 5 commits into
Open
Single-threaded (!Send) client & server: tonic::local#2806artsiomkaltovich wants to merge 5 commits into
!Send) client & server: tonic::local#2806artsiomkaltovich wants to merge 5 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prototype for #2790 (see also #2171, #844, #1505, #784 — the same request keeps coming back).
Motivation
Tonic's generated servers require
Send + Sync + 'statichandlers, and the client path boxesfutures/bodies as
Send. That makes tonic hard to adopt in single-threaded async code: anythingholding
Rc,RefCell, or a non-Sendthird-party handle has to be redesigned or wrapped, eventhough the service will only ever run on one thread. Not every service needs a multi-threaded
runtime — a
current_threadruntime is often the right tool (lower latency variance, nocross-thread synchronisation, simpler state).
This PR makes that case work natively, without touching the multi-threaded path.
What this adds
tonic::local::— a!Sendclient, server, router, body, streaming and a minimal HTTP/2transport, all driven by
tokio::task::spawn_local.tonic_prost_build::Builder::local(true)(andCodeGenBuilder::local) emits#[async_trait(?Send)]service traits,Rc<T>handlers and non-Sendfutures.tokio::task::LocalSet(any tokio 1.x) ortokio::runtime::LocalRuntime(stable since tokio 1.51). No tokio version bump: the library only uses
spawn_local.Design
Feature-gated, additive, zero changes to existing public API.
local(pure — no new dependencies, wasm-friendly) andlocal-transport(adds the hyper/tokio bits for the provided server + channel).
localfeature ontonic-build/tonic-prost-buildgates thelocal()buildermethod, mirroring the existing
transport-feature precedent.pubitem changed signature or behaviour. Everything new lives undertonic::local::; the default build is byte-identical in API terms.BodyKind<B>,StreamingImpl<T, DecoderStore, B>,classify_response,set_grpc_response_headers,ServerGrpcConfig. TheSendand!Sendtypes are thin wrappersover the same cores, so the decode state machine, framing, compression and codec handling exist
once. Decode benches are at parity with the core path.
Send + Sync(Status,BoxError) — required by hyper's HTTP/2 signatures, andharmless:
Sendon an error value never constrains handlers, futures or state.Trade-offs of this approach
Pros
!Sendtypes are honestly!Send— misuse is a compile error, not a runtime surprise.Cons
Grpc<T>method bodies exist twice (client ~230 lines, server ~290): identical code whoseonly difference is
Send/'statictokens inwhereclauses. See below for why.tonic::Streamingvstonic::local::Streaming, …).reconnect/balancing. Enough for a prototype, not feature parity. (Good enough for prototype).
Alternatives considered
localimplementation). Simplest to write and to reason aboutin isolation, but every fix has to be applied twice and the two copies drift. Rejected as the
primary strategy — though see the point below: for the
Grpcmethod bodies it is what remains.The attractive option, and the one we probed hardest. It does not work on stable Rust: a shared
trait seam must fix its method bounds once for all impls, so the core impl's internal
Sendrequirements (
Body::new,Streaming::new_response) would leak into the trait signature andforce
Sendback onto the local call sites — defeating the feature. There is no way to make abound conditionally present per instantiation. A
macro_rules!template could cut ~150 lines,but at the cost of tt-munged
whereclauses and materially worse compiler errors: a bad tradefor code that is otherwise plainly readable and diffable. What could be shared has been, as
private generics (above).
Streaming<T, Store = …>).Removes most duplication, but changes tonic's core public types and their inference/rustdoc
identity — too invasive for a prototype, and a call for maintainers rather than a contributor. (To be honest, I prefer this, but it is you to decide)
ClientStreamingService<R, St = Streaming<R>>(same forStreamingService). Backwardcompatible (the default keeps every existing impl, including generated ones, compiling
unchanged) and would delete ~58 lines plus a codegen branch, letting
localreuse the coretraits. Deliberately not applied here — it modifies public traits, so it is offered as a
ready follow-up if you want it.
Example / tests
End-to-end echo service on a
current_threadruntime:tests/local/—proto/echo.proto,tests/local.rs.It covers all four RPC shapes with
Rc<RefCell<_>>handler state and non-Sendstreams in bothdirections, an interceptor round-trip, an unimplemented-path check, and the same flow on
LocalRuntimewith noLocalSet. Static assertions pin the guarantee that the local types are!Send, sotokio::spawnof them cannot compile.Status
All existing tests pass unchanged; new unit + e2e + codegen tests added; rustdoc clean under
-D warnings; feature combinations (localalone,local-transportalone, no-default-features)all build. Happy to split this into smaller PRs, or to adopt alternatives above, if that suits
review better.