bus_contract/types.rs
1//! The contract's types, shared by every implementation.
2
3use std::fmt;
4use std::time::Duration;
5
6/// The deadline of an in-process listener when neither the listener nor
7/// its point sets one.
8pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(1);
9
10/// The deadline meant for listeners that answer from another process (a
11/// plugin over RPC): give it with [`ListenOpts::deadline`] or
12/// [`PointSpec::deadline`].
13pub const PLUGIN_DEADLINE: Duration = Duration::from_secs(5);
14
15/// The `after` target that places a listener after every other listener
16/// of its point ([`ListenOpts::last`]): one per point, a second is
17/// refused as a [`Refused::Cycle`] (each would run after the other).
18pub const LAST: &str = "*";
19
20/// The name a host gives the fact it publishes for each [`Failure`] its
21/// sinks receive ([`Bus::add_failure_sink`](crate::Bus::add_failure_sink)).
22pub const FAILED_FACT: &str = "hook.failed";
23
24/// A hook point: one type per point, so its input and value are checked
25/// at compile time. Declared by the crate that owns the result.
26///
27/// Every listener of a point has the same shape: it reads the emit's
28/// [`Input`](Point::Input) and edits a [`Value`](Point::Value). An
29/// [`alter`](crate::Bus::alter_any) emit passes one value through the listeners
30/// in order; a [`collect`](crate::Bus::collect_any) emit gives each listener a
31/// fresh value and gathers them in a list.
32pub trait Point: 'static {
33 /// The point's id, dotted by convention (`health.report`).
34 const ID: &'static str;
35 /// What every listener reads: shared, never changed by a listener.
36 type Input: Send + Sync + 'static;
37 /// What a listener edits: the value altered in turn, or one
38 /// listener's contribution to a collect.
39 type Value: Send + 'static;
40 /// What the point is for ([`PointKind`]); [`PointKind::Alter`] unless
41 /// the point says otherwise.
42 const KIND: PointKind = PointKind::Alter;
43}
44
45/// What a point is for: declared, for introspection and review, not
46/// enforced (a request is an alter emit over the request's input).
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
48#[non_exhaustive]
49pub enum PointKind {
50 /// A request (`<noun>.<verb>`): its listeners do the work in their
51 /// declared order; the value is what each did.
52 Request,
53 /// An event's listeners: each event delivered once, in journal order.
54 Event,
55 /// One value passed through the listeners in turn.
56 #[default]
57 Alter,
58 /// Each listener adds its own part.
59 Collect,
60}
61
62impl PointKind {
63 /// The kind as introspection writes it (`request`).
64 pub fn as_str(self) -> &'static str {
65 match self {
66 PointKind::Request => "request",
67 PointKind::Event => "event",
68 PointKind::Alter => "alter",
69 PointKind::Collect => "collect",
70 }
71 }
72}
73
74/// A point's declaration: its description and limits, for introspection.
75#[derive(Clone, Debug, Default, PartialEq, Eq)]
76pub struct PointSpec {
77 /// What the point builds, for people and agents reading
78 /// [`Bus::points`](crate::Bus::points).
79 pub description: String,
80 /// The deadline of the point's listeners that set none themselves;
81 /// `None` takes the kernel's default.
82 pub deadline: Option<Duration>,
83}
84
85impl PointSpec {
86 /// A point described by `description`, with the kernel's deadline.
87 pub fn new(description: impl Into<String>) -> PointSpec {
88 PointSpec {
89 description: description.into(),
90 deadline: None,
91 }
92 }
93
94 /// The deadline of the point's listeners that set none themselves.
95 pub fn deadline(mut self, deadline: Duration) -> PointSpec {
96 self.deadline = Some(deadline);
97 self
98 }
99}
100
101/// How a listener is placed and limited.
102#[derive(Clone, Debug, Default, PartialEq, Eq)]
103pub struct ListenOpts {
104 /// Listeners this one runs after.
105 pub after: Vec<String>,
106 /// Listeners this one runs before.
107 pub before: Vec<String>,
108 /// Among listeners `after`/`before` leave free, higher runs first;
109 /// ties run in registration order.
110 pub priority: i32,
111 /// Overrides the point's deadline.
112 pub deadline: Option<Duration>,
113 /// Who registered it (a module, a plugin), for [`Bus::forget`](crate::Bus::forget) and
114 /// introspection.
115 pub owner: Option<String>,
116 /// Runs on a thread of its own, so the emit stops waiting at the
117 /// deadline. An inline listener (the default) runs on the emitting
118 /// thread: it cannot be stopped, and only counts as late once it
119 /// returns. A local listener runs inline on its own thread: it is
120 /// refused with this set ([`Refused::Threaded`]).
121 pub threaded: bool,
122}
123
124impl ListenOpts {
125 /// No constraint, priority 0, the point's deadline, inline.
126 pub fn new() -> ListenOpts {
127 ListenOpts::default()
128 }
129
130 /// Runs after the listener `id` (a missing one is reported and
131 /// ignored).
132 pub fn after(mut self, id: impl Into<String>) -> ListenOpts {
133 self.after.push(id.into());
134 self
135 }
136
137 /// Runs before the listener `id` (a missing one is reported and
138 /// ignored).
139 pub fn before(mut self, id: impl Into<String>) -> ListenOpts {
140 self.before.push(id.into());
141 self
142 }
143
144 /// Runs after every other listener of its point, whatever they
145 /// declare: an invariants check, a listener that reads what all the
146 /// others left. One per point: a second one closes a cycle and is
147 /// refused ([`Refused::Cycle`]). Kept in [`ListenOpts::after`] as
148 /// [`LAST`].
149 pub fn last(mut self) -> ListenOpts {
150 if !self.after.iter().any(|a| a == LAST) {
151 self.after.push(LAST.to_owned());
152 }
153 self
154 }
155
156 /// Whether the listener runs after every other one of its point
157 /// ([`ListenOpts::last`]).
158 pub fn is_last(&self) -> bool {
159 self.after.iter().any(|a| a == LAST)
160 }
161
162 /// Higher runs first among listeners left free by `after`/`before`.
163 pub fn priority(mut self, priority: i32) -> ListenOpts {
164 self.priority = priority;
165 self
166 }
167
168 /// Overrides the point's deadline.
169 pub fn deadline(mut self, deadline: Duration) -> ListenOpts {
170 self.deadline = Some(deadline);
171 self
172 }
173
174 /// Who registered the listener.
175 pub fn owner(mut self, owner: impl Into<String>) -> ListenOpts {
176 self.owner = Some(owner.into());
177 self
178 }
179
180 /// Runs on a thread of its own, so a slow listener cannot hold the
181 /// emit past its deadline.
182 pub fn threaded(mut self) -> ListenOpts {
183 self.threaded = true;
184 self
185 }
186}
187
188/// The error a listener returns.
189#[derive(Clone, Debug, PartialEq, Eq)]
190pub struct HookError(pub String);
191
192impl fmt::Display for HookError {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 f.write_str(&self.0)
195 }
196}
197
198impl std::error::Error for HookError {}
199
200impl From<String> for HookError {
201 fn from(message: String) -> HookError {
202 HookError(message)
203 }
204}
205
206impl From<&str> for HookError {
207 fn from(message: &str) -> HookError {
208 HookError(message.to_owned())
209 }
210}
211
212/// What went wrong with one listener during an emit.
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub enum FailureKind {
215 /// The listener returned an error.
216 Error(String),
217 /// The listener panicked; the panic's message.
218 Panic(String),
219 /// The listener missed its deadline. `took` is its time when it
220 /// returned late (inline); `None` when the emit stopped waiting
221 /// (threaded).
222 Late {
223 /// The deadline it had.
224 deadline: Duration,
225 /// How long it ran, when it returned.
226 took: Option<Duration>,
227 },
228 /// An `after` or `before` constraint names a listener that is not
229 /// registered. The listener still ran and its contribution counts;
230 /// only the constraint was ignored. Not sent to the failure sinks.
231 MissingTarget(String),
232 /// The point id is registered with another [`Point`] type; no
233 /// listener ran. `listener` is `*`.
234 TypeMismatch,
235}
236
237/// One listener's failure: its contribution was dropped (except for a
238/// [`FailureKind::MissingTarget`]), the other listeners ran.
239#[derive(Clone, Debug, PartialEq, Eq)]
240pub struct Failure {
241 /// The point emitted.
242 pub point: &'static str,
243 /// The listener's id.
244 pub listener: String,
245 /// The listener's owner.
246 pub owner: Option<String>,
247 /// What went wrong.
248 pub kind: FailureKind,
249}
250
251impl Failure {
252 /// Whether the failure dropped a contribution: everything but a
253 /// missing ordering target. Only these reach the failure sinks.
254 pub fn dropped(&self) -> bool {
255 !matches!(self.kind, FailureKind::MissingTarget(_))
256 }
257}
258
259impl fmt::Display for Failure {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 write!(f, "hook `{}`, listener `{}`: ", self.point, self.listener)?;
262 match &self.kind {
263 FailureKind::Error(m) => write!(f, "failed: {m}"),
264 FailureKind::Panic(m) => write!(f, "panicked: {m}"),
265 FailureKind::Late {
266 deadline,
267 took: Some(t),
268 } => write!(f, "took {t:?}, past its deadline of {deadline:?}"),
269 FailureKind::Late { deadline, .. } => {
270 write!(f, "no answer within its deadline of {deadline:?}")
271 }
272 FailureKind::MissingTarget(t) => {
273 write!(f, "orders itself against `{t}`, which is not there")
274 }
275 FailureKind::TypeMismatch => write!(f, "the point is registered with another type"),
276 }
277 }
278}
279
280/// Why a declaration or a listener was refused. Nothing was changed.
281#[derive(Clone, Debug, PartialEq, Eq)]
282pub enum Refused {
283 /// The point already has a listener with this id.
284 Duplicate {
285 /// The point.
286 point: &'static str,
287 /// The id taken.
288 listener: String,
289 },
290 /// The listener's `after`/`before` would close a cycle: these
291 /// listeners, each to run before the next, the first again at the
292 /// end.
293 Cycle {
294 /// The point.
295 point: &'static str,
296 /// The listeners in the cycle.
297 path: Vec<String>,
298 },
299 /// The point id is already registered with another [`Point`] type.
300 TypeMismatch {
301 /// The point.
302 point: &'static str,
303 },
304 /// The point was already declared.
305 AlreadyDeclared {
306 /// The point.
307 point: &'static str,
308 },
309 /// A local listener asked for a thread of its own
310 /// ([`ListenOpts::threaded`]); it runs on the thread that registered
311 /// it.
312 Threaded {
313 /// The point.
314 point: &'static str,
315 /// The listener.
316 listener: String,
317 },
318}
319
320impl fmt::Display for Refused {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 match self {
323 Refused::Duplicate { point, listener } => {
324 write!(f, "hook `{point}` already has a listener `{listener}`")
325 }
326 Refused::Cycle { point, path } => {
327 write!(
328 f,
329 "hook `{point}`: listeners order each other in a cycle: {}",
330 path.join(" -> ")
331 )
332 }
333 Refused::TypeMismatch { point } => {
334 write!(f, "hook `{point}` is registered with another type")
335 }
336 Refused::AlreadyDeclared { point } => write!(f, "hook `{point}` is already declared"),
337 Refused::Threaded { point, listener } => write!(
338 f,
339 "hook `{point}`: the local listener `{listener}` runs on its own thread, not a new one"
340 ),
341 }
342 }
343}
344
345impl std::error::Error for Refused {}
346
347/// The result of an [`alter`](crate::Bus::alter_any) emit.
348#[derive(Debug)]
349pub struct Altered<V> {
350 /// The value after every listener that succeeded.
351 pub value: V,
352 /// Every failure, in listener order.
353 pub failures: Vec<Failure>,
354 /// The local listeners bound to another thread, in order: queued for
355 /// that thread's [`run_pending`](crate::Bus::run_pending), not run
356 /// by this emit.
357 pub deferred: Vec<String>,
358}
359
360/// The result of a [`collect`](crate::Bus::collect_any) emit.
361#[derive(Debug)]
362pub struct Collected<V> {
363 /// Each successful listener's value, in listener order, with its id.
364 pub parts: Vec<(String, V)>,
365 /// Every failure, in listener order.
366 pub failures: Vec<Failure>,
367 /// The local listeners bound to another thread, in order: queued for
368 /// that thread's [`run_pending`](crate::Bus::run_pending), not run
369 /// by this emit.
370 pub deferred: Vec<String>,
371}
372
373/// What one emit's deferred local listeners did when their thread ran
374/// them ([`Bus::run_pending`](crate::Bus::run_pending)).
375#[derive(Clone, Debug, PartialEq, Eq)]
376pub struct PendingRun {
377 /// The point emitted.
378 pub point: &'static str,
379 /// The listeners that ran, in order (a listener removed since the
380 /// emit is not run).
381 pub ran: Vec<String>,
382 /// Their failures, in listener order.
383 pub failures: Vec<Failure>,
384}
385
386/// A listener as introspection shows it.
387#[derive(Clone, Debug, PartialEq, Eq)]
388pub struct ListenerInfo {
389 /// Its id.
390 pub id: String,
391 /// Its owner.
392 pub owner: Option<String>,
393 /// The listeners it runs after.
394 pub after: Vec<String>,
395 /// The listeners it runs before.
396 pub before: Vec<String>,
397 /// Its priority.
398 pub priority: i32,
399 /// The deadline it gets: its own, else its point's, else the kernel's.
400 pub deadline: Duration,
401 /// Whether it runs on a thread of its own.
402 pub threaded: bool,
403 /// Whether it is a local listener, bound to the thread that
404 /// registered it.
405 pub local: bool,
406 /// The `after`/`before` targets that are not registered.
407 pub missing: Vec<String>,
408 /// How many times it ran.
409 pub runs: u64,
410 /// How many of those runs failed (contribution dropped).
411 pub failures: u64,
412 /// The last failure, as text.
413 pub last_failure: Option<String>,
414}
415
416/// A point as introspection shows it.
417#[derive(Clone, Debug, PartialEq, Eq)]
418pub struct PointInfo {
419 /// Its id.
420 pub id: &'static str,
421 /// What it is for.
422 pub kind: PointKind,
423 /// Its description; empty until declared.
424 pub description: String,
425 /// Whether its owner declared it ([`Bus::declare_point`](crate::Bus::declare_point)); a point
426 /// listened to before that is not.
427 pub declared: bool,
428 /// The deadline of its listeners that set none.
429 pub deadline: Duration,
430 /// Its listeners, in the order they run.
431 pub listeners: Vec<ListenerInfo>,
432}