Skip to main content

bast3st_eval/evaluation/
single_evaluation.rs

1use std::{borrow::Cow, collections::BTreeMap, fmt::Display, str::FromStr, sync::Arc};
2
3use derive_more::{Display, From};
4use either::Either;
5use itertools::Itertools;
6use reqwest::Url;
7use serde::{Deserialize, Serialize};
8
9use crate::{
10    Features, LogPfx,
11    catchable::cerr,
12    evaluation::{RequiredFeatures, SelectableSource},
13    helpers::NoError,
14    spec::{
15        EndThisTestAction, Entity, EntityId, FatalError, InnerNetworkRequest, Machine,
16        MissingValue, NetworkRequest, NetworkResponse, NoticeAction, RuntimeAction, RuntimeAny,
17        Selector, SpecializeFrom, Text, UnfinishedMachine,
18    },
19};
20
21pub struct EvaluationRunning(());
22pub struct EvaluationFinished(());
23pub struct EvaluationFinishedOrCancelled(());
24
25pub type AllowNetData = (Url, InnerNetworkRequest);
26pub type AllowedNetClosure =
27    Arc<dyn Fn(AllowNetData) -> Result<AllowNetData, (AllowNetData, cerr)> + Send + Sync>;
28
29#[derive(derive_more::Debug)]
30pub struct SingleEvaluation<'e, 's, S, EvalStatus> {
31    log_pfx: LogPfx,
32    entities: &'e BTreeMap<EntityId, Entity>,
33    selectable: &'s S,
34    entry_point: EntityId,
35    allowed_features: Features,
36    values: BTreeMap<EntityId, RuntimeAny>,
37    machines: BTreeMap<EntityId, Machine<RuntimeAny>>,
38    id_stack: Vec<EntityId>,
39    actions: Vec<RuntimeAction>,
40    further_steps_and_no_early_termination: Result<bool, AnyEvalTermination>,
41    used_features: Features,
42    #[debug("allowed_network: ...")]
43    allowed_network: AllowedNetClosure,
44    _phantom: std::marker::PhantomData<EvalStatus>,
45}
46
47#[derive(
48    Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, thiserror::Error, Serialize, Deserialize,
49)]
50#[error("entry point id {_0} not in entity set")]
51pub struct EntryPointMissing(EntityId);
52
53#[derive(Debug, PartialEq, PartialOrd, Clone, thiserror::Error, Serialize, Deserialize)]
54#[serde(rename_all = "kebab-case")]
55pub enum SingleEvaluationError<Extra: Display = NoError> {
56    #[error("missing entity/final value: {_0}")]
57    EntryPoint(#[from] EntryPointMissing),
58    #[error("catchable: {_0:?}")]
59    #[serde(with = "bitflags::serde")]
60    Cerr(cerr),
61    #[error("fatal: {_0:?}")]
62    Fatal(#[from] FatalError),
63    #[error("other: {_0}")]
64    Extra(Extra),
65}
66
67impl<'e, 's, S: SelectableSource> SingleEvaluation<'e, 's, S, EvaluationFinished> {
68    pub fn one_specialized<T: SpecializeFrom>(
69        &self,
70    ) -> Result<T, SingleEvaluationError<EvalSignal>> {
71        match self.maybe_specialized_value::<T>() {
72            Ok(Some(normal)) => Ok(normal.into_owned()),
73            // This situation should never occur as `run_to_end` *should* compute
74            // the value (or create an error), so no extra variant is used.
75            Ok(None) => Err(SingleEvaluationError::EntryPoint(EntryPointMissing(
76                self.entry_point,
77            ))),
78            Err(Either::Left(catchable)) => Err(SingleEvaluationError::Cerr(catchable)),
79            Err(Either::Right(AnyEvalTermination::Fatal(fatal))) => {
80                Err(SingleEvaluationError::Fatal(fatal))
81            }
82            Err(Either::Right(AnyEvalTermination::End(end))) => {
83                Err(SingleEvaluationError::Extra(end))
84            }
85        }
86    }
87}
88
89impl<'e, 's, S: SelectableSource> SingleEvaluation<'e, 's, S, EvaluationFinishedOrCancelled> {
90    pub fn one_specialized<T: SpecializeFrom>(
91        &self,
92    ) -> Result<Either<EvalSignal, T>, SingleEvaluationError> {
93        match self.maybe_specialized_value::<T>() {
94            Ok(Some(normal)) => Ok(Either::Right(normal.into_owned())),
95            // This situation should never occur as `run_to_end` *should* compute
96            // the value (or create an error), so no extra variant is used.
97            Ok(None) => Err(SingleEvaluationError::EntryPoint(EntryPointMissing(
98                self.entry_point,
99            ))),
100            Err(Either::Left(catchable)) => Err(SingleEvaluationError::Cerr(catchable)),
101            Err(Either::Right(AnyEvalTermination::Fatal(fatal))) => {
102                Err(SingleEvaluationError::Fatal(fatal))
103            }
104            Err(Either::Right(AnyEvalTermination::End(end))) => Ok(Either::Left(end)),
105        }
106    }
107}
108
109impl<'e, 's, S: SelectableSource, X> SingleEvaluation<'e, 's, S, X> {
110    pub fn maybe_specialized_value<T: SpecializeFrom>(
111        &self,
112    ) -> Result<Option<Cow<'_, T>>, Either<cerr, AnyEvalTermination>> {
113        if let Some(val) = self.value().map_err(Either::Right)? {
114            let specialized = T::specialize_from(Cow::Borrowed(val));
115            specialized.map_err(Either::Left).map(Some)
116        } else {
117            Ok(None)
118        }
119    }
120
121    pub fn value(&self) -> Result<Option<&RuntimeAny>, AnyEvalTermination> {
122        self.further_steps_and_no_early_termination.clone()?;
123        Ok(self.values.get(&self.entry_point))
124    }
125    pub fn into_actions(self) -> Vec<RuntimeAction> {
126        self.actions
127    }
128
129    pub fn all_values(&self) -> &BTreeMap<EntityId, RuntimeAny> {
130        &self.values
131    }
132}
133
134impl<'e, 's, S: SelectableSource> SingleEvaluation<'e, 's, S, EvaluationRunning> {
135    pub fn new(
136        log_pfx: LogPfx,
137        entities: &'e BTreeMap<EntityId, Entity>,
138        entry_point: EntityId,
139        selectable_data: &'s S,
140        allowed_features: Features,
141        allowed_network: AllowedNetClosure,
142    ) -> Result<Self, EntryPointMissing> {
143        if entities.contains_key(&entry_point) {
144            Ok(Self {
145                log_pfx,
146                entities,
147                entry_point,
148                selectable: selectable_data,
149                values: Default::default(),
150                machines: Default::default(),
151                id_stack: vec![entry_point],
152                further_steps_and_no_early_termination: Ok(true),
153                actions: Default::default(),
154                used_features: Features::empty(),
155                allowed_features,
156                allowed_network,
157                _phantom: Default::default(),
158            })
159        } else {
160            Err(EntryPointMissing(entry_point))
161        }
162    }
163    pub fn extract_notice(&mut self) -> Vec<NoticeAction> {
164        let (left, right) = std::mem::take(&mut self.actions)
165            .into_iter()
166            .partition_map(|act| match act {
167                RuntimeAction::Notice(n) => Either::Left(n),
168                x => Either::Right(x),
169            });
170
171        self.actions = right;
172        left
173    }
174
175    /// Run the next step if there is one and return (as bool) if
176    /// there was a step to execute.
177    ///
178    /// - `Ok(true)`: There was something to do
179    /// - `Ok(false)`: Computation finished
180    /// - `Err(fatal)`: Something really bad happened
181    pub async fn run_step(&mut self) -> Result<bool, AnyEvalTermination> {
182        self.further_steps_and_no_early_termination.clone()?;
183        self.further_steps_and_no_early_termination = self._run_step().await;
184        self.further_steps_and_no_early_termination
185            .clone()
186            .inspect_err(|err| {
187                log::debug!("[{}] early termination during eval: {err:?}", self.log_pfx)
188            })
189    }
190
191    // This function doesn't mutate the state so the produced error
192    // should be saved by another part of the program
193    fn check_features(&self) -> Result<(), FatalError> {
194        if !self.allowed_features.contains(self.used_features)
195            && self.further_steps_and_no_early_termination.is_ok()
196        {
197            Err(FatalError::FeatureMissmatch {
198                required: self.used_features,
199                provided: self.allowed_features,
200            })
201        } else {
202            Ok(())
203        }
204    }
205
206    pub async fn run_to_end_without_early_return(
207        mut self,
208    ) -> (
209        Vec<NoticeAction>,
210        SingleEvaluation<'e, 's, S, EvaluationFinished>,
211    ) {
212        while self.run_step().await.is_ok_and(|x| x) {}
213        let notice = self.extract_notice();
214        let eval = SingleEvaluation {
215            log_pfx: self.log_pfx,
216            entities: self.entities,
217            selectable: self.selectable,
218            entry_point: self.entry_point,
219            allowed_features: self.allowed_features,
220            values: self.values,
221            machines: self.machines,
222            id_stack: self.id_stack,
223            actions: self.actions,
224            further_steps_and_no_early_termination: self.further_steps_and_no_early_termination,
225            used_features: self.used_features,
226            allowed_network: self.allowed_network,
227            _phantom: Default::default(),
228        };
229
230        log::debug!(
231            "[{}] evaluation with forbidden early return reached final result {:?}",
232            eval.log_pfx,
233            eval.value()
234        );
235        (notice, eval)
236    }
237
238    pub async fn run_to_end_with_early_return(
239        mut self,
240    ) -> (
241        Vec<NoticeAction>,
242        SingleEvaluation<'e, 's, S, EvaluationFinishedOrCancelled>,
243    ) {
244        while self.run_step().await.is_ok_and(|x| x) {}
245        let notice = self.extract_notice();
246
247        let eval = SingleEvaluation {
248            log_pfx: self.log_pfx,
249            entities: self.entities,
250            selectable: self.selectable,
251            entry_point: self.entry_point,
252            allowed_features: self.allowed_features,
253            values: self.values,
254            machines: self.machines,
255            id_stack: self.id_stack,
256            actions: self.actions,
257            further_steps_and_no_early_termination: self.further_steps_and_no_early_termination,
258            used_features: self.used_features,
259            allowed_network: self.allowed_network,
260            _phantom: Default::default(),
261        };
262        log::debug!(
263            "[{}] evaluation with allowed early return reached final result {:?}",
264            eval.log_pfx,
265            eval.value()
266        );
267        (notice, eval)
268    }
269    async fn get_selector_value(
270        &mut self,
271        selector: &Selector,
272    ) -> Result<Cow<'s, RuntimeAny>, FatalError> {
273        self.selectable
274            .request(selector, self.allowed_features)
275            .await
276    }
277    async fn run_network_task(
278        &mut self,
279        task: NetworkRequest,
280    ) -> Result<Result<NetworkResponse, cerr>, FatalError> {
281        let server = task.server().trim_end_matches('/');
282        let route = task.route().trim_start_matches('/');
283        let string_url = format!("{server}/{route}");
284
285        type ParseError = <reqwest::Url as FromStr>::Err;
286        let url: Result<reqwest::Url, ParseError> = string_url.parse();
287
288        let url = url.or_else(|err| {
289            if err == ParseError::RelativeUrlWithoutBase {
290                let url: Result<reqwest::Url, ParseError> =
291                    format!("https://{server}/{route}").parse();
292                log::debug!(
293                    "[{}] original url had no base, adding https:// resulted in {url:?}",
294                    self.log_pfx
295                );
296                url
297            } else {
298                Err(err)
299            }
300        });
301
302        log::info!(
303            "[{}] parsed server={server:?}, route={route:?} to url={url:?}",
304            self.log_pfx
305        );
306
307        let url = match url {
308            Ok(url) => url,
309            Err(_) => {
310                self.actions
311                    .push(RuntimeAction::Notice(NoticeAction::Network {
312                        url: Err((task.server().clone(), task.route().clone())),
313                        request: task.into_specific(),
314                        response: Err(cerr::network_url_syntax),
315                    }));
316                return Ok(Err(cerr::network_url_syntax));
317            }
318        };
319        let specific = task.into_specific();
320        log::debug!(
321            "[{}] find out if network is allowed: {url:?}, {specific:?}",
322            self.log_pfx
323        );
324
325        let decision = (self.allowed_network)((url, specific));
326        let (info, response) = match decision {
327            Err((info, err)) => (info, Err(err)),
328            Ok((url, specific)) => match &specific {
329                InnerNetworkRequest::Get => {
330                    log::debug!("[{}] start network GET {url}", self.log_pfx);
331                    let r = reqwest::get(url.clone()).await.map_err(Text::from_debug);
332                    ((url, specific), Ok(r))
333                }
334                InnerNetworkRequest::Post { json } => match reqwest::Client::builder().build() {
335                    Err(err) => ((url, specific), Ok(Err(Text::from_debug(err)))),
336                    Ok(client) => {
337                        let json: BTreeMap<_, _> = json
338                            .as_ref()
339                            .map(|x| BTreeMap::from_iter(x.iter().cloned()))
340                            .unwrap_or_default();
341                        log::debug!("[{}] start network POST {url} {json:?}", self.log_pfx);
342                        let r = client
343                            .post(url.clone())
344                            .json(&json)
345                            .send()
346                            .await
347                            .map_err(Text::from_debug);
348                        ((url, specific), Ok(r))
349                    }
350                },
351            },
352        };
353        let response: Result<Result<NetworkResponse, Text>, cerr> = match response {
354            Err(e) => {
355                log::info!(
356                    "[{}] network request to s_url={string_url:?} failed or was forbidden: {e:?}",
357                    self.log_pfx
358                );
359                Err(e)
360            }
361            Ok(Ok(o)) => {
362                log::debug!(
363                    "[{}] network request to s_url={string_url:?} returned: {o:?}",
364                    self.log_pfx
365                );
366                let resp = NetworkResponse::new(o).await;
367                log::info!(
368                    "[{}] network request to s_url={string_url:?} resulted in parsed: {resp:?}",
369                    self.log_pfx
370                );
371                resp.map(Ok)
372            }
373            Ok(Err(e)) => {
374                log::info!(
375                    "[{}] network request to s_url={string_url:?} was allowed but failed: {e}",
376                    self.log_pfx
377                );
378                Ok(Err(e))
379            }
380        };
381        let return_value = response
382            .clone()
383            .and_then(|x| x.map_err(|_| cerr::network_external));
384
385        self.actions
386            .push(RuntimeAction::Notice(NoticeAction::Network {
387                url: Ok(info.0.to_string().into()),
388                request: info.1,
389                response,
390            }));
391        Ok(return_value)
392    }
393
394    async fn _run_step(&mut self) -> Result<bool, AnyEvalTermination> {
395        if let Some(current) = self.id_stack.last().cloned() {
396            if self.values.contains_key(&current) {
397                self.id_stack.pop();
398                return Ok(true);
399            }
400
401            let entity = self
402                .entities
403                .get(&current)
404                .ok_or(FatalError::EntityNotFound(current))?;
405            /*
406            log::trace!(
407                "[{}] run step for entity {current}: {entity:?}",
408                self.log_pfx
409            );*/
410
411            let machine: Machine<RuntimeAny> = self
412                .machines
413                .remove(&current)
414                .unwrap_or_else(|| entity.machine());
415            match machine.big_red_and_btn() {
416                Either::Left(finished) => {
417                    let value = match finished? {
418                        Ok((finished, meta)) => {
419                            self.used_features |= meta.features();
420
421                            let mut return_early = Ok(());
422                            for action in meta.into_actions() {
423                                if let RuntimeAction::EndThisTest(ref end) = action
424                                    && return_early.is_ok()
425                                {
426                                    return_early = Err(EvalSignal::EndTest(end.clone()));
427                                }
428                                self.actions.push(action);
429                            }
430                            self.check_features()?;
431                            return_early?;
432                            finished
433                        }
434                        Err(err) => RuntimeAny::Catchable(err),
435                    };
436                    log::trace!("[{}] evaluated {} to {:?}", self.log_pfx, current, value);
437                    self.values.insert(current, value);
438                }
439                Either::Right(UnfinishedMachine::Missing(m)) => {
440                    let missing_value = m.missing_value();
441                    let new_machine = match missing_value {
442                        MissingValue::NoValueNeeded => m.call(Ok(&RuntimeAny::Value(0.into()))),
443                        MissingValue::EntityId(id) => {
444                            if let Some(delivered) = self.values.get(id) {
445                                m.call(Ok(delivered))
446                            } else {
447                                log::trace!(
448                                    "[{}] {current} requires to evaluate {id} first",
449                                    self.log_pfx
450                                );
451                                if self.id_stack.contains(id) {
452                                    Err(FatalError::CyclicIdReferences(*id))?;
453                                }
454
455                                self.id_stack.push(*id);
456                                m.delay()
457                            }
458                        }
459                        MissingValue::Selector(selector) => {
460                            self.used_features |= selector.required_features();
461                            self.check_features()?;
462                            log::trace!(
463                                "[{}] {current} requires selector {selector}",
464                                self.log_pfx
465                            );
466                            let val = self.get_selector_value(selector).await?;
467                            m.call(Ok(val.as_ref()))
468                        }
469                    };
470                    self.machines.insert(current, new_machine);
471                }
472                Either::Right(UnfinishedMachine::RegexTask(m)) => {
473                    let pattern = regex::Regex::new(m.request.requested_pattern())
474                        .map_err(|_| cerr::regex_syntax);
475                    let new_machine = (m.closure)(Cow::Owned(pattern));
476                    self.machines.insert(current, new_machine);
477                }
478                Either::Right(UnfinishedMachine::NetworkTask(m)) => {
479                    let response = self.run_network_task(m.request).await?;
480                    let new_machine = (m.closure)(Cow::Owned(response));
481                    self.machines.insert(current, new_machine);
482                }
483            }
484
485            return Ok(true);
486        }
487        Ok(false)
488    }
489}
490
491#[derive(Debug, PartialEq, From, Clone)]
492pub enum AnyEvalTermination {
493    Fatal(FatalError),
494    End(EvalSignal),
495}
496
497#[derive(Debug, Display, PartialEq, From, Clone, PartialOrd)]
498pub enum EvalSignal {
499    #[display("end-test: early return using {_0:?}")]
500    EndTest(EndThisTestAction),
501}