Skip to main content

jmap_tasks_server/
workflow.rs

1//! The Task `workflowStatus` and `progress` rule (docs/design/DECISIONS.md
2//! decision 42; jmapio/jmap #465 against draft-ietf-jmap-tasks-06 §4).
3//!
4//! -06 says only "Must be one of the `TaskList`'s `workflowStatuses`. If set,
5//! `progress` MUST null", which leaves a task completed through
6//! `workflowStatus` looking unfinished to a JSCalendar or iCalendar reader.
7//! Decision 42 replaces it:
8//!
9//! - A `workflowStatus` that is one of the RFC 8984 §5.2.5 progress values
10//!   is mirrored into `progress` by the server; any other value (`pending`,
11//!   a list-defined one) leaves `progress` `null`. A changed `progress`,
12//!   including one the mirror clears, also sets `progressUpdated` (RFC
13//!   8984 §5.2.6) to the current time, unless the client set it.
14//! - Setting `progress` to anything else while `workflowStatus` is set is
15//!   `invalidProperties` naming `progress`.
16//! - A `workflowStatus` not in the task list's `workflowStatuses` is
17//!   `invalidProperties` naming `workflowStatus`, on create, when the
18//!   update sets it, and when the update moves the task to another list.
19//! - Changing a list's `workflowStatuses` does not touch its tasks: an
20//!   update that neither sets `workflowStatus` nor moves the task is not
21//!   checked against the list.
22//!
23//! [`apply_workflow_status`] is the whole rule, on the Task as it would be
24//! stored. A [`TasksBackend`](crate::TasksBackend) runs it in the same
25//! critical section as the write, so a concurrent change of the list's
26//! `workflowStatuses` cannot slip a value past it.
27
28use jmap_types::{SetError, SetErrorType};
29use serde_json::{Map, Value};
30
31/// draft-ietf-jmap-tasks-06 §3: a `TaskList`'s `workflowStatuses` default,
32/// used when the list has none.
33pub const DEFAULT_WORKFLOW_STATUSES: &[&str] = &[
34    "completed",
35    "failed",
36    "in-process",
37    "needs-action",
38    "cancelled",
39    "pending",
40];
41
42/// The RFC 8984 §5.2.5 `progress` values that a `workflowStatus` mirrors.
43pub const PROGRESS_VALUES: &[&str] = &[
44    "needs-action",
45    "in-process",
46    "completed",
47    "failed",
48    "cancelled",
49];
50
51fn invalid(property: &str, description: &str) -> Box<SetError> {
52    Box::new(
53        SetError::new(SetErrorType::InvalidProperties)
54            .with_properties([property])
55            .with_description(description),
56    )
57}
58
59/// How a write reached [`apply_workflow_status`].
60#[derive(Debug, Clone, Copy)]
61pub enum WorkflowWrite<'a> {
62    /// A create (or a `Task/copy` into the account): every rule applies.
63    Create,
64    /// An update of `before`, whose top-level patched properties are
65    /// `written`.
66    Update {
67        /// The stored Task.
68        before: &'a Map<String, Value>,
69        /// The top-level properties the patch names.
70        written: &'a [String],
71    },
72}
73
74/// Apply decision 42 to `task`, the Task as it would be stored, in a list
75/// whose `workflowStatuses` is `list_statuses` (`None`: the list has none,
76/// or none is stored, so [`DEFAULT_WORKFLOW_STATUSES`]). `now` is the
77/// `UTCDate` a server-changed `progress` gives `progressUpdated`.
78///
79/// Returns whether the server changed `task` (`progress` or
80/// `progressUpdated`), so an update can echo it (RFC 8620 §5.3).
81///
82/// # Errors
83///
84/// `invalidProperties` naming `workflowStatus` or `progress`, as listed in
85/// the module docs.
86pub fn apply_workflow_status(
87    task: &mut Map<String, Value>,
88    write: WorkflowWrite<'_>,
89    list_statuses: Option<&[String]>,
90    now: &str,
91) -> Result<bool, Box<SetError>> {
92    let wrote_progress_updated = match write {
93        WorkflowWrite::Create => task_has(task, "progressUpdated"),
94        WorkflowWrite::Update { written, .. } => written.iter().any(|w| w == "progressUpdated"),
95    };
96    let (sets_status, sets_progress, moves) = match write {
97        WorkflowWrite::Create => (true, task_has(task, "progress"), false),
98        WorkflowWrite::Update { before, written } => (
99            written.iter().any(|w| w == "workflowStatus"),
100            written.iter().any(|w| w == "progress"),
101            before.get("taskListId") != task.get("taskListId"),
102        ),
103    };
104    let Some(status) = task
105        .get("workflowStatus")
106        .and_then(Value::as_str)
107        .map(str::to_owned)
108    else {
109        return Ok(false);
110    };
111    if sets_status || moves {
112        let allowed = match list_statuses {
113            Some(list) => list.contains(&status),
114            None => DEFAULT_WORKFLOW_STATUSES.contains(&status.as_str()),
115        };
116        if !allowed {
117            return Err(invalid(
118                "workflowStatus",
119                "workflowStatus is not one of the task list's workflowStatuses",
120            ));
121        }
122    }
123    if !sets_status && !sets_progress {
124        return Ok(false);
125    }
126    let mirrored = PROGRESS_VALUES
127        .contains(&status.as_str())
128        .then(|| Value::String(status.clone()));
129    let given = task.get("progress").filter(|v| !v.is_null()).cloned();
130    if sets_progress && given != mirrored {
131        return Err(invalid(
132            "progress",
133            "progress must match workflowStatus: the workflowStatus when it is a progress value, otherwise null",
134        ));
135    }
136    let previous = match write {
137        WorkflowWrite::Create => None,
138        WorkflowWrite::Update { before, .. } => before.get("progress").filter(|v| !v.is_null()),
139    };
140    let mut changed = given != mirrored;
141    match &mirrored {
142        Some(v) => {
143            task.insert("progress".to_owned(), v.clone());
144        }
145        None => {
146            task.remove("progress");
147        }
148    }
149    // "Whenever the server changes `progress` this way" (local spec
150    // {#workflow} rule 1; decision 42 "as for any `progress` change"):
151    // clearing it, e.g. `completed` to `pending`, is such a change too.
152    if previous != mirrored.as_ref() && !wrote_progress_updated {
153        task.insert("progressUpdated".to_owned(), Value::String(now.to_owned()));
154        changed = true;
155    }
156    Ok(changed)
157}
158
159fn task_has(task: &Map<String, Value>, k: &str) -> bool {
160    task.get(k).is_some_and(|v| !v.is_null())
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use serde_json::json;
167
168    const NOW: &str = "2026-11-19T12:00:00Z";
169
170    fn map(v: Value) -> Map<String, Value> {
171        v.as_object().cloned().unwrap()
172    }
173
174    /// Decision 42: a progress value mirrors; `progressUpdated` is set.
175    #[test]
176    fn a_progress_value_mirrors() {
177        let mut t = map(json!({ "taskListId": "L", "workflowStatus": "completed" }));
178        assert!(apply_workflow_status(&mut t, WorkflowWrite::Create, None, NOW).unwrap());
179        assert_eq!(t["progress"], "completed");
180        assert_eq!(t["progressUpdated"], NOW);
181    }
182
183    /// "pending" is a default workflowStatus but not an RFC 8984 progress
184    /// value: `progress` stays null.
185    #[test]
186    fn pending_leaves_progress_null() {
187        let mut t = map(json!({ "taskListId": "L", "workflowStatus": "pending" }));
188        assert!(!apply_workflow_status(&mut t, WorkflowWrite::Create, None, NOW).unwrap());
189        assert!(t.get("progress").is_none());
190    }
191
192    /// The same value given for both is not a conflict.
193    #[test]
194    fn matching_progress_is_accepted() {
195        let mut t = map(json!({ "workflowStatus": "in-process", "progress": "in-process" }));
196        apply_workflow_status(&mut t, WorkflowWrite::Create, None, NOW).unwrap();
197    }
198
199    /// An update that touches neither workflowStatus nor taskListId is
200    /// not checked against the list (its statuses may have changed).
201    #[test]
202    fn an_unrelated_update_skips_the_list_check() {
203        let before = map(json!({ "taskListId": "L", "workflowStatus": "in-review" }));
204        let mut t = map(json!({ "taskListId": "L", "workflowStatus": "in-review", "title": "x" }));
205        let written = vec!["title".to_owned()];
206        let w = WorkflowWrite::Update {
207            before: &before,
208            written: &written,
209        };
210        assert!(!apply_workflow_status(&mut t, w, Some(&[]), NOW).unwrap());
211    }
212}