AsyncComputer
The asynchronous, infallible member of the handler family: a Computer that
awaits.
Overview
In Context-Generic Programming (CGP), AsyncComputer is for computations that must await
but still cannot fail. CGP enables pluggable trait implementations in Rust, and AsyncComputer is
the component that lets a context plug in an async computation. Reading a value that is
already in memory is a Computer; awaiting a timer, or a channel that always
yields a value, is an AsyncComputer. It turns an Input into an Output under a phantom Code
tag, against a context (the type the implementation runs
against), and its async method returns the Output directly rather than a Result.
It sits between Computer, which drops the asynchrony, and
Handler, which adds a failure path to it. Like the synchronous computer it never
names an error type, so it does not have HasErrorType as a
supertrait. See the handler family overview for
how the members relate and promote.
Definition
CanComputeAsync is defined as:
#[async_trait]
#[cgp_component(AsyncComputer)]
#[prefix(@cgp.extra.handler in DefaultNamespace)]
#[derive_delegate(UseDelegate<Code>)]
#[derive_delegate(UseInputDelegate<Input>)]
pub trait CanComputeAsync<Code, Input> {
type Output;
async fn compute_async(&self, _code: PhantomData<Code>, input: Input) -> Self::Output;
}
Its attributes:
#[async_trait]— rewrites theasync fninto a method returning-> impl Future, the lint-clean, allocation-free form, which adds noSendbound to the future.#[cgp_component]— turns the trait into a component: its argument names the provider traitAsyncComputerthat implementations target and the wiring keyAsyncComputerComponent, whileCanComputeAsyncstays the consumer trait callers use.#[prefix]— registers the component inDefaultNamespaceunder the path@cgp.extra.handler, so a context that joins that namespace binds its provider at@cgp.extra.handler.AsyncComputerComponentrather than at the bare key.#[derive_delegate]— generates the legacyUseDelegateandUseInputDelegateproviders, which dispatch on theCodetag and on theInputtype through an inner table; theopenstatement replaces both, dispatching on either parameter or on the pair.
Usage
AsyncComputer, AsyncComputerComponent, and the consumer trait CanComputeAsync are imported
from cgp::extra::handler. The method is async and
takes the input by value:
async fn compute_async(&self, _code: PhantomData<Code>, input: Input) -> Self::Output;
A context gains the operation by wiring AsyncComputerComponent to a provider, and the component
dispatches on both the Code tag and the Input type. A provider comes from one of four places:
- A hand-written provider declares
async fn compute_asyncin its impl, as the example below does. PromoteAsync<P>, imported fromcgp::extra::handler, runs a synchronousComputerPinside the async method, soAsyncComputerComponent: PromoteAsync<Double>answerscompute_asyncfrom aDoublecomputer.#[cgp_computer]implementsAsyncComputerdirectly for anasync fn, and reaches it through promotion for a synchronous one.UseField<Tag>forwards the computation to the value stored in the context'sTagfield, which must itself implementCanComputeAsync.
Its by-reference sibling is AsyncComputerRef.
Examples
An async computer provider, wired into a context and awaited through the consumer trait:
use core::marker::PhantomData;
use cgp::extra::handler::{AsyncComputer, AsyncComputerComponent};
use cgp::prelude::*;
use cgp::extra::handler::CanComputeAsync;
#[cgp_new_provider]
impl<Context, Code> AsyncComputer<Context, Code, u64> for DoubleAsync {
type Output = u64;
async fn compute_async(_context: &Context, _code: PhantomData<Code>, input: u64) -> u64 {
input * 2
}
}
pub struct App;
delegate_components! {
App {
AsyncComputerComponent: DoubleAsync,
}
}
check_components! {
App {
AsyncComputerComponent: ((), u64),
}
}
pub async fn run(app: &App) -> u64 {
app.compute_async(PhantomData::<()>, 21).await // 42
}
DoubleAsync implements the provider trait with an async fn, so a real provider could await
inside it. App is an environmental context, and
the component is parameter-targeted:
the computation acts on the Input, while App decides the provider. The future run returns
needs an executor to run it, which CGP leaves to the application.
When to use it
Reach for AsyncComputer for a computation that awaits but cannot fail. A computation that only
reads its input fits the by-reference AsyncComputerRef better.
Reach for Computer instead when nothing needs awaiting, since PromoteAsync
lifts a synchronous computer into an AsyncComputer and the computer stays usable in the
synchronous positions too. Reach for Handler when the computation can also fail.
Implement whichever single member fits and let the wiring promote it.
Related constructs
Computer— the synchronous counterpart; promotes into this.AsyncComputerRef— the by-reference variant of this component.Handler— adds a failure path to the asynchrony.#[async_trait]— the attribute that rewrites itsasync fn.#[cgp_computer]— builds a provider that answers this, directly or through promotion.- Handler combinators —
PromoteAsyncand the promotion bundles.
The ideas behind it:
- Handlers — the computation family and its sync, async, fallible, and input-passing axes.
- Recovering
Sendbounds — restoring theSendguarantee the async method does not carry.
Source
AsyncComputerandAsyncComputerRef, and theUseFieldasync computer:async_computer.rsPromoteAsync:promote_async.rs- Re-exported through
cgp::extra::handler.
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.