Skip to main content

vpf_runner/
record.rs

1//! What a runner keeps of a run: each step's answers, each proof with its result, the steps skipped, the
2//! person's decisions, each version of the plan, and what the run waits for, so it can go on later.
3
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use jiff::Timestamp;
8use jiff::tz::TimeZone;
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11use vpf::{Plan, Step};
12
13use crate::journal::Entry;
14use crate::person::Ask;
15
16/// How a run ended, or where it stands.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum Outcome {
19    /// The last step passed.
20    Done,
21    /// The run stopped, for this reason.
22    Stopped(String),
23    /// The run waits, holding nothing, for these answers and times. It goes on with [`crate::Runner::resume`].
24    Waiting(Vec<Waiting>),
25}
26
27/// One thing a waiting run waits for.
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Waiting {
30    /// The step that waits.
31    pub step: String,
32    /// What names the answer in the run, to give it with [`Record::reply`].
33    pub key: String,
34    /// What it waits for.
35    pub wait: Wait,
36}
37
38/// What a step waits for.
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum Wait {
42    /// A text: a person's step, or a name the plan's reference did not give.
43    Answer(Ask),
44    /// A person's approval of the work: yes, or no with the points against it.
45    Approval(Ask),
46    /// Yes or no.
47    Decision(String),
48    /// One of the options.
49    Choice {
50        /// The question.
51        question: String,
52        /// The options, in order.
53        options: Vec<String>,
54    },
55    /// A time: the step may not start before it.
56    Time(Timestamp),
57}
58
59/// A person's reply to what a run waits for.
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum Reply {
63    /// A text, for [`Wait::Answer`].
64    Text(String),
65    /// Yes, for [`Wait::Approval`] or [`Wait::Decision`].
66    Yes,
67    /// No, for [`Wait::Approval`] or [`Wait::Decision`].
68    No {
69        /// The points against the work.
70        points: String,
71        /// The earlier steps the work goes back to, among those offered.
72        back: Vec<String>,
73    },
74    /// The option chosen, counted from 0, for [`Wait::Choice`].
75    Option(usize),
76}
77
78/// One version of the plan a run followed.
79#[derive(Clone, Debug, PartialEq)]
80pub struct Version {
81    /// The plan.
82    pub plan: Plan,
83    /// Who approved it, for a version taken during the run.
84    pub approved_by: Option<String>,
85    /// The first step it was followed from, the first that had not ended.
86    pub from: Option<String>,
87    /// When it was taken.
88    pub at: Timestamp,
89}
90
91/// One proof asked, with its result. A skipped proof is kept without `passed`, since it neither passed nor refused.
92#[derive(Clone, Debug, Deserialize)]
93pub struct ProofRecord {
94    /// Who proved: `algorithm`, `agent` or `person`.
95    pub by: String,
96    /// What was asked: the command, the needs, the check or the question, with references filled.
97    pub asked: String,
98    /// Whether it passed. `false` for a skipped proof.
99    #[serde(default)]
100    pub passed: bool,
101    /// The points against the work, when it did not pass.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub points: Option<String>,
104    /// Whether it was skipped: it is for another answer of a choice, so it was not asked and did not refuse.
105    #[serde(default)]
106    pub skipped: bool,
107    /// Why it was skipped: the answer it is for, and the answer given.
108    #[serde(default)]
109    pub reason: Option<String>,
110}
111
112impl Serialize for ProofRecord {
113    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
114        use serde::ser::SerializeMap;
115        let mut map = serializer.serialize_map(None)?;
116        map.serialize_entry("by", &self.by)?;
117        map.serialize_entry("asked", &self.asked)?;
118        if self.skipped {
119            map.serialize_entry("skipped", &true)?;
120        } else {
121            map.serialize_entry("passed", &self.passed)?;
122        }
123        if let Some(points) = &self.points {
124            map.serialize_entry("points", points)?;
125        }
126        if let Some(reason) = &self.reason {
127            map.serialize_entry("reason", reason)?;
128        }
129        map.end()
130    }
131}
132
133/// One try at a step's work.
134#[derive(Clone, Debug, Serialize, Deserialize)]
135pub struct Attempt {
136    /// Who did the work: `agent`, `algorithm`, `person` or `plan`.
137    pub by: String,
138    /// What they answered.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub answer: Option<String>,
141    /// The proofs asked, in order, up to the first that refused.
142    pub proofs: Vec<ProofRecord>,
143    /// The steps of the other plan, for a step by `plan`.
144    #[serde(default, skip_serializing_if = "Vec::is_empty")]
145    pub steps: Vec<StepRecord>,
146    /// The earlier steps a refusal sent the work back to, when it named some.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub back: Vec<String>,
149    /// Why the work failed before any proof was asked: its agent ended with an error, or it cannot be undone and
150    /// was not done when the run stopped.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub failed: Option<String>,
153    /// The conversation the agent did the work in, when it said.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub conversation: Option<String>,
156    /// The files added, changed or removed in the folder from when the work began to when it ended, in order,
157    /// when the runner saw both. Work done at the same time by other steps shows here too.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub changed: Vec<String>,
160}
161
162impl Attempt {
163    /// A try by `by`, with nothing done yet.
164    pub fn by(by: &str) -> Self {
165        Self {
166            by: by.to_owned(),
167            answer: None,
168            proofs: Vec::new(),
169            steps: Vec::new(),
170            back: Vec::new(),
171            failed: None,
172            conversation: None,
173            changed: Vec::new(),
174        }
175    }
176}
177
178/// One item of a step done for each item.
179#[derive(Clone, Debug, Serialize, Deserialize)]
180pub struct ItemRecord {
181    /// The item, as `{{item}}` names it.
182    pub item: String,
183    /// Its answer, once it passed.
184    pub answer: Option<String>,
185    /// Each try at its work.
186    pub attempts: Vec<Attempt>,
187}
188
189/// One step of the run.
190#[derive(Clone, Debug, Serialize, Deserialize)]
191pub struct StepRecord {
192    /// The step's id.
193    pub id: String,
194    /// Its answer, once it passed.
195    pub answer: Option<String>,
196    /// Whether it was skipped: its path was not taken, or the person went on without it.
197    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
198    pub skipped: bool,
199    /// Whether it has ended, passed or skipped, and is not to be done again.
200    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
201    pub ended: bool,
202    /// Each try at its work. Work sent back to it adds more.
203    pub attempts: Vec<Attempt>,
204    /// Each item, for a step done for each item.
205    #[serde(default, skip_serializing_if = "Vec::is_empty")]
206    pub items: Vec<ItemRecord>,
207}
208
209impl StepRecord {
210    /// A step not started yet.
211    pub fn new(id: &str) -> Self {
212        Self {
213            id: id.to_owned(),
214            answer: None,
215            skipped: false,
216            ended: false,
217            attempts: Vec::new(),
218            items: Vec::new(),
219        }
220    }
221
222    /// Whether its work has started.
223    pub fn started(&self) -> bool {
224        !self.attempts.is_empty() || !self.items.is_empty()
225    }
226}
227
228/// A question the person decided.
229#[derive(Clone, Debug, Serialize, Deserialize)]
230pub struct Decision {
231    /// The step it was about.
232    pub step: String,
233    /// What they were asked.
234    pub asked: String,
235    /// What they answered: `yes`, `no`, the option they chose, or `none`.
236    pub answer: String,
237    /// Who answered, when someone answered from elsewhere and said who they are.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub by: Option<String>,
240}
241
242/// One run of a plan.
243#[derive(Clone, Debug)]
244pub struct Record {
245    /// What names the run: when it started and the plan's name. Its file in `.vpf/runs` is `{id}.json`.
246    pub id: String,
247    /// The plan's name, when it has one.
248    pub plan: Option<String>,
249    /// The plan's wish.
250    pub wish: String,
251    /// What the run was started with.
252    pub asked: String,
253    /// When it started.
254    pub started: Timestamp,
255    /// When it ended, or last stopped to wait.
256    pub ended: Timestamp,
257    /// How it ended, or what it waits for.
258    pub outcome: Outcome,
259    /// What the agents said it cost.
260    pub cost: f64,
261    /// Whether some agent did not say what it cost.
262    pub cost_unmeasured: bool,
263    /// Every step of the plan, in the order written.
264    pub steps: Vec<StepRecord>,
265    /// What the person decided.
266    pub decisions: Vec<Decision>,
267    /// Each version of the plan the run followed, the first first.
268    pub versions: Vec<Version>,
269    /// Everything the run was given from outside it, by agents, commands, people and the clock, so that it can go
270    /// on from where it stands without asking any of it again.
271    pub journal: Vec<Entry>,
272}
273
274/// A record as kept in its file.
275#[derive(Deserialize)]
276struct Kept {
277    #[serde(default)]
278    id: String,
279    plan: Option<String>,
280    wish: String,
281    asked: String,
282    started: Timestamp,
283    ended: Timestamp,
284    outcome: String,
285    #[serde(default)]
286    reason: Option<String>,
287    #[serde(default)]
288    waiting: Option<Vec<Waiting>>,
289    cost: f64,
290    cost_unmeasured: bool,
291    steps: Vec<StepRecord>,
292    decisions: Vec<Decision>,
293    #[serde(default)]
294    versions: Vec<KeptVersion>,
295    #[serde(default)]
296    journal: Vec<Entry>,
297}
298
299#[derive(Deserialize)]
300struct KeptVersion {
301    plan: Value,
302    approved_by: Option<String>,
303    from: Option<String>,
304    at: Timestamp,
305}
306
307impl Record {
308    /// The record as JSON.
309    pub fn to_json(&self) -> Value {
310        let (outcome, reason, waiting) = match &self.outcome {
311            Outcome::Done => ("done", None, None),
312            Outcome::Stopped(reason) => ("stopped", Some(reason), None),
313            Outcome::Waiting(waiting) => ("waiting", None, Some(waiting)),
314        };
315        let versions: Vec<Value> = self
316            .versions
317            .iter()
318            .map(|version| {
319                json!({
320                    "plan": version.plan,
321                    "approved_by": version.approved_by,
322                    "from": version.from,
323                    "at": version.at,
324                })
325            })
326            .collect();
327        json!({
328            "id": self.id,
329            "plan": self.plan,
330            "wish": self.wish,
331            "asked": self.asked,
332            "started": self.started.to_string(),
333            "ended": self.ended.to_string(),
334            "outcome": outcome,
335            "reason": reason,
336            "waiting": waiting,
337            "cost": self.cost,
338            "cost_unmeasured": self.cost_unmeasured,
339            "steps": self.steps,
340            "decisions": self.decisions,
341            "versions": versions,
342            "journal": self.journal,
343        })
344    }
345
346    /// Reads a record kept in a file.
347    ///
348    /// # Errors
349    ///
350    /// When the file cannot be read, or does not hold a record.
351    pub fn load(file: &Path) -> Result<Self, String> {
352        let text = fs::read_to_string(file)
353            .map_err(|error| format!("cannot read {}: {error}", file.display()))?;
354        let kept: Kept = serde_json::from_str(&text)
355            .map_err(|error| format!("{} does not hold a run: {error}", file.display()))?;
356        let outcome = match kept.outcome.as_str() {
357            "done" => Outcome::Done,
358            "waiting" => Outcome::Waiting(kept.waiting.unwrap_or_default()),
359            _ => Outcome::Stopped(kept.reason.unwrap_or_default()),
360        };
361        let mut versions = Vec::new();
362        for version in kept.versions {
363            let report = vpf::check(&version.plan.to_string());
364            let plan = report
365                .plan
366                .filter(|_| report.problems.is_empty())
367                .ok_or_else(|| format!("{} holds a plan with problems", file.display()))?;
368            versions.push(Version {
369                plan,
370                approved_by: version.approved_by,
371                from: version.from,
372                at: version.at,
373            });
374        }
375        let id = if kept.id.is_empty() {
376            file.file_stem()
377                .and_then(|stem| stem.to_str())
378                .unwrap_or_default()
379                .to_owned()
380        } else {
381            kept.id
382        };
383        Ok(Self {
384            id,
385            plan: kept.plan,
386            wish: kept.wish,
387            asked: kept.asked,
388            started: kept.started,
389            ended: kept.ended,
390            outcome,
391            cost: kept.cost,
392            cost_unmeasured: kept.cost_unmeasured,
393            steps: kept.steps,
394            decisions: kept.decisions,
395            versions,
396            journal: kept.journal,
397        })
398    }
399
400    /// The processes that still work for the run, from a runner that stopped while they worked: the agents and
401    /// commands it kept in the folder that have not ended.
402    pub fn still_working(&self, folder: &Path) -> Vec<u32> {
403        self.kept_work(folder)
404            .into_iter()
405            .filter_map(|(pid, running)| running.then_some(pid))
406            .collect()
407    }
408
409    /// The processes of agents and commands kept in the folder for the run that stopped without ending, as when the
410    /// computer went down: going on does that work again, asking first when it cannot be undone.
411    pub fn stopped_working(&self, folder: &Path) -> Vec<u32> {
412        self.kept_work(folder)
413            .into_iter()
414            .filter_map(|(pid, running)| (!running).then_some(pid))
415            .collect()
416    }
417
418    /// Each process kept in the folder for the run that has not ended by itself, and whether it still runs.
419    fn kept_work(&self, folder: &Path) -> Vec<(u32, bool)> {
420        let Ok(read) = fs::read_dir(runs(folder).join(format!("{}.out", self.id))) else {
421            return Vec::new();
422        };
423        let mut work: Vec<(u32, bool)> = read
424            .filter_map(Result::ok)
425            .map(|entry| entry.path())
426            .filter(|dir| crate::command::kept(dir).is_none())
427            .filter_map(|dir| {
428                let pid = fs::read_to_string(dir.join("pid"))
429                    .ok()?
430                    .trim()
431                    .parse()
432                    .ok()?;
433                Some((pid, crate::command::alive(pid)))
434            })
435            .collect();
436        work.sort_unstable();
437        work
438    }
439
440    /// Where the record is kept in the folder.
441    pub fn file(&self, folder: &Path) -> PathBuf {
442        runs(folder).join(format!("{}.json", self.id))
443    }
444
445    /// Writes the record in the folder's `.vpf/runs`, in place of what it kept of the run before.
446    ///
447    /// # Errors
448    ///
449    /// When the file cannot be written.
450    pub fn keep(&self, folder: &Path) -> std::io::Result<PathBuf> {
451        fs::create_dir_all(runs(folder))?;
452        let file = self.file(folder);
453        let text = serde_json::to_string_pretty(&self.to_json()).unwrap_or_default();
454        fs::write(&file, text + "\n")?;
455        Ok(file)
456    }
457
458    /// Adds entries a [`Keeper`](crate::Keeper) was handed to the run's journal, in order: an entry under a key
459    /// the journal holds takes the place of the one there. A run that stopped in the middle is rebuilt this way
460    /// from the record it began with, and goes on without asking any of them again.
461    pub fn add_entries(&mut self, entries: impl IntoIterator<Item = Entry>) {
462        let mut places: std::collections::HashMap<String, usize> = self
463            .journal
464            .iter()
465            .enumerate()
466            .map(|(place, entry)| (entry.key.clone(), place))
467            .collect();
468        for entry in entries {
469            if let Some(&place) = places.get(&entry.key) {
470                self.journal[place] = entry;
471            } else {
472                places.insert(entry.key.clone(), self.journal.len());
473                self.journal.push(entry);
474            }
475        }
476    }
477
478    /// Gives a waiting run the reply to what it waits for under `key`, from `by` when they say who they are. The
479    /// run goes on with it when it is resumed.
480    ///
481    /// # Errors
482    ///
483    /// When the run does not wait for `key`, the reply does not fit what is asked, or the question is for named
484    /// people and `by` is not one of them.
485    pub fn reply(&mut self, key: &str, reply: Reply, by: Option<&str>) -> Result<(), String> {
486        let Outcome::Waiting(waiting) = &mut self.outcome else {
487            return Err(format!("the run {} waits for nothing", self.id));
488        };
489        let place = waiting
490            .iter()
491            .position(|waiting| waiting.key == key)
492            .ok_or_else(|| format!("the run {} does not wait for {key}", self.id))?;
493        fits(&waiting[place].wait, &reply, by)?;
494        waiting.remove(place);
495        self.journal.push(Entry {
496            key: key.to_owned(),
497            at: Timestamp::now(),
498            by: by.map(str::to_owned),
499            value: serde_json::to_value(reply).unwrap_or_default(),
500        });
501        Ok(())
502    }
503
504    /// Takes a new version of the plan for a waiting run, approved by `approved_by`: the run goes on with it from
505    /// where it stands when it is resumed.
506    ///
507    /// # Errors
508    ///
509    /// When the run does not wait, no one approved, the plan has problems, a step that ended is not in it as it
510    /// was, or a step that started is not in it with the same `id`, `by` and `do`.
511    pub fn change(&mut self, plan: &Plan, approved_by: &str, at: Timestamp) -> Result<(), String> {
512        if !matches!(self.outcome, Outcome::Waiting(_)) {
513            return Err(format!(
514                "the run {} does not wait, so its plan cannot change",
515                self.id
516            ));
517        }
518        let approved_by = approved_by.trim();
519        if approved_by.is_empty() {
520            return Err("a new version of the plan needs the person's approval".to_owned());
521        }
522        let report = vpf::check(&serde_json::to_string(plan).unwrap_or_default());
523        if !report.problems.is_empty() {
524            let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
525            return Err(format!(
526                "the new version has problems: {}",
527                problems.join("; ")
528            ));
529        }
530        let old = self
531            .versions
532            .last()
533            .ok_or_else(|| format!("the run {} keeps no plan", self.id))?;
534        for (step, record) in old.plan.steps.iter().zip(&self.steps) {
535            let new = plan.steps.iter().find(|new| new.id == step.id);
536            if record.ended && new != Some(step) {
537                return Err(format!(
538                    "the step {} has ended, so it must stay as it was",
539                    step.id
540                ));
541            }
542            if record.started()
543                && !new.is_some_and(|new| new.by == step.by && new.what == step.what)
544            {
545                return Err(format!(
546                    "the step {} has started, so it must keep its id, by and do",
547                    step.id
548                ));
549            }
550            if record.started() && step.irreversible() && !new.is_some_and(Step::irreversible) {
551                return Err(format!(
552                    "the step {} has started and cannot be undone, so it stays so",
553                    step.id
554                ));
555            }
556        }
557        let ended: Vec<&str> = self
558            .steps
559            .iter()
560            .filter(|record| record.ended)
561            .map(|record| record.id.as_str())
562            .collect();
563        let from = plan
564            .steps
565            .iter()
566            .find(|step| !ended.contains(&step.id.as_str()))
567            .map(|step| step.id.clone());
568        self.wish = crate::fill::fill(
569            &plan.wish,
570            &std::collections::HashMap::from([("asked".to_owned(), self.asked.clone())]),
571        );
572        self.versions.push(Version {
573            plan: plan.clone(),
574            approved_by: Some(approved_by.to_owned()),
575            from,
576            at,
577        });
578        Ok(())
579    }
580}
581
582/// Whether a reply fits what is waited for, and comes from someone it is for.
583fn fits(wait: &Wait, reply: &Reply, by: Option<&str>) -> Result<(), String> {
584    let ask = match wait {
585        Wait::Answer(ask) | Wait::Approval(ask) => Some(ask),
586        _ => None,
587    };
588    if let Some(ask) = ask.filter(|ask| !ask.people.is_empty()) {
589        if !by.is_some_and(|by| ask.people.iter().any(|person| person == by)) {
590            return Err(format!(
591                "only {} may answer this; say who answers",
592                ask.people.join(" or ")
593            ));
594        }
595    }
596    match (wait, reply) {
597        (Wait::Answer(ask), Reply::Text(text)) => {
598            if ask.choices.is_empty() || ask.choices.iter().any(|choice| choice == text.trim()) {
599                Ok(())
600            } else {
601                Err(format!(
602                    "the answer must be one of: {}",
603                    ask.choices.join(", ")
604                ))
605            }
606        }
607        (Wait::Approval(ask), Reply::No { back, .. }) => {
608            match back.iter().find(|id| !ask.back_to.contains(id)) {
609                Some(id) => Err(format!(
610                    "the work may not go back to {id}; it may go back to: {}",
611                    ask.back_to.join(", ")
612                )),
613                None => Ok(()),
614            }
615        }
616        (Wait::Approval(_) | Wait::Decision(_), Reply::Yes)
617        | (Wait::Decision(_), Reply::No { .. }) => Ok(()),
618        (Wait::Choice { options, .. }, Reply::Option(chosen)) if *chosen < options.len() => Ok(()),
619        (Wait::Time(at), _) => Err(format!("this waits for a time, {at}, not for an answer")),
620        _ => Err("the reply does not fit what is asked".to_owned()),
621    }
622}
623
624/// Where a folder keeps its runs.
625pub fn runs(folder: &Path) -> PathBuf {
626    folder.join(".vpf").join("runs")
627}
628
629/// What the runs of a plan kept in the folder cost in the calendar month of `now`, where the runner runs.
630pub fn spent_this_month(folder: &Path, plan: &str, now: Timestamp) -> f64 {
631    let zone = TimeZone::system();
632    let month = |at: Timestamp| {
633        let date = at.to_zoned(zone.clone()).date();
634        (date.year(), date.month())
635    };
636    let this = month(now);
637    let Ok(read) = fs::read_dir(runs(folder)) else {
638        return 0.0;
639    };
640    read.filter_map(Result::ok)
641        .filter_map(|entry| fs::read_to_string(entry.path()).ok())
642        .filter_map(|text| serde_json::from_str::<Value>(&text).ok())
643        .filter(|record| record["plan"] == plan)
644        .filter(|record| {
645            record["started"]
646                .as_str()
647                .and_then(|started| started.parse::<Timestamp>().ok())
648                .is_some_and(|started| month(started) == this)
649        })
650        .filter_map(|record| record["cost"].as_f64())
651        .sum()
652}