1use either::Either;
2use serde::{Deserialize, Serialize};
3
4use crate::{
5 Features, LogPfx,
6 evaluation::{
7 Context, Effects, SelectableSource, SingleEvaluation, SingleEvaluationError, WithNotice,
8 single_evaluation::EvalSignal,
9 },
10 spec::{ActionEntity, CriterionEntity, EntityId, HookList, RuntimeAction, RuntimeCriterion},
11};
12
13#[derive(Debug, thiserror::Error, PartialEq, PartialOrd, Clone, Serialize, Deserialize)]
14#[serde(rename_all = "kebab-case")]
15pub enum HookFailure {
16 #[error("criterion: {_0}")]
17 Criterion(SingleEvaluationError),
18 #[error("action: {_0}")]
19 Action(SingleEvaluationError),
20}
21
22pub type FallibleHookResults = Vec<Result<HookResult, HookFailure>>;
23
24#[derive(Debug, PartialEq, PartialOrd, Clone, Serialize, Deserialize)]
28pub struct HookResult {
29 pub(crate) criterion: Option<RuntimeCriterion>,
30 }
32
33impl HookList {
34 #[allow(unused)]
35 pub(crate) async fn run_all<Source: SelectableSource>(
36 &self,
37 ctx: &Context,
38 log_pfx: LogPfx,
39 eft: &mut Effects,
40 feat: Features,
41 fallback: Source,
42 ) -> (FallibleHookResults, Option<EvalSignal>) {
43 let mut tried = vec![];
44 log::debug!(
45 "[{log_pfx}] enter hook execution loop, hook count: {}",
46 self.iter().count()
47 );
48 for (index, (crit, act)) in self.iter().enumerate() {
49 match execute_hook(ctx, log_pfx.join(index), (&eft, &fallback), feat, crit, act).await {
50 Err(fail_w_notice) => {
51 let (failure, notice) = fail_w_notice.into_parts();
52 eft.extend(notice);
53 tried.push(Err(failure))
54 }
55 Ok((actions, criterion, signal)) => {
56 tried.push(Ok(HookResult { criterion }));
57 eft.extend(actions);
58
59 if let Some(signal) = signal {
60 match &signal {
61 EvalSignal::EndTest(_) => {
62 log::debug!(
63 "[{log_pfx}] early return from hook execution loop after hook number {index}",
64 );
65 return (tried, Some(signal));
66 }
67 }
68 }
69 }
70 }
71 }
72 log::trace!("[{log_pfx}] exit from hook execution loop after all hooks");
73 (tried, None)
74 }
75}
76
77async fn execute_hook<Source: SelectableSource>(
78 settings: &Context,
79 log_pfx: LogPfx,
80 outer_fallback: Source,
81 features: Features,
82 crit: EntityId<CriterionEntity>,
83 act: EntityId<ActionEntity>,
84) -> Result<
85 (
86 Vec<RuntimeAction>,
87 Option<RuntimeCriterion>,
88 Option<EvalSignal>,
89 ),
90 WithNotice<HookFailure>,
91> {
92 let mut actions = vec![];
93 let res = inner_execute_hook(
94 settings,
95 log_pfx,
96 outer_fallback,
97 features,
98 crit,
99 act,
100 &mut actions,
101 )
102 .await;
103 match res {
104 Ok((crit, sig)) => Ok((actions, crit, sig)),
105 Err(failure) => Err(WithNotice::new(
106 failure,
107 actions
108 .into_iter()
109 .flat_map(|a| match a {
110 RuntimeAction::Notice(notice) => Some(notice),
111 RuntimeAction::SendMsg(_)
112 | RuntimeAction::SetFlag(_)
113 | RuntimeAction::EndThisTest(_) => None,
114 })
115 .collect(),
116 )),
117 }
118}
119
120async fn inner_execute_hook<Source: SelectableSource>(
121 settings: &Context,
122 log_pfx: LogPfx,
123 outer_fallback: Source,
124 features: Features,
125 crit: EntityId<CriterionEntity>,
126 act: EntityId<ActionEntity>,
127 actions: &mut Vec<RuntimeAction>,
128) -> Result<(Option<RuntimeCriterion>, Option<EvalSignal>), HookFailure> {
129 let crit_eval = SingleEvaluation::new(
130 log_pfx.join("crit"),
131 settings.entities(),
132 crit.cast_id(),
133 &outer_fallback,
134 features,
135 settings.allowed_network().clone(),
136 )
137 .map_err(SingleEvaluationError::from)
138 .map_err(HookFailure::Criterion)?;
139 let (notice_actions, crit_eval) = crit_eval.run_to_end_with_early_return().await;
140 actions.extend(notice_actions.into_iter().map(RuntimeAction::Notice));
141
142 let criterion: Either<EvalSignal, RuntimeCriterion> = crit_eval
143 .one_specialized()
144 .map_err(HookFailure::Criterion)?;
145
146 let eval_signals = match criterion.clone().map_left(Some) {
147 Either::Left(eval_signals) => eval_signals,
148 Either::Right(criterion) => {
149 if criterion.is_fulfilled() {
150 let act_eval = SingleEvaluation::new(
151 log_pfx.join("act"),
152 settings.entities(),
153 act.cast_id(),
154 &outer_fallback,
155 features,
156 settings.allowed_network().clone(),
157 )
158 .map_err(SingleEvaluationError::from)
159 .map_err(HookFailure::Action)?;
160
161 let (notice_actions, act_eval) = act_eval.run_to_end_with_early_return().await;
162 actions.extend(notice_actions.into_iter().map(RuntimeAction::Notice));
163
164 let action: Either<EvalSignal, RuntimeAction> =
165 act_eval.one_specialized().map_err(HookFailure::Action)?;
166
167 actions.extend(crit_eval.into_actions());
168 actions.extend(act_eval.into_actions());
169 match action.map_left(Some) {
170 Either::Left(eval_signals) => eval_signals,
171 Either::Right(action) => {
172 actions.push(action);
173 None
174 }
175 }
176 } else {
177 None
178 }
179 }
180 };
181 Ok((criterion.right(), eval_signals))
182}