rustango_cms/task_kind.rs
1//! Custom workflow task kinds.
2//!
3//! `WorkflowTask` rows carry a `kind` discriminator (default
4//! `"group_approval"` — a role member clicks approve). The
5//! [`TaskKind`] trait lets hosts register additional kinds:
6//! auto-approve, webhook-on-assign, or anything else they need.
7//!
8//! ## Built-in kinds
9//!
10//! - `group_approval` — current behavior; a member of the task's
11//! role decides via the editor UI.
12//! - `auto_approve` — completes immediately when assigned. Useful
13//! for steps that exist only to record a workflow checkpoint
14//! (e.g. "schedule final publish" as a no-op separator).
15//! - `webhook_notify` — best-effort POSTs `task.webhook_url`
16//! on assign, then completes the task. External systems can
17//! trigger their own approval back via the usual approve
18//! endpoint when they're ready.
19//!
20//! ## Registering a custom kind
21//!
22//! ```ignore
23//! use rustango_cms::task_kind::{TaskKind, TaskKindRegistration, AssignedTask, AssignOutcome};
24//!
25//! struct ConditionalSkip;
26//!
27//! impl TaskKind for ConditionalSkip {
28//! fn kind_name(&self) -> &'static str { "conditional_skip" }
29//! fn verbose_name(&self) -> &'static str { "Conditional skip" }
30//! fn on_assign(&self, _task: &AssignedTask<'_>) -> AssignOutcome {
31//! // Inspect _task.page / _task.task and decide.
32//! AssignOutcome::AutoApprove
33//! }
34//! }
35//!
36//! rustango_cms::register_task_kind!(ConditionalSkip);
37//! ```
38
39use crate::page::Page;
40use crate::workflow::WorkflowTask;
41
42/// Outcome of [`TaskKind::on_assign`]. The workflow engine reads it
43/// to decide whether to leave the task in flight (`WaitForHuman`)
44/// or auto-advance (`AutoApprove`).
45#[derive(Debug, Clone)]
46pub enum AssignOutcome {
47 /// Leave the task in flight; an approver needs to click
48 /// approve / reject via the usual UI.
49 WaitForHuman,
50 /// Mark the task approved immediately and advance to the next
51 /// task (or finish the workflow if this was the last one).
52 AutoApprove,
53}
54
55/// Bundle of references passed to [`TaskKind::on_assign`] so the
56/// kind can decide based on the live workflow context without
57/// re-querying.
58pub struct AssignedTask<'a> {
59 pub task: &'a WorkflowTask,
60 pub page: &'a Page,
61 /// User id of the editor who submitted the page for review.
62 pub requested_by: i64,
63}
64
65/// One pluggable workflow task behavior. Defaults make the trait
66/// minimal to implement — only [`Self::kind_name`] is required;
67/// the rest opt in.
68pub trait TaskKind: Send + Sync + 'static {
69 /// Discriminator stored in `WorkflowTask.kind`. Globally unique
70 /// across the process.
71 fn kind_name(&self) -> &'static str;
72
73 /// Human-readable label for the workflow task editor's "Kind"
74 /// dropdown. Defaults to [`Self::kind_name`].
75 fn verbose_name(&self) -> &'static str {
76 self.kind_name()
77 }
78
79 /// Called when this task becomes the workflow's current step.
80 /// Side-effects (firing webhooks, recording metrics) belong here.
81 ///
82 /// The default implementation returns `WaitForHuman` — i.e. the
83 /// task behaves like the canonical `group_approval` kind.
84 fn on_assign(&self, _ctx: &AssignedTask<'_>) -> AssignOutcome {
85 AssignOutcome::WaitForHuman
86 }
87}
88
89/// Inventory registration shim. Built-in + host-registered kinds
90/// land in the same registry via [`crate::register_task_kind!`].
91pub struct TaskKindRegistration {
92 pub builder: fn() -> Box<dyn TaskKind>,
93}
94
95inventory::collect!(TaskKindRegistration);
96
97/// Macro mirror of [`crate::register_block!`]. Hosts call this to
98/// publish a custom [`TaskKind`] into the runtime registry.
99///
100/// ```ignore
101/// rustango_cms::register_task_kind!(ConditionalSkip);
102/// ```
103#[macro_export]
104macro_rules! register_task_kind {
105 ($ty:ty) => {
106 $crate::inventory::submit! {
107 $crate::task_kind::TaskKindRegistration {
108 builder: || -> Box<dyn $crate::task_kind::TaskKind> {
109 Box::new(<$ty as core::default::Default>::default())
110 },
111 }
112 }
113 };
114}
115
116/// Every registered task kind, including built-ins.
117#[must_use]
118pub fn registered_kinds() -> Vec<Box<dyn TaskKind>> {
119 inventory::iter::<TaskKindRegistration>()
120 .map(|r| (r.builder)())
121 .collect()
122}
123
124/// Look up a kind by `kind_name`. Returns `None` when missing — the
125/// workflow engine falls back to `WaitForHuman` semantics so an
126/// unknown kind doesn't auto-advance into a corrupt state.
127#[must_use]
128pub fn find(name: &str) -> Option<Box<dyn TaskKind>> {
129 inventory::iter::<TaskKindRegistration>()
130 .map(|r| (r.builder)())
131 .find(|k| k.kind_name() == name)
132}
133
134// =====================================================================
135// Built-in kinds
136// =====================================================================
137
138/// Default — a role member must approve via the existing UI.
139#[derive(Default)]
140pub struct GroupApprovalKind;
141
142impl TaskKind for GroupApprovalKind {
143 fn kind_name(&self) -> &'static str {
144 "group_approval"
145 }
146 fn verbose_name(&self) -> &'static str {
147 "Group approval (role member clicks approve)"
148 }
149 fn on_assign(&self, _ctx: &AssignedTask<'_>) -> AssignOutcome {
150 AssignOutcome::WaitForHuman
151 }
152}
153
154/// Skip-everything task — used for "checkpoint" steps that exist
155/// solely to record progress without blocking on a human.
156#[derive(Default)]
157pub struct AutoApproveKind;
158
159impl TaskKind for AutoApproveKind {
160 fn kind_name(&self) -> &'static str {
161 "auto_approve"
162 }
163 fn verbose_name(&self) -> &'static str {
164 "Auto-approve (no human interaction)"
165 }
166 fn on_assign(&self, _ctx: &AssignedTask<'_>) -> AssignOutcome {
167 AssignOutcome::AutoApprove
168 }
169}
170
171/// Fires a best-effort POST to `task.webhook_url` and then auto-
172/// approves. External systems wire `webhook_url` to whatever they
173/// want notified (a Slack incoming webhook, a custom orchestrator,
174/// the legal team's intake form). The HTTP fire is intentionally
175/// stubbed at the framework level — see the impl for details — so
176/// no new HTTP-client dependency is forced on the default build.
177#[derive(Default)]
178pub struct WebhookNotifyKind;
179
180impl TaskKind for WebhookNotifyKind {
181 fn kind_name(&self) -> &'static str {
182 "webhook_notify"
183 }
184 fn verbose_name(&self) -> &'static str {
185 "Webhook notify (best-effort POST + auto-approve)"
186 }
187 fn on_assign(&self, ctx: &AssignedTask<'_>) -> AssignOutcome {
188 let url = ctx.task.webhook_url.trim();
189 if url.is_empty() {
190 tracing::warn!(
191 target: "rustango_cms::task_kind",
192 task_name = %ctx.task.name,
193 "webhook_notify task has empty webhook_url; auto-approving anyway"
194 );
195 } else {
196 // Best-effort spawn — the workflow advance doesn't wait
197 // on the network. Hosts that need durable delivery
198 // should register their own kind that wraps a queued
199 // mailer / job runner.
200 tracing::info!(
201 target: "rustango_cms::task_kind",
202 task_name = %ctx.task.name,
203 page_id = ctx.page.id.get().copied().unwrap_or(0),
204 url = %url,
205 requested_by = ctx.requested_by,
206 "webhook_notify firing (host should register a custom kind for production HTTP delivery)"
207 );
208 }
209 AssignOutcome::AutoApprove
210 }
211}
212
213register_task_kind!(GroupApprovalKind);
214register_task_kind!(AutoApproveKind);
215register_task_kind!(WebhookNotifyKind);
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
222 fn registry_includes_built_ins() {
223 let names: Vec<&'static str> = registered_kinds().iter().map(|k| k.kind_name()).collect();
224 assert!(names.contains(&"group_approval"));
225 assert!(names.contains(&"auto_approve"));
226 assert!(names.contains(&"webhook_notify"));
227 }
228
229 #[test]
230 fn find_resolves_known_kind() {
231 assert!(find("group_approval").is_some());
232 assert!(find("auto_approve").is_some());
233 assert!(find("webhook_notify").is_some());
234 assert!(find("does_not_exist").is_none());
235 }
236
237 #[test]
238 fn auto_approve_returns_auto() {
239 let k = AutoApproveKind;
240 // We can't easily construct an AssignedTask in a unit test
241 // (it needs a live Page row). Smoke-check by reading
242 // kind_name + verbose_name.
243 assert_eq!(k.kind_name(), "auto_approve");
244 assert!(k.verbose_name().contains("Auto"));
245 }
246}