pub trait ReadyService {
type Ready;
// Required method
fn ready(&self) -> impl Future<Output = Self::Ready>;
}Expand description
Extend trait for Service.
Can be used to cehck the ready state of a service before calling it.
§Examples:
// a service with conditional availability based on state of Permit.
struct Foo(Permit);
// a permit reset the inner boolean to true on drop.
#[derive(Clone)]
struct Permit(Rc<Cell<bool>>);
impl Drop for Permit {
fn drop(&mut self) {
self.0.set(true);
}
}
impl Service<()> for Foo {
type Response = ();
type Error = ();
async fn call(&self, _req: ()) -> Result<Self::Response, Self::Error> {
Ok(())
}
}
impl ReadyService for Foo {
type Ready = Result<Permit, ()>;
async fn ready(&self) -> Self::Ready {
if self.0.0.get() {
// set permit to false and return with Ok<Permit>
self.0.0.set(false);
Ok(self.0.clone())
} else {
// return error is to simply the example.
// In real world this branch should be an async waiting for Permit reset to true.
Err(())
}
}
}
async fn workflow(service: &Foo) {
let permit = service.ready().await.unwrap(); // check service ready state.
service.call(()).await.unwrap(); // run Service::call when permit is held in scope.
drop(permit); // drop permit after Service::call is finished.
}
async fn throttle(service: &Foo) {
let permit = service.ready().await.unwrap();
assert!(service.ready().await.is_err()); // service is throttled because permit is still held in scope.
}Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.