use std::fmt;
use std::time::Duration;
pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(1);
pub const PLUGIN_DEADLINE: Duration = Duration::from_secs(5);
pub const LAST: &str = "*";
pub const FAILED_FACT: &str = "hook.failed";
pub trait Point: 'static {
const ID: crate::PointId;
type Input: Send + Sync + 'static;
type Value: Send + 'static;
const KIND: PointKind = PointKind::Alter;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PointKind {
Request,
Event,
#[default]
Alter,
Collect,
}
impl PointKind {
pub fn as_str(self) -> &'static str {
match self {
PointKind::Request => "request",
PointKind::Event => "event",
PointKind::Alter => "alter",
PointKind::Collect => "collect",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PointSpec {
pub description: String,
pub deadline: Option<Duration>,
pub fail_closed: bool,
pub budget: Option<Duration>,
pub facets: Vec<crate::Facet>,
pub version: u32,
}
impl PointSpec {
pub fn new(description: impl Into<String>) -> PointSpec {
PointSpec {
description: description.into(),
deadline: None,
fail_closed: false,
budget: None,
facets: Vec::new(),
version: 1,
}
}
pub fn deadline(mut self, deadline: Duration) -> PointSpec {
self.deadline = Some(deadline);
self
}
pub fn fail_closed(mut self) -> PointSpec {
self.fail_closed = true;
self
}
pub fn budget(mut self, budget: Duration) -> PointSpec {
self.budget = Some(budget);
self
}
pub fn facet(mut self, facet: crate::Facet) -> PointSpec {
self.facets.push(facet);
self
}
pub fn has(&self, contract: &crate::Contract) -> bool {
self.facets.iter().any(|f| f.contract == contract)
}
pub fn version(mut self, version: u32) -> PointSpec {
self.version = version;
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ListenOpts {
pub after: Vec<String>,
pub before: Vec<String>,
pub priority: i32,
pub deadline: Option<Duration>,
pub owner: Option<String>,
pub threaded: bool,
}
impl ListenOpts {
pub fn new() -> ListenOpts {
ListenOpts::default()
}
pub fn after(mut self, id: impl Into<String>) -> ListenOpts {
self.after.push(id.into());
self
}
pub fn before(mut self, id: impl Into<String>) -> ListenOpts {
self.before.push(id.into());
self
}
pub fn last(mut self) -> ListenOpts {
if !self.after.iter().any(|a| a == LAST) {
self.after.push(LAST.to_owned());
}
self
}
pub fn is_last(&self) -> bool {
self.after.iter().any(|a| a == LAST)
}
pub fn priority(mut self, priority: i32) -> ListenOpts {
self.priority = priority;
self
}
pub fn deadline(mut self, deadline: Duration) -> ListenOpts {
self.deadline = Some(deadline);
self
}
pub fn owner(mut self, owner: impl Into<String>) -> ListenOpts {
self.owner = Some(owner.into());
self
}
pub fn threaded(mut self) -> ListenOpts {
self.threaded = true;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HookError {
Failed(String),
Refuse(String),
}
impl HookError {
pub fn failed(message: impl Into<String>) -> HookError {
HookError::Failed(message.into())
}
pub fn refuse(reason: impl Into<String>) -> HookError {
HookError::Refuse(reason.into())
}
pub fn message(&self) -> &str {
match self {
HookError::Failed(m) | HookError::Refuse(m) => m,
}
}
pub fn is_refusal(&self) -> bool {
matches!(self, HookError::Refuse(_))
}
}
impl fmt::Display for HookError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HookError::Failed(m) => f.write_str(m),
HookError::Refuse(r) => write!(f, "refused: {r}"),
}
}
}
impl std::error::Error for HookError {}
impl From<String> for HookError {
fn from(message: String) -> HookError {
HookError::Failed(message)
}
}
impl From<&str> for HookError {
fn from(message: &str) -> HookError {
HookError::Failed(message.to_owned())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FailureKind {
Error(String),
Panic(String),
Late {
deadline: Duration,
took: Option<Duration>,
},
MissingTarget(String),
TypeMismatch,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Failure {
pub point: &'static str,
pub listener: String,
pub owner: Option<String>,
pub kind: FailureKind,
}
impl Failure {
pub fn new(
point: &'static str,
listener: impl Into<String>,
owner: Option<String>,
kind: FailureKind,
) -> Failure {
Failure {
point,
listener: listener.into(),
owner,
kind,
}
}
pub fn dropped(&self) -> bool {
!matches!(self.kind, FailureKind::MissingTarget(_))
}
}
impl fmt::Display for FailureKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FailureKind::Error(m) => write!(f, "failed: {m}"),
FailureKind::Panic(m) => write!(f, "panicked: {m}"),
FailureKind::Late {
deadline,
took: Some(t),
} => write!(f, "took {t:?}, past its deadline of {deadline:?}"),
FailureKind::Late { deadline, .. } => {
write!(f, "no answer within its deadline of {deadline:?}")
}
FailureKind::MissingTarget(t) => {
write!(f, "orders itself against `{t}`, which is not there")
}
FailureKind::TypeMismatch => write!(f, "the point is registered with another type"),
}
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"hook `{}`, listener `{}`: {}",
self.point, self.listener, self.kind
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Refused {
Duplicate {
point: &'static str,
listener: String,
},
Cycle {
point: &'static str,
path: Vec<String>,
},
TypeMismatch {
point: &'static str,
},
AlreadyDeclared {
point: &'static str,
},
Threaded {
point: &'static str,
listener: String,
},
Unsupported {
point: &'static str,
contract: &'static str,
},
Contract {
point: &'static str,
contract: &'static str,
reason: String,
},
BadId {
id: String,
error: crate::IdError,
},
}
impl fmt::Display for Refused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Refused::Duplicate { point, listener } => {
write!(f, "hook `{point}` already has a listener `{listener}`")
}
Refused::Cycle { point, path } => {
write!(
f,
"hook `{point}`: listeners order each other in a cycle: {}",
path.join(" -> ")
)
}
Refused::TypeMismatch { point } => {
write!(f, "hook `{point}` is registered with another type")
}
Refused::AlreadyDeclared { point } => write!(f, "hook `{point}` is already declared"),
Refused::Threaded { point, listener } => write!(
f,
"hook `{point}`: the local listener `{listener}` runs on its own thread, not a new one"
),
Refused::Unsupported { point, contract } => write!(
f,
"hook `{point}` needs the `{contract}` contract, which this bus does not offer"
),
Refused::Contract {
point,
contract,
reason,
} => write!(
f,
"hook `{point}`: refused by the `{contract}` contract: {reason}"
),
Refused::BadId { id, error } => write!(f, "id `{id}` refused: {error}"),
}
}
}
impl std::error::Error for Refused {}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Refusal {
pub point: &'static str,
pub listener: String,
pub owner: Option<String>,
pub reason: String,
pub failed: bool,
}
impl Refusal {
pub fn new(
point: &'static str,
listener: impl Into<String>,
owner: Option<String>,
reason: impl Into<String>,
) -> Refusal {
Refusal {
point,
listener: listener.into(),
owner,
reason: reason.into(),
failed: false,
}
}
pub fn from_failure(failure: &Failure) -> Refusal {
let reason = match &failure.kind {
FailureKind::Error(m) | FailureKind::Panic(m) => m.clone(),
kind => kind.to_string(),
};
Refusal {
point: failure.point,
listener: failure.listener.clone(),
owner: failure.owner.clone(),
reason,
failed: true,
}
}
}
impl fmt::Display for Refusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.failed {
write!(
f,
"hook `{}`: refused, `{}` failed: {}",
self.point, self.listener, self.reason
)
} else {
write!(
f,
"hook `{}`: refused by `{}`: {}",
self.point, self.listener, self.reason
)
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Altered<V> {
pub value: V,
pub failures: Vec<Failure>,
pub deferred: Vec<String>,
pub refused: Option<Refusal>,
}
impl<V> Altered<V> {
pub fn new(value: V) -> Altered<V> {
Altered {
value,
failures: Vec::new(),
deferred: Vec::new(),
refused: None,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Collected<V> {
pub parts: Vec<(String, V)>,
pub failures: Vec<Failure>,
pub deferred: Vec<String>,
pub refused: Option<Refusal>,
}
impl<V> Collected<V> {
pub fn new() -> Collected<V> {
Collected {
parts: Vec::new(),
failures: Vec::new(),
deferred: Vec::new(),
refused: None,
}
}
}
impl<V> Default for Collected<V> {
fn default() -> Collected<V> {
Collected::new()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PendingRun {
pub point: &'static str,
pub ran: Vec<String>,
pub failures: Vec<Failure>,
pub refused: Option<Refusal>,
pub ask: Option<u64>,
}
impl PendingRun {
pub fn new(point: &'static str) -> PendingRun {
PendingRun {
point,
ran: Vec::new(),
failures: Vec::new(),
refused: None,
ask: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ListenerInfo {
pub id: String,
pub owner: Option<String>,
pub after: Vec<String>,
pub before: Vec<String>,
pub priority: i32,
pub deadline: Duration,
pub threaded: bool,
pub local: bool,
pub missing: Vec<String>,
pub runs: u64,
pub failures: u64,
pub last_failure: Option<String>,
}
impl ListenerInfo {
pub fn new(id: impl Into<String>) -> ListenerInfo {
ListenerInfo {
id: id.into(),
owner: None,
after: Vec::new(),
before: Vec::new(),
priority: 0,
deadline: DEFAULT_DEADLINE,
threaded: false,
local: false,
missing: Vec::new(),
runs: 0,
failures: 0,
last_failure: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PointInfo {
pub id: &'static str,
pub kind: PointKind,
pub description: String,
pub declared: bool,
pub deadline: Duration,
pub fail_closed: bool,
pub budget: Option<Duration>,
pub facets: Vec<crate::Facet>,
pub version: u32,
pub listeners: Vec<ListenerInfo>,
}
impl PointInfo {
pub fn new(id: &'static str, kind: PointKind) -> PointInfo {
PointInfo {
id,
kind,
description: String::new(),
declared: false,
deadline: DEFAULT_DEADLINE,
fail_closed: false,
budget: None,
facets: Vec::new(),
version: 1,
listeners: Vec::new(),
}
}
}