adk_kernel/charter/kit.rs
1//! [`CharterKit`]: one call that installs a site's jobs, KPI tracker and signals on a kernel
2//! (spec 3.5 §7.10, §7.11, §7.19, §7.20; #1278).
3
4use std::collections::BTreeMap;
5use std::sync::Arc;
6
7use adk_core::NewRun;
8use serde_json::Value;
9use uuid::Uuid;
10
11use super::signal::SignalStore;
12use super::site::SiteProcessKind;
13use super::tracker::KpiTracker;
14use crate::inventory::InventoryWarning;
15use crate::kernel::KernelBuilder;
16use crate::partition::PartitionId;
17use crate::wake::Wake;
18
19/// Installs a site's charter machinery on a kernel (spec 3.5 §7.10, §7.11, §7.19, §7.20):
20/// the product binds each [`SiteProcessKind`] it runs to its own target with
21/// [`job`](Self::job), and [`install`](Self::install) registers on a [`KernelBuilder`]:
22///
23/// | Part | What `install` registers |
24/// |---|---|
25/// | Each bound kind | Its standing trigger ([`SiteProcessKind::trigger`]) on its default wake, or the one [`job_on`](Self::job_on) names, in the back-office partition, running the bound target with the bound input as the kit's user |
26/// | The KPI tracker ([`tracker`](Self::tracker)) | [`KernelBuilder::kpi_tracker`]: its `kernel.kpi` trigger on the kit's cron and its executor, so the tracker is a kernel process — in `ps`, with a cron watermark, held during a freeze |
27/// | Signals | [`KernelBuilder::signals`] over the kit's signal store in the back-office partition, so [`Kernel::signal_sink`](crate::Kernel::signal_sink) files the edge's signals and they wake the signal kinds |
28/// | Each kind not bound | An inventory warning `charter.job_unbound` naming the kind, with the reason [`skip`](Self::skip) gave |
29///
30/// The kernel recognises the kinds and the product does their work: the kit never picks a
31/// target for a kind.
32///
33/// # Example
34///
35/// ```rust
36/// use std::sync::Arc;
37/// use adk_core::InMemoryRunStore;
38/// use adk_kernel::Kernel;
39/// use adk_kernel::charter::{CharterKit, InMemorySignalStore, SiteProcessKind};
40///
41/// let site = uuid::Uuid::new_v4();
42/// let kit = CharterKit::new(site, "bakery", "bakery.back-office", Arc::new(InMemorySignalStore::new()))
43/// .job(SiteProcessKind::Probe, "website.guardian.probe", serde_json::json!({ "site": site }))
44/// .skip(SiteProcessKind::Digest, "the owner has no channel");
45/// let kernel = kit.install(Kernel::builder().run_store(Arc::new(InMemoryRunStore::new()))).build()?;
46/// let triggers: Vec<&str> = kernel.wake_router().triggers().iter().map(|t| t.name.as_str()).collect();
47/// assert_eq!(triggers, ["site.probe"]);
48/// assert!(kernel.signal_sink("bakery.back-office").is_ok());
49/// let unbound = kernel.inventory().warnings.into_iter().filter(|w| w.code == CharterKit::JOB_UNBOUND).count();
50/// assert_eq!(unbound, SiteProcessKind::ALL.len() - 1);
51/// # Ok::<(), adk_kernel::KernelError>(())
52/// ```
53#[derive(Clone)]
54pub struct CharterKit {
55 site: Uuid,
56 app: String,
57 user: String,
58 back_office: PartitionId,
59 signals: Arc<dyn SignalStore>,
60 jobs: BTreeMap<SiteProcessKind, Job>,
61 skipped: BTreeMap<SiteProcessKind, String>,
62 tracker: Option<KpiTracker>,
63 tracker_cron: String,
64}
65
66/// One bound kind.
67#[derive(Clone)]
68struct Job {
69 target: String,
70 input: Value,
71 wake: Option<Wake>,
72}
73
74impl std::fmt::Debug for CharterKit {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 f.debug_struct("CharterKit")
77 .field("site", &self.site)
78 .field("app", &self.app)
79 .field("back_office", &self.back_office)
80 .field("jobs", &self.jobs.keys().collect::<Vec<_>>())
81 .field("tracker", &self.tracker.is_some())
82 .finish_non_exhaustive()
83 }
84}
85
86impl CharterKit {
87 /// The inventory warning of a kind no job is bound to.
88 pub const JOB_UNBOUND: &'static str = "charter.job_unbound";
89
90 /// The tracker's default cron: hourly, on the hour, in UTC. The tracker reads each KPI
91 /// on its own cadence, daily at the most often.
92 pub const DEFAULT_TRACKER_CRON: &'static str = "0 0 * * * *";
93
94 /// A kit for site `site` of app `app`, its jobs running in the back-office partition
95 /// `back_office`, its signals filed through `signals`; the runs act for the user `site`.
96 pub fn new(
97 site: Uuid,
98 app: impl Into<String>,
99 back_office: impl Into<PartitionId>,
100 signals: Arc<dyn SignalStore>,
101 ) -> Self {
102 Self {
103 site,
104 app: app.into(),
105 user: "site".into(),
106 back_office: back_office.into(),
107 signals,
108 jobs: BTreeMap::new(),
109 skipped: BTreeMap::new(),
110 tracker: None,
111 tracker_cron: Self::DEFAULT_TRACKER_CRON.into(),
112 }
113 }
114
115 /// Runs the jobs' processes for `user`, a `Service` subject.
116 #[must_use]
117 pub fn with_user(mut self, user: impl Into<String>) -> Self {
118 self.user = user.into();
119 self
120 }
121
122 /// Binds `kind` to `target`, an agent or workflow the kernel serves, its runs starting
123 /// with `input`, on the kind's default wake ([`SiteProcessKind::default_wake`]). Binding a
124 /// kind again replaces it.
125 #[must_use]
126 pub fn job(mut self, kind: SiteProcessKind, target: impl Into<String>, input: Value) -> Self {
127 self.skipped.remove(&kind);
128 self.jobs.insert(kind, Job { target: target.into(), input, wake: None });
129 self
130 }
131
132 /// Binds `kind` as [`job`](Self::job) does, started by `wake` instead of its default.
133 #[must_use]
134 pub fn job_on(
135 mut self,
136 kind: SiteProcessKind,
137 target: impl Into<String>,
138 input: Value,
139 wake: Wake,
140 ) -> Self {
141 self.skipped.remove(&kind);
142 self.jobs.insert(kind, Job { target: target.into(), input, wake: Some(wake) });
143 self
144 }
145
146 /// Leaves `kind` unbound for `reason`, such as "the owner has no channel": the kernel's
147 /// inventory names it with the reason.
148 #[must_use]
149 pub fn skip(mut self, kind: SiteProcessKind, reason: impl Into<String>) -> Self {
150 self.jobs.remove(&kind);
151 self.skipped.insert(kind, reason.into());
152 self
153 }
154
155 /// Runs `tracker`, the site's KPI tracker, as the kernel's `kernel.kpi` process.
156 #[must_use]
157 pub fn tracker(mut self, tracker: KpiTracker) -> Self {
158 self.tracker = Some(tracker);
159 self
160 }
161
162 /// Runs the tracker on the six-field UTC cron expression `expr` instead of
163 /// [`DEFAULT_TRACKER_CRON`](Self::DEFAULT_TRACKER_CRON).
164 #[must_use]
165 pub fn tracker_cron(mut self, expr: impl Into<String>) -> Self {
166 self.tracker_cron = expr.into();
167 self
168 }
169
170 /// The kinds bound to a job.
171 pub fn bound(&self) -> Vec<SiteProcessKind> {
172 self.jobs.keys().copied().collect()
173 }
174
175 /// Registers the kit on `builder` (see the type's table).
176 pub fn install(self, mut builder: KernelBuilder) -> KernelBuilder {
177 let bound = self.bound();
178 for (kind, job) in self.jobs {
179 let wake = job.wake.unwrap_or_else(|| kind.default_wake(&self.back_office));
180 let run =
181 NewRun::new(kind.queue().as_str(), &self.app, &self.user, job.target, job.input);
182 builder = builder.trigger(kind.trigger(wake, run, self.back_office.clone()));
183 }
184 for kind in SiteProcessKind::ALL.into_iter().filter(|kind| !bound.contains(kind)) {
185 let reason = self.skipped.get(&kind).map_or("no job is bound to it", String::as_str);
186 builder = builder.inventory_warning(
187 InventoryWarning::new(
188 Self::JOB_UNBOUND,
189 format!("site {} runs no `{kind}` process: {reason}", self.site),
190 )
191 .with_subject(kind.as_str()),
192 );
193 }
194 if let Some(tracker) = self.tracker {
195 builder = builder.kpi_tracker(tracker, &self.app, &self.tracker_cron);
196 }
197 builder.signals(self.signals, self.back_office)
198 }
199}