Skip to main content

adk_kernel/charter/
site.rs

1//! The site's process kinds (spec 3.5 §7.11, §7.19, §7.20).
2
3use std::fmt;
4
5use adk_core::NewRun;
6use adk_core::schedule::MissedFirePolicy;
7use serde::{Deserialize, Serialize};
8
9use crate::partition::PartitionId;
10use crate::process::{ProcessKind, ProcessMeta, ProcessSpec};
11use crate::sched::QueueClass;
12use crate::wake::{Trigger, Wake, WakeOverlap};
13
14/// The label every site process carries, with its kind's name as the value (spec 3.5 §7.11).
15pub const SITE_PROCESS_LABEL: &str = "site.process";
16
17/// A kind of process a website's team runs (spec 3.5 §7.11, §7.19, §7.20): the kernel
18/// recognises these, and the product does their work.
19///
20/// A site process is a [`ProcessKind::Triggered`] process whose source is the kind's name,
21/// labelled [`SITE_PROCESS_LABEL`]; [`trigger`](Self::trigger) builds the standing trigger
22/// that starts one, and [`of`](Self::of) recognises one in the process table.
23///
24/// | Kind | Job (§7.20) | Default wake (§7.19) |
25/// |---|---|---|
26/// | `site.probe` | Guardian: drift probes of the served release | every 5 minutes |
27/// | `site.watch` | Guardian: advisories, certificates, domains, status | daily at 06:00 UTC |
28/// | `site.content` | Growth: freshness and content gaps | a `content_gap` signal |
29/// | `site.reviews` | Growth, Inbox: review replies | a `review_seen` signal |
30/// | `site.outreach` | Revenue: nurture sequences and handoffs | daily at 09:00 UTC |
31/// | `site.support` | Steward: support escalations | a `support_escalation` signal |
32/// | `site.digest` | Steward, Finance: the weekly review | Mondays at 07:00 UTC |
33///
34/// # Example
35///
36/// ```rust
37/// use adk_kernel::charter::SiteProcessKind;
38/// use adk_kernel::{ProcessKind, ProcessMeta, QueueClass};
39///
40/// let kind: SiteProcessKind = "site.digest".parse().unwrap();
41/// assert_eq!(kind, SiteProcessKind::Digest);
42/// let meta = ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Triggered { source: "site.probe".into() });
43/// assert_eq!(SiteProcessKind::of(&meta), Some(SiteProcessKind::Probe));
44/// ```
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
46#[non_exhaustive]
47pub enum SiteProcessKind {
48    /// `site.probe`.
49    #[serde(rename = "site.probe")]
50    Probe,
51    /// `site.watch`.
52    #[serde(rename = "site.watch")]
53    Watch,
54    /// `site.content`.
55    #[serde(rename = "site.content")]
56    Content,
57    /// `site.reviews`.
58    #[serde(rename = "site.reviews")]
59    Reviews,
60    /// `site.outreach`.
61    #[serde(rename = "site.outreach")]
62    Outreach,
63    /// `site.support`.
64    #[serde(rename = "site.support")]
65    Support,
66    /// `site.digest`.
67    #[serde(rename = "site.digest")]
68    Digest,
69}
70
71impl SiteProcessKind {
72    /// Every kind.
73    pub const ALL: [Self; 7] = [
74        Self::Probe,
75        Self::Watch,
76        Self::Content,
77        Self::Reviews,
78        Self::Outreach,
79        Self::Support,
80        Self::Digest,
81    ];
82
83    /// The kind's name, `site.probe` to `site.digest`.
84    pub fn as_str(self) -> &'static str {
85        match self {
86            Self::Probe => "site.probe",
87            Self::Watch => "site.watch",
88            Self::Content => "site.content",
89            Self::Reviews => "site.reviews",
90            Self::Outreach => "site.outreach",
91            Self::Support => "site.support",
92            Self::Digest => "site.digest",
93        }
94    }
95
96    /// The kind of `meta`'s process: its [`SITE_PROCESS_LABEL`], or the source of a
97    /// [`ProcessKind::Triggered`] process; `None` for a process no site trigger started.
98    pub fn of(meta: &ProcessMeta) -> Option<Self> {
99        let named = |name: &str| Self::ALL.into_iter().find(|kind| kind.as_str() == name);
100        meta.labels.get(SITE_PROCESS_LABEL).and_then(|name| named(name)).or_else(|| {
101            match &meta.kind {
102                ProcessKind::Triggered { source } => named(source),
103                _ => None,
104            }
105        })
106    }
107
108    /// The queue its processes run on: a probe and a watch are the kernel's own upkeep
109    /// (`maintenance`); the rest are the team's work (`background`).
110    pub fn queue(self) -> QueueClass {
111        match self {
112            Self::Probe | Self::Watch => QueueClass::Maintenance,
113            Self::Content | Self::Reviews | Self::Outreach | Self::Support | Self::Digest => {
114                QueueClass::Background
115            }
116        }
117    }
118
119    /// The wake that starts it by default (spec 3.5 §7.19): a six-field UTC cron for the
120    /// scheduled kinds, a [`Wake::Signal`] of the back office `partition` for the kinds a
121    /// signal starts.
122    pub fn default_wake(self, partition: &PartitionId) -> Wake {
123        let cron =
124            |expr: &str| Wake::Cron { expr: expr.to_string(), missed: MissedFirePolicy::Skip };
125        let signal = |kind: &str| Wake::Signal {
126            kind: kind.to_string(),
127            partition: Some(partition.clone()),
128        };
129        match self {
130            Self::Probe => cron("0 */5 * * * *"),
131            Self::Watch => cron("0 0 6 * * *"),
132            Self::Content => signal("content_gap"),
133            Self::Reviews => signal("review_seen"),
134            Self::Outreach => cron("0 0 9 * * *"),
135            Self::Support => signal("support_escalation"),
136            Self::Digest => cron("0 0 7 * * MON"),
137        }
138    }
139
140    /// The process spec of a kind's process in `partition`: [`ProcessKind::Triggered`] with
141    /// the kind's name as source, labelled [`SITE_PROCESS_LABEL`].
142    pub fn spec(self, partition: impl Into<PartitionId>) -> ProcessSpec {
143        ProcessSpec::new(ProcessKind::Triggered { source: self.as_str().to_string() })
144            .with_partition(partition)
145            .with_label(SITE_PROCESS_LABEL, self.as_str())
146    }
147
148    /// The standing trigger that starts a kind's process in `partition` when `wake` fires,
149    /// running `run` on the kind's [`queue`](Self::queue); the trigger is named after the
150    /// kind, so its processes are [`ProcessKind::Triggered`] with that source. On a cron wake
151    /// a firing while the kind's process is unfinished starts nothing
152    /// ([`WakeOverlap::Skip`]); on any other wake each firing queues a process
153    /// ([`WakeOverlap::Queue`]), since each signal carries its own news.
154    ///
155    /// # Example
156    ///
157    /// ```rust
158    /// use adk_core::NewRun;
159    /// use adk_kernel::charter::SiteProcessKind;
160    ///
161    /// let run = NewRun::new("background", "adk-rust", "site", "guardian", serde_json::json!({"text": "probe"}));
162    /// let partition = "back-office".into();
163    /// let trigger = SiteProcessKind::Probe.trigger(SiteProcessKind::Probe.default_wake(&partition), run, partition);
164    /// assert_eq!(trigger.name, "site.probe");
165    /// assert_eq!(trigger.run.queue, "maintenance");
166    /// assert_eq!(trigger.overlap, adk_kernel::WakeOverlap::Skip);
167    /// ```
168    pub fn trigger(
169        self,
170        wake: Wake,
171        mut run: NewRun,
172        partition: impl Into<PartitionId>,
173    ) -> Trigger {
174        run.queue = self.queue().as_str().to_string();
175        let overlap = match wake {
176            Wake::Cron { .. } => WakeOverlap::Skip,
177            _ => WakeOverlap::Queue,
178        };
179        Trigger::new(self.as_str(), wake, run).with_partition(partition).with_overlap(overlap)
180    }
181}
182
183impl fmt::Display for SiteProcessKind {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.write_str(self.as_str())
186    }
187}
188
189impl std::str::FromStr for SiteProcessKind {
190    type Err = crate::KernelError;
191
192    fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
193        let text = text.trim();
194        Self::ALL.into_iter().find(|kind| kind.as_str() == text).ok_or_else(|| {
195            crate::KernelError::Config {
196                reason: format!(
197                    "unknown site process kind `{text}`; use site.probe, site.watch, site.content, \
198                     site.reviews, site.outreach, site.support or site.digest"
199                ),
200            }
201        })
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn names_parse_back_and_serialize_as_themselves() {
211        for kind in SiteProcessKind::ALL {
212            assert_eq!(kind.as_str().parse::<SiteProcessKind>().unwrap(), kind);
213            assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
214        }
215        assert!("site.other".parse::<SiteProcessKind>().is_err());
216    }
217
218    #[test]
219    fn a_spec_is_recognised_by_its_label_and_kind() {
220        let spec = SiteProcessKind::Reviews.spec("back-office");
221        assert_eq!(spec.labels.get(SITE_PROCESS_LABEL).map(String::as_str), Some("site.reviews"));
222        let meta = ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal)
223            .with_label(SITE_PROCESS_LABEL, "site.reviews");
224        assert_eq!(SiteProcessKind::of(&meta), Some(SiteProcessKind::Reviews));
225        let other = ProcessMeta::new("run-2", QueueClass::Background, ProcessKind::Goal);
226        assert_eq!(SiteProcessKind::of(&other), None);
227    }
228
229    #[test]
230    fn default_wakes_are_valid_crons_or_signals_of_the_partition() {
231        let partition = PartitionId::new("back-office");
232        for kind in SiteProcessKind::ALL {
233            match kind.default_wake(&partition) {
234                Wake::Cron { expr, .. } => {
235                    adk_agent::ambient::CronTrigger::new(&expr).expect("a valid cron");
236                }
237                Wake::Signal { partition: Some(p), .. } => assert_eq!(p, partition),
238                other => panic!("{kind} wakes on {other:?}"),
239            }
240        }
241    }
242}