CanSendRun
The runner variant whose returned future is Send, for work that must cross a thread boundary.
Overview
In Context-Generic Programming (CGP), CanSendRun<Code> is CanRun with
one added guarantee: the future its method returns is
Send, so it can be handed to a spawner
such as tokio::spawn. CGP enables pluggable trait implementations in Rust, and CanSendRun is the
component that lets a context plug in a Send-future runner. It exists to solve a specific Rust limitation. A generic async fn over abstract
context types (the context being the type a method runs on that supplies the values an
implementation needs as its own fields) cannot promise its future is Send without annotating Send
bounds on every abstract type in scope, and those bounds pollute every interface.
CanSendRun<Code> sidesteps that by returning an explicit
impl Future<Output = Result<(), Error>> + Send, so the Send requirement lives on this one trait
rather than spreading across the abstract types.
A context implements CanSendRun<Code> as a thin proxy over its CanRun<Code>
implementation. Because the proxy is written against the concrete context, the compiler can confirm
the concrete future is Send without abstract-type annotations. This is a workaround that stays
necessary until Rust stabilizes Return Type Notation; once that lands, the Send-bound future could be
expressed without the separate trait. The pattern is developed as a concept in
recovering Send bounds.
Definition
CanSendRun is defined as:
#[cgp_component(SendRunner)]
#[async_trait]
#[derive_delegate(UseDelegate<Code>)]
#[use_type(HasErrorType.Error)]
pub trait CanSendRun<Code> {
fn send_run(
&self,
_code: PhantomData<Code>,
) -> impl Future<Output = Result<(), Error>> + Send;
}
Its attributes:
#[cgp_component]— turns the trait into a component: its argument names the provider traitSendRunnerthat implementations target and the wiring keySendRunnerComponent, whileCanSendRunstays the consumer trait callers use.#[async_trait]— the attribute CGP's async trait methods carry; it rewrites anasync fninto a lint-clean-> impl Futuremethod. Heresend_runis already written in that form so it can add the+ Sendbound thatCanRun'srunomits.#[derive_delegate]— generates aUseDelegateprovider that dispatches on theCodetype, so a context can route eachCodeto its own provider; theopenstatement is the modern sugar for the same dispatch.#[use_type]— addsHasErrorTypeas a supertrait and rewrites the bareErrorto<Self as HasErrorType>::Error.
Usage
CanSendRun is imported from cgp::extra::run, with its provider trait SendRunner and its key
SendRunnerComponent; none of them is in the prelude. Its method differs from run only in the shape of its
return, an explicit Send future rather than a plain async fn:
fn send_run(&self, _code: PhantomData<Code>) -> impl Future<Output = Result<(), Error>> + Send;
A context gains the operation by wiring SendRunnerComponent, or, in the common case, by supplying a
proxy impl on the concrete context that forwards to its own run. The proxy discharges the
Send bound:
use cgp::extra::run::{CanRun, SendRunner, SendRunnerComponent};
#[cgp_provider]
impl SendRunner<App, ActionA> for App {
async fn send_run(context: &App, code: PhantomData<ActionA>) -> Result<(), Infallible> {
context.run(code).await
}
}
Because this impl names the concrete App and ActionA, the future produced by context.run(code) has
a fully known type, so the compiler can verify it is Send and satisfy the + Send bound on
send_run, which the generic CanRun definition deliberately does not assert. A
spawning runner provider can then require Context: CanSendRun<InCode>, clone the context into a Send
future, and hand it to a spawner, all without Send bounds leaking into the abstract interfaces.
#[cgp_provider] derives the component key SendRunnerComponent from the trait name, so the key must
be in scope even though the context never wires it.
Examples
A spawning provider requires the context to be CanSendRun and hands a Send future to a spawner.
spawn stands for any function with the signature of tokio::spawn, which requires a
Send + 'static future. The context wires it as CanRun shows:
#[cgp_impl(new SpawnAndRun<InCode>: RunnerComponent)]
#[use_type(HasErrorType.Error)]
impl<Code, InCode> Runner<Code>
where
Self: 'static + Send + Clone + CanSendRun<InCode>,
{
async fn run(&self, _code: PhantomData<Code>) -> Result<(), Error> {
let context = self.clone();
spawn(async move {
let _ = context.send_run(PhantomData).await;
});
Ok(())
}
}
The spawner requires a Send + 'static future, which
context.send_run(PhantomData::<InCode>) returns, so the bound Context: CanSendRun<InCode>
makes the spawn type-check. The context wires its CanRun tasks and supplies a
SendRunner proxy for the inner task, and the Send bound is discharged only at that concrete proxy,
never on the abstract task or error types. App is an environmental context, and the task is a
type-level Code selector.
When to use it
Reach for CanSendRun when a runner's future must be Send, which in practice means whenever the
work is handed to a work-stealing spawner like tokio::spawn. A provider that spawns bounds its context
by CanSendRun<InCode> and supplies a concrete proxy for each task it spawns, which keeps the Send
requirement out of every abstract interface.
Do not reach for it when the future is never spawned across a thread boundary, where plain
CanRun is enough and needs no proxy. CanSendRun is a targeted workaround for the
Send-future limitation rather than a default: use it only where the Send bound is actually required.
Related constructs
CanRun/Runner— the base runner this proxies, without theSendrequirement.HasRuntime— the runtime a spawning runner reaches to hand off theSendfuture.HasErrorType— the supertrait supplying theSelf::Errora task fails with.#[derive_delegate]— generates the per-Codedispatch this uses.
The ideas behind it:
- Recovering
Sendbounds — restoring theSendguarantee an async trait method drops, which this component embodies. - Handlers — the effectful computation family a runner drives.
Source
CanSendRun/SendRunner, defined besideCanRun:cgp-run/src/lib.rs, reached from the facade ascgp::extra::run.- The
#[cgp_component]and#[derive_delegate]expansions it relies on:cgp-macro-core/src/
An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.