onetaskgraph_plugin_api/update.rs
1//! A targeted update of one existing task: every field a caller names, and nothing else.
2//!
3//! The narrow writes each change one field in one call, and a copy rewrites the whole item. A
4//! caller whose change touches a status and several metadata keys at once needs neither: this
5//! names exactly the fields that changed, and a source applies them in as few writes as it
6//! can, sending nothing for a field that already holds the requested value.
7//!
8//! The source's answer carries everything the engine reports about the call — the task read
9//! back, the fields it wrote, and the `delivers` it held before — so the engine reads nothing
10//! of its own around it. That is the difference between one read of an item and two on a
11//! hosted backend, on every update.
12
13use std::collections::{BTreeMap, BTreeSet};
14
15use schemars::JsonSchema;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use crate::{
20 DependencyEdge, Direction, ItemWrite, MetadataKey, NativeId, PageRequest, Priority,
21 SourceError, Status, Task, TaskRef, TaskSource,
22};
23
24/// A targeted update of one existing task. A member left `None` (or empty) leaves that field
25/// exactly as the source holds it.
26///
27/// Labels, repositories and project membership are deliberately outside it — an existing
28/// item is never moved, and no caller writes labels this way — and so is creation, which is a
29/// copy's.
30#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
31pub struct TaskUpdate {
32 /// The task's title.
33 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub title: Option<String>,
35 /// `Task::content` exactly as a read reports it; a metadata block the source keeps in the
36 /// same backend field is kept byte for byte.
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub content: Option<String>,
39 /// Name and category. A source that keeps status names stores the name; one that maps by
40 /// category (GitHub Projects) writes its mapped option, exactly as `write_task` does, and
41 /// refuses a category it has disabled in the same words.
42 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub status: Option<Status>,
44 /// The task's priority; `none` clears it.
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub priority: Option<Priority>,
47 // llmlint: ignore-block[invalid_states_unrepresentable] `metadata_set` and `metadata_remove` are two members because Contract 1 of the `graphql-writeback-quota` project record fixes them by name and type, and onepipeline builds against exactly this shape; the one state they can express that is not an update — one key in both — is refused by `consistent` before any source is read or written, in one wording every source and the engine share. A single map of key to set-or-remove would be the contract's owner's change to make, not this crate's.
48 /// Keys added or replaced; every other key is kept.
49 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
50 #[schemars(!skip_serializing_if)]
51 pub metadata_set: BTreeMap<MetadataKey, Value>,
52 /// Keys removed; a key the task does not hold is no write. Refused when it names a key
53 /// `metadata_set` also names.
54 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
55 #[schemars(!skip_serializing_if)]
56 pub metadata_remove: BTreeSet<MetadataKey>,
57 // llmlint: ignore-end[invalid_states_unrepresentable]
58 /// Replaces the list; the engine keeps each ticket's `delivered_by` in step.
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub delivers: Option<Vec<TaskRef>>,
61 /// Replaces the task's forward dependency edges (`from` is this task); the source sends
62 /// only the difference.
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub depends_on: Option<Vec<DependencyEdge>>,
65}
66
67impl TaskUpdate {
68 /// Whether this update names no field at all.
69 #[must_use]
70 pub fn is_empty(&self) -> bool {
71 self.title.is_none()
72 && self.content.is_none()
73 && self.status.is_none()
74 && self.priority.is_none()
75 && self.metadata_set.is_empty()
76 && self.metadata_remove.is_empty()
77 && self.delivers.is_none()
78 && self.depends_on.is_none()
79 }
80
81 /// Whether this update names `field`, which is the only way a source may report it written.
82 #[must_use]
83 pub fn names(&self, field: UpdatedField) -> bool {
84 match field {
85 UpdatedField::Title => self.title.is_some(),
86 UpdatedField::Content => self.content.is_some(),
87 UpdatedField::Status => self.status.is_some(),
88 UpdatedField::Priority => self.priority.is_some(),
89 UpdatedField::Metadata => {
90 !self.metadata_set.is_empty() || !self.metadata_remove.is_empty()
91 }
92 UpdatedField::Delivers => self.delivers.is_some(),
93 UpdatedField::DependsOn => self.depends_on.is_some(),
94 }
95 }
96
97 /// Every metadata key this update both sets and removes, in order.
98 ///
99 /// An update naming one is refused before anything is written: which of the two it meant
100 /// is not something a source may guess.
101 #[must_use]
102 pub fn contradictions(&self) -> Vec<&MetadataKey> {
103 self.metadata_remove
104 .iter()
105 .filter(|key| self.metadata_set.contains_key(*key))
106 .collect()
107 }
108
109 /// The refusal of an update that both sets and removes a key, or `Ok` when it does not.
110 ///
111 /// Spelled once here, so every source and the engine refuse it in the same words.
112 ///
113 /// # Errors
114 ///
115 /// Returns [`SourceError::Refused`] naming every such key.
116 pub fn consistent(&self) -> Result<(), SourceError> {
117 let both = self.contradictions();
118 if both.is_empty() {
119 return Ok(());
120 }
121 let named: Vec<&str> = both.iter().map(|key| key.as_str()).collect();
122 Err(SourceError::Refused {
123 message: format!(
124 "this update both sets and removes the metadata {} {}; next: name each key \
125 either to set or to remove, not both",
126 if named.len() == 1 { "key" } else { "keys" },
127 named.join(", ")
128 ),
129 })
130 }
131
132 /// `task` as it reads once this update is applied to it: every named field replaced, every
133 /// named metadata key set or removed, and everything else exactly as it was.
134 ///
135 /// [`depends_on`](Self::depends_on) is not a member of a [`Task`], so it is not applied
136 /// here.
137 #[must_use]
138 pub fn applied_to(&self, task: &Task) -> Task {
139 let mut updated = task.clone();
140 if let Some(title) = &self.title {
141 updated.title.clone_from(title);
142 }
143 if let Some(content) = &self.content {
144 updated.content = Some(content.clone());
145 }
146 if let Some(status) = &self.status {
147 updated.status = status.clone();
148 }
149 if let Some(priority) = self.priority {
150 updated.priority = priority;
151 }
152 for (key, value) in &self.metadata_set {
153 updated
154 .metadata
155 .insert(key.as_str().to_owned(), value.clone());
156 }
157 for key in &self.metadata_remove {
158 updated.metadata.remove(key.as_str());
159 }
160 if let Some(delivers) = &self.delivers {
161 updated.delivers.clone_from(delivers);
162 }
163 updated
164 }
165
166 /// The fields this update names whose value differs between `before` and `after` — which,
167 /// for a source that compares before it writes, is exactly what it wrote.
168 ///
169 /// [`UpdatedField::DependsOn`] is never among them: a [`Task`] carries no edges, so a
170 /// source says whether it wrote those itself.
171 #[must_use]
172 pub fn changed(&self, before: &Task, after: &Task) -> BTreeSet<UpdatedField> {
173 let mut written = BTreeSet::new();
174 if self.title.is_some() && before.title != after.title {
175 written.insert(UpdatedField::Title);
176 }
177 if self.content.is_some() && before.content != after.content {
178 written.insert(UpdatedField::Content);
179 }
180 if self.status.is_some() && before.status != after.status {
181 written.insert(UpdatedField::Status);
182 }
183 if self.priority.is_some() && before.priority != after.priority {
184 written.insert(UpdatedField::Priority);
185 }
186 let named = self
187 .metadata_set
188 .keys()
189 .chain(&self.metadata_remove)
190 .map(MetadataKey::as_str);
191 if named
192 .into_iter()
193 .any(|key| before.metadata.get(key) != after.metadata.get(key))
194 {
195 written.insert(UpdatedField::Metadata);
196 }
197 if self.delivers.is_some() && before.delivers != after.delivers {
198 written.insert(UpdatedField::Delivers);
199 }
200 written
201 }
202
203 /// Apply this update to the task `id` of `source` by rewriting it: read it, apply the
204 /// update, and — only when anything differs — [`write_task`](TaskSource::write_task) it
205 /// with its `target` set, then read it back. `None` when `source` holds no such task.
206 ///
207 /// This is what [`TaskSource::update_task`] does for a source that does not override it,
208 /// and it is public so a host forwarding the call to a peer that does not declare the
209 /// targeted update can fall back to exactly it. It is correct and not minimal: a write it
210 /// makes rewrites the whole item, and a source that can send less owes an override.
211 ///
212 /// The forward edges are read whenever they are needed — to compare against a named
213 /// `depends_on`, or to carry unchanged through a rewrite a named `depends_on` does not
214 /// replace — because a [`write_task`](TaskSource::write_task) replaces them.
215 ///
216 /// # Errors
217 ///
218 /// Returns [`SourceError::Refused`] for an update that both sets and removes a key,
219 /// [`SourceError::Malformed`] when the write answers an id other than `id` or the task could
220 /// not be read back after it, and
221 /// whatever the source's own read or write fails with.
222 pub async fn rewrite<S: TaskSource + ?Sized>(
223 &self,
224 source: &S,
225 id: &NativeId,
226 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
227 self.consistent()?;
228 let Some(held) = source.get_task(id).await? else {
229 return Ok(None);
230 };
231 let updated = self.applied_to(&held);
232 let (depends_on, edges_differ) = match &self.depends_on {
233 Some(wanted) => {
234 let current = forward_edges(source, id).await?;
235 (wanted.clone(), !same_edges(¤t, wanted))
236 }
237 None if updated != held => (forward_edges(source, id).await?, false),
238 None => (Vec::new(), false),
239 };
240 if updated == held && !edges_differ {
241 return Ok(Some(TaskUpdateOutcome {
242 delivers_before: held.delivers.clone(),
243 task: held,
244 written: BTreeSet::new(),
245 }));
246 }
247 let wrote = source
248 .write_task(&ItemWrite {
249 target: Some(id.clone()),
250 item: updated,
251 depends_on,
252 })
253 .await?;
254 // A write that names its target answers that target: another id means the source
255 // wrote some other record, and reading `id` back would report an update that never
256 // reached it.
257 if &wrote != id {
258 return Err(SourceError::Malformed {
259 message: format!(
260 "task {id} was updated, and the source answered that it wrote {wrote}"
261 ),
262 });
263 }
264 let task = source
265 .get_task(id)
266 .await?
267 .ok_or_else(|| SourceError::Malformed {
268 message: format!("task {id} was updated and then could not be read back"),
269 })?;
270 let mut written = self.changed(&held, &task);
271 if edges_differ {
272 written.insert(UpdatedField::DependsOn);
273 }
274 Ok(Some(TaskUpdateOutcome {
275 task,
276 written,
277 delivers_before: held.delivers,
278 }))
279 }
280}
281
282/// One field of a task a [`TaskUpdate`] names, as the answer to it reports what was written.
283///
284/// kebab-case on the wire. [`Metadata`](Self::Metadata) stands for every metadata key the
285/// update set or removed together; [`DependsOn`](Self::DependsOn) for the task's forward edges.
286#[derive(
287 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
288)]
289#[serde(rename_all = "kebab-case")]
290pub enum UpdatedField {
291 /// [`TaskUpdate::title`].
292 Title,
293 /// [`TaskUpdate::content`].
294 Content,
295 /// [`TaskUpdate::status`].
296 Status,
297 /// [`TaskUpdate::priority`].
298 Priority,
299 /// [`TaskUpdate::metadata_set`] and [`TaskUpdate::metadata_remove`].
300 Metadata,
301 /// [`TaskUpdate::delivers`].
302 Delivers,
303 /// [`TaskUpdate::depends_on`].
304 DependsOn,
305}
306
307/// What a source answers a [`TaskUpdate`] of a task it holds with.
308///
309/// Everything the engine reports about the call is read off this, so the engine sends no read
310/// of its own before or after it: `task` is what it answers with, `written` is what it says
311/// was written, and `delivers_before` is what tells it which delivered tasks the update
312/// dropped.
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
314pub struct TaskUpdateOutcome {
315 /// The task as this source reads it once the update landed.
316 pub task: Task,
317 /// The fields this source actually wrote — empty when nothing differed, and never a field
318 /// the update did not name. Required on the wire: an answer that leaves it out has not said
319 /// what it wrote, which is not the same as having written nothing.
320 pub written: BTreeSet<UpdatedField>,
321 /// The task's [`Task::delivers`] as this source held it before the update, which is the
322 /// list a named `delivers` replaced. Required on the wire, for the reason `written` is: an
323 /// answer leaving it out would hide every delivered task the update dropped.
324 pub delivers_before: Vec<TaskRef>,
325}
326
327/// Every forward dependency edge `source` reports at `id`, walked to exhaustion.
328async fn forward_edges<S: TaskSource + ?Sized>(
329 source: &S,
330 id: &NativeId,
331) -> Result<Vec<DependencyEdge>, SourceError> {
332 let limit = source.capabilities().max_page_size.max(1);
333 let mut edges = Vec::new();
334 let mut cursor = None;
335 loop {
336 let page = source
337 .task_dependencies(id, Direction::DependsOn, &PageRequest { cursor, limit })
338 .await?;
339 edges.extend(page.items);
340 match page.next {
341 Some(next) => cursor = Some(next),
342 None => return Ok(edges),
343 }
344 }
345}
346
347/// Whether two edge lists name the same far ends by the same kinds, whatever their order and
348/// whatever each says its near end is.
349fn same_edges(held: &[DependencyEdge], wanted: &[DependencyEdge]) -> bool {
350 let far = |edges: &[DependencyEdge]| -> BTreeSet<(String, String, String)> {
351 edges
352 .iter()
353 .map(|edge| {
354 (
355 edge.to.id().to_owned(),
356 format!("{:?}", edge.to.kind),
357 format!("{:?}", edge.kind),
358 )
359 })
360 .collect()
361 };
362 held.len() == wanted.len() && far(held) == far(wanted)
363}