#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
mod tools;
mod types;
use std::any::{Any, TypeId, type_name};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
pub use tools::{declare_all, missing_targets, order_dump};
pub use types::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PointKey {
pub id: &'static str,
pub kind: PointKind,
pub type_id: TypeId,
pub type_name: &'static str,
}
impl PointKey {
pub fn of<P: Point>() -> PointKey {
PointKey {
id: P::ID,
kind: P::KIND,
type_id: TypeId::of::<P>(),
type_name: type_name::<P>(),
}
}
}
pub type AnyInput = Arc<dyn Any + Send + Sync>;
pub type AnyValue = Box<dyn Any + Send>;
pub type AnyListener = Arc<
dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
>;
pub type AnyLocalListener =
Rc<dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError>>;
pub type PendingWaker = Arc<dyn Fn(std::thread::ThreadId) + Send + Sync>;
pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;
pub type FreshFn = fn() -> AnyValue;
pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;
pub type BudgetSink = Arc<dyn Fn(&OverBudget) + Send + Sync>;
pub trait Bus: Send + Sync {
fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;
fn listen_any(
&self,
point: PointKey,
id: String,
opts: ListenOpts,
run: AnyListener,
) -> Result<(), Refused>;
fn listen_local_any(
&self,
point: PointKey,
id: String,
opts: ListenOpts,
run: AnyLocalListener,
) -> Result<(), Refused>;
fn run_pending(&self) -> Vec<PendingRun>;
fn add_pending_waker(&self, wake: PendingWaker);
fn unlisten(&self, point: &str, id: &str) -> bool;
fn forget(&self, owner: &str) -> usize;
fn alter_any(
&self,
point: PointKey,
input: AnyInput,
value: AnyValue,
clone: CloneFn,
) -> Altered<AnyValue>;
fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;
fn add_failure_sink(&self, sink: FailureSink);
fn points(&self) -> Vec<PointInfo>;
fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;
fn defer(&self) -> Option<&dyn Defer> {
None
}
fn timings(&self) -> Option<&dyn Timings> {
None
}
}
pub fn offers(bus: &dyn Bus, capability: Capability) -> bool {
match capability {
Capability::Defer => bus.defer().is_some(),
Capability::Timings => bus.timings().is_some(),
}
}
pub trait Timings: Send + Sync {
fn points(&self) -> Vec<PointTimings>;
fn point(&self, point: &str) -> Option<PointTimings>;
fn reset(&self);
fn add_budget_sink(&self, sink: BudgetSink);
}
impl<'a> dyn Timings + 'a {
pub fn on_over_budget(&self, sink: impl Fn(&OverBudget) + Send + Sync + 'static) {
self.add_budget_sink(Arc::new(sink));
}
}
pub trait Defer: Send + Sync {
fn ask_any(&self, point: PointKey, input: AnyInput, value: AnyValue, clone: CloneFn) -> u64;
fn drain(&self) -> Vec<PendingRun>;
fn waiting(&self) -> usize;
}
impl<'a> dyn Defer + 'a {
pub fn ask<P: Point>(&self, input: P::Input, value: P::Value) -> u64
where
P::Value: Clone,
{
self.ask_any(
PointKey::of::<P>(),
Arc::new(input),
Box::new(value),
clone_value::<P::Value>,
)
}
}
impl<B: Bus + ?Sized> Bus for Arc<B> {
fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
(**self).declare_point(point, spec)
}
fn listen_any(
&self,
point: PointKey,
id: String,
opts: ListenOpts,
run: AnyListener,
) -> Result<(), Refused> {
(**self).listen_any(point, id, opts, run)
}
fn listen_local_any(
&self,
point: PointKey,
id: String,
opts: ListenOpts,
run: AnyLocalListener,
) -> Result<(), Refused> {
(**self).listen_local_any(point, id, opts, run)
}
fn run_pending(&self) -> Vec<PendingRun> {
(**self).run_pending()
}
fn add_pending_waker(&self, wake: PendingWaker) {
(**self).add_pending_waker(wake);
}
fn unlisten(&self, point: &str, id: &str) -> bool {
(**self).unlisten(point, id)
}
fn forget(&self, owner: &str) -> usize {
(**self).forget(owner)
}
fn alter_any(
&self,
point: PointKey,
input: AnyInput,
value: AnyValue,
clone: CloneFn,
) -> Altered<AnyValue> {
(**self).alter_any(point, input, value, clone)
}
fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
(**self).collect_any(point, input, fresh)
}
fn add_failure_sink(&self, sink: FailureSink) {
(**self).add_failure_sink(sink);
}
fn points(&self) -> Vec<PointInfo> {
(**self).points()
}
fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
(**self).listeners(point)
}
fn defer(&self) -> Option<&dyn Defer> {
(**self).defer()
}
fn timings(&self) -> Option<&dyn Timings> {
(**self).timings()
}
}
fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
match value.downcast_ref::<V>() {
Some(v) => Box::new(v.clone()),
None => panic!(
"a bus implementation passed a value that is not a `{}`",
type_name::<V>()
),
}
}
fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
Box::new(V::default())
}
fn typed<P: Point>(value: AnyValue) -> P::Value {
match value.downcast::<P::Value>() {
Ok(v) => *v,
Err(_) => panic!(
"the bus returned a value of another type than `{}`'s ({})",
P::ID,
type_name::<P::Value>()
),
}
}
impl<'a> dyn Bus + 'a {
pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
self.declare_point(PointKey::of::<P>(), spec)
}
pub fn listen<P: Point>(
&self,
id: impl Into<String>,
opts: ListenOpts,
run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
) -> Result<(), Refused> {
self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
}
pub fn listen_local<P: Point>(
&self,
id: impl Into<String>,
opts: ListenOpts,
run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
) -> Result<(), Refused> {
self.listen_local_any(PointKey::of::<P>(), id.into(), opts, erase_local::<P>(run))
}
pub fn on_pending(&self, wake: impl Fn(std::thread::ThreadId) + Send + Sync + 'static) {
self.add_pending_waker(Arc::new(wake));
}
pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
where
P::Value: Clone,
{
let out = self.alter_any(
PointKey::of::<P>(),
Arc::new(input),
Box::new(value),
clone_value::<P::Value>,
);
Altered {
value: typed::<P>(out.value),
failures: out.failures,
deferred: out.deferred,
refused: out.refused,
}
}
pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
where
P::Value: Default,
{
let out = self.collect_any(
PointKey::of::<P>(),
Arc::new(input),
fresh_value::<P::Value>,
);
Collected {
parts: out
.parts
.into_iter()
.map(|(id, v)| (id, typed::<P>(v)))
.collect(),
failures: out.failures,
deferred: out.deferred,
refused: out.refused,
}
}
pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
self.add_failure_sink(Arc::new(sink));
}
}
pub fn erase<P: Point>(
run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
) -> AnyListener {
Arc::new(move |input, value| {
let Some(input) = input.downcast_ref::<P::Input>() else {
return Err(HookError::Failed(format!(
"`{}`: the input is not a `{}`",
P::ID,
type_name::<P::Input>()
)));
};
let Some(value) = value.downcast_mut::<P::Value>() else {
return Err(HookError::Failed(format!(
"`{}`: the value is not a `{}`",
P::ID,
type_name::<P::Value>()
)));
};
run(input, value)
})
}
pub fn erase_local<P: Point>(
run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + 'static,
) -> AnyLocalListener {
Rc::new(move |input, value| {
let Some(input) = input.downcast_ref::<P::Input>() else {
return Err(HookError::Failed(format!(
"`{}`: the input is not a `{}`",
P::ID,
type_name::<P::Input>()
)));
};
let Some(value) = value.downcast_mut::<P::Value>() else {
return Err(HookError::Failed(format!(
"`{}`: the value is not a `{}`",
P::ID,
type_name::<P::Value>()
)));
};
run(input, value)
})
}
#[derive(Clone, Copy, Debug)]
pub struct PointDecl {
pub id: &'static str,
pub kind: PointKind,
pub description: &'static str,
pub deadline: Option<Duration>,
pub fail_closed: bool,
pub needs: &'static [Capability],
pub budget: Option<Duration>,
key: fn() -> PointKey,
}
impl PointDecl {
pub const fn of<P: Point>(description: &'static str) -> PointDecl {
PointDecl {
id: P::ID,
kind: P::KIND,
description,
deadline: None,
fail_closed: false,
needs: &[],
budget: None,
key: PointKey::of::<P>,
}
}
pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
self.deadline = Some(deadline);
self
}
pub const fn fail_closed(mut self) -> PointDecl {
self.fail_closed = true;
self
}
pub const fn needs(mut self, needs: &'static [Capability]) -> PointDecl {
self.needs = needs;
self
}
pub const fn budget(mut self, budget: Duration) -> PointDecl {
self.budget = Some(budget);
self
}
pub fn key(&self) -> PointKey {
(self.key)()
}
pub fn spec(&self) -> PointSpec {
let mut spec = PointSpec::new(self.description);
spec.deadline = self.deadline;
spec.fail_closed = self.fail_closed;
spec.budget = self.budget;
spec
}
}