Skip to main content

adk_website/
workflows.rs

1//! The site's model-free jobs as kernel runs (spec 3.5 §7.20, §7.11, §7.21): the Guardian's
2//! probe ([`PROBE_WORKFLOW`]), the hosting job's upkeep check ([`WATCH_WORKFLOW`]) and the
3//! weekly review's composition ([`DIGEST_WORKFLOW`]), a push to the content repository
4//! ([`REPOSITORY_WORKFLOW`]), and the playbook-learning run ([`LEARNING_WORKFLOW`]).
5//! Register [`SiteWorkflows`] with `KernelBuilder::workflows` and each process's trigger from
6//! [`crate::jobs::processes`]; the other site processes run their job's agent.
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use adk_kernel::channels::ChannelSink;
12use adk_server::background::{WorkflowExecutor, WorkflowState};
13use async_trait::async_trait;
14use chrono::{Datelike, Duration, Utc};
15use serde_json::{Value, json};
16use tokio_util::sync::CancellationToken;
17use uuid::Uuid;
18
19use crate::incident::GuardianProbe;
20pub use crate::jobs::{DIGEST_WORKFLOW, PROBE_WORKFLOW, WATCH_WORKFLOW};
21pub use crate::learning::LEARNING_WORKFLOW;
22pub use crate::repository::REPOSITORY_WORKFLOW;
23use crate::review::{ReviewComposer, ReviewInputs};
24
25/// Where a site's weekly review goes.
26pub struct DigestTarget {
27    /// The composer.
28    pub composer: Arc<ReviewComposer>,
29    /// The owner's channel.
30    pub sink: Arc<dyn ChannelSink>,
31    /// The owner's thread on it.
32    pub thread: String,
33}
34
35/// The executor of the site's model-free jobs, one probe and one digest per site (spec 3.5
36/// §7.20).
37#[derive(Default)]
38pub struct SiteWorkflows {
39    probes: BTreeMap<Uuid, Arc<GuardianProbe>>,
40    watches: BTreeMap<Uuid, Arc<crate::upkeep::UpkeepCheck>>,
41    digests: BTreeMap<Uuid, DigestTarget>,
42    repositories: BTreeMap<Uuid, Arc<crate::repository::RepositoryEntry>>,
43    learnings: BTreeMap<Uuid, Arc<crate::learning::PlaybookLearning>>,
44}
45
46impl SiteWorkflows {
47    /// No sites yet.
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    /// Runs `site`'s probe.
53    #[must_use]
54    pub fn probe(mut self, site: Uuid, probe: Arc<GuardianProbe>) -> Self {
55        self.probes.insert(site, probe);
56        self
57    }
58
59    /// Runs `site`'s daily upkeep check (spec 3.5 §7.20).
60    #[must_use]
61    pub fn watch(mut self, site: Uuid, check: Arc<crate::upkeep::UpkeepCheck>) -> Self {
62        self.watches.insert(site, check);
63        self
64    }
65
66    /// Takes `site`'s pushes to its content repository (spec 3.5 §7.8.2).
67    #[must_use]
68    pub fn repository(
69        mut self,
70        site: Uuid,
71        entry: Arc<crate::repository::RepositoryEntry>,
72    ) -> Self {
73        self.repositories.insert(site, entry);
74        self
75    }
76
77    /// Runs `site`'s weekly playbook learning (spec 3.5 §7.15).
78    #[must_use]
79    pub fn learning(
80        mut self,
81        site: Uuid,
82        learning: Arc<crate::learning::PlaybookLearning>,
83    ) -> Self {
84        self.learnings.insert(site, learning);
85        self
86    }
87
88    /// Sends `site`'s weekly review to `target`.
89    #[must_use]
90    pub fn digest(mut self, site: Uuid, target: DigestTarget) -> Self {
91        self.digests.insert(site, target);
92        self
93    }
94}
95
96#[async_trait]
97impl WorkflowExecutor for SiteWorkflows {
98    fn has_workflow(&self, workflow_id: &str) -> bool {
99        matches!(
100            workflow_id,
101            PROBE_WORKFLOW
102                | WATCH_WORKFLOW
103                | DIGEST_WORKFLOW
104                | REPOSITORY_WORKFLOW
105                | LEARNING_WORKFLOW
106        )
107    }
108
109    async fn execute(
110        &self,
111        workflow_id: &str,
112        input: WorkflowState,
113        cancel_token: CancellationToken,
114    ) -> Result<Value, String> {
115        let site = input
116            .get("site")
117            .and_then(Value::as_str)
118            .and_then(|site| site.parse::<Uuid>().ok())
119            .ok_or_else(|| {
120                format!("a `{workflow_id}` run names its site as {{\"site\": <uuid>}}")
121            })?;
122        let work =
123            async {
124                match workflow_id {
125                    PROBE_WORKFLOW => {
126                        let probe = self
127                            .probes
128                            .get(&site)
129                            .ok_or_else(|| format!("no probe is registered for site {site}"))?;
130                        let outcome = probe.run().await;
131                        // The probe runs every five minutes for as long as the site serves;
132                        // each run reads its own requests so they do not accumulate.
133                        let requests = probe.http.take_connections();
134                        let mut value = serde_json::to_value(outcome.map_err(|e| e.to_string())?)
135                            .map_err(|e| e.to_string())?;
136                        value["requests"] = json!(requests.len());
137                        Ok(value)
138                    }
139                    WATCH_WORKFLOW => {
140                        let check = self.watches.get(&site).ok_or_else(|| {
141                            format!("no upkeep check is registered for site {site}")
142                        })?;
143                        let report = check.run().await.map_err(|e| e.to_string())?;
144                        serde_json::to_value(report).map_err(|e| e.to_string())
145                    }
146                    DIGEST_WORKFLOW => {
147                        let target = self.digests.get(&site).ok_or_else(|| {
148                            format!("no weekly review is registered for site {site}")
149                        })?;
150                        let today = Utc::now().date_naive();
151                        let this_monday = today
152                            - Duration::days(i64::from(today.weekday().num_days_from_monday()));
153                        let review = target
154                            .composer
155                            .compose(this_monday - Duration::days(7), ReviewInputs::default())
156                            .await
157                            .map_err(|e| e.to_string())?;
158                        let document = target
159                            .composer
160                            .send(&review, target.sink.as_ref(), &target.thread)
161                            .await
162                            .map_err(|e| e.to_string())?;
163                        Ok(json!({ "summary": review.summary(), "document": document }))
164                    }
165                    REPOSITORY_WORKFLOW => {
166                        let entry = self.repositories.get(&site).ok_or_else(|| {
167                            format!("no content repository is configured for site {site}")
168                        })?;
169                        entry.execute(&input).await.map_err(|e| e.to_string())
170                    }
171                    LEARNING_WORKFLOW => {
172                        let learning = self.learnings.get(&site).ok_or_else(|| {
173                            format!("no playbook learning is registered for site {site}")
174                        })?;
175                        learning.run().await.map_err(|e| e.to_string())
176                    }
177                    other => Err(format!("{other} is not a website workflow")),
178                }
179            };
180        tokio::select! {
181            () = cancel_token.cancelled() => Err("cancelled".to_string()),
182            result = work => result,
183        }
184    }
185}