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, Repository,
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 and project membership are deliberately outside it — an existing item is never
28/// moved, and no caller writes labels this way — and so is creation, which is a copy's. Its
29/// `repositories` list is a field of the item like its title, and is replaced whole.
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 /// Replaces the task's [`Task::repositories`] whole; an empty list clears it. Where the
66 /// item's issue lives is never moved by it: it is the list the item names, as a read
67 /// reports it.
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub repositories: Option<Vec<Repository>>,
70 /// Replaces every person the task is assigned to with exactly these — empty unassigns.
71 /// The engine names at most one, and only to a source declaring
72 /// [`Capabilities::assignees`](crate::Capabilities::assignees). A source refuses a person
73 /// it cannot assign, naming them, rather than writing the rest without them.
74 // llmlint: ignore[invalid_states_unrepresentable] The same list `Task::assignees` reads, so `applied_to` and `changed` compare one shape and a source checks its write's answer against what it asked for; the one-person rule is the engine's, refused before any source is asked.
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub assignees: Option<Vec<String>>,
77 /// Close the task as a duplicate of this one, the survivor — a decision its caller made,
78 /// which the store never makes on its own. Valid only beside a `cancelled` status, or with
79 /// no status named, when it implies `cancelled`; any other status is refused by
80 /// [`consistent`](Self::consistent), writing nothing.
81 ///
82 /// A source closes it natively where its backend can — GitHub's duplicate closure, Linear's
83 /// duplicate relation — and every source records the typed `duplicate` link in the task's
84 /// metadata, so a later read reports it `cancelled` with that link.
85 // llmlint: ignore[invalid_states_unrepresentable] `duplicate_of: Option<TaskRef>` beside `status` is the shape the store-fixes contract fixes by name and type, which onefollowup and onepipeline build against; the one state it can express that is no update — a duplicate close beside a status other than `cancelled` — is refused by `consistent` before any source is read or written, in one wording every source and the engine share, as `metadata_set` beside `metadata_remove` is above.
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub duplicate_of: Option<TaskRef>,
88}
89
90impl TaskUpdate {
91 /// Whether this update names no field at all.
92 #[must_use]
93 pub fn is_empty(&self) -> bool {
94 self.title.is_none()
95 && self.content.is_none()
96 && self.status.is_none()
97 && self.priority.is_none()
98 && self.metadata_set.is_empty()
99 && self.metadata_remove.is_empty()
100 && self.delivers.is_none()
101 && self.depends_on.is_none()
102 && self.repositories.is_none()
103 && self.assignees.is_none()
104 && self.duplicate_of.is_none()
105 }
106
107 /// Whether this update names `field`, which is the only way a source may report it written.
108 #[must_use]
109 pub fn names(&self, field: UpdatedField) -> bool {
110 match field {
111 UpdatedField::Title => self.title.is_some(),
112 UpdatedField::Content => self.content.is_some(),
113 UpdatedField::Status => self.status.is_some(),
114 UpdatedField::Priority => self.priority.is_some(),
115 UpdatedField::Metadata => {
116 !self.metadata_set.is_empty() || !self.metadata_remove.is_empty()
117 }
118 UpdatedField::Delivers => self.delivers.is_some(),
119 UpdatedField::DependsOn => self.depends_on.is_some(),
120 UpdatedField::Repositories => self.repositories.is_some(),
121 UpdatedField::Assignees => self.assignees.is_some(),
122 UpdatedField::DuplicateOf => self.duplicate_of.is_some(),
123 }
124 }
125
126 /// The status this update writes: the one it names, or `cancelled` for an update closing
127 /// the task as a duplicate that names none.
128 #[must_use]
129 pub fn effective_status(&self) -> Option<Status> {
130 match (&self.status, &self.duplicate_of) {
131 (Some(status), _) => Some(status.clone()),
132 (None, Some(_)) => Some(Status {
133 category: crate::StatusCategory::Cancelled,
134 name: "cancelled".to_owned(),
135 }),
136 (None, None) => None,
137 }
138 }
139
140 /// Every metadata key this update both sets and removes, in order.
141 ///
142 /// An update naming one is refused before anything is written: which of the two it meant
143 /// is not something a source may guess.
144 #[must_use]
145 pub fn contradictions(&self) -> Vec<&MetadataKey> {
146 self.metadata_remove
147 .iter()
148 .filter(|key| self.metadata_set.contains_key(*key))
149 .collect()
150 }
151
152 /// The refusal of an update that both sets and removes a key, or `Ok` when it does not.
153 ///
154 /// Spelled once here, so every source and the engine refuse it in the same words.
155 ///
156 /// # Errors
157 ///
158 /// Returns [`SourceError::Refused`] naming every such key, and for an update closing the
159 /// task as a duplicate beside a status other than `cancelled`.
160 pub fn consistent(&self) -> Result<(), SourceError> {
161 if let (Some(survivor), Some(status)) = (&self.duplicate_of, &self.status)
162 && status.category != crate::StatusCategory::Cancelled
163 {
164 return Err(SourceError::Refused {
165 message: format!(
166 "this update closes the task as a duplicate of {survivor}, which leaves it \
167 cancelled, and names the status {:?} beside it; next: name `cancelled`, or \
168 no status at all",
169 status.name
170 ),
171 });
172 }
173 let both = self.contradictions();
174 if both.is_empty() {
175 return Ok(());
176 }
177 let named: Vec<&str> = both.iter().map(|key| key.as_str()).collect();
178 Err(SourceError::Refused {
179 message: format!(
180 "this update both sets and removes the metadata {} {}; next: name each key \
181 either to set or to remove, not both",
182 if named.len() == 1 { "key" } else { "keys" },
183 named.join(", ")
184 ),
185 })
186 }
187
188 /// `task` as it reads once this update is applied to it: every named field replaced, every
189 /// named metadata key set or removed, and everything else exactly as it was.
190 ///
191 /// [`depends_on`](Self::depends_on) is not a member of a [`Task`], so it is not applied
192 /// here.
193 #[must_use]
194 pub fn applied_to(&self, task: &Task) -> Task {
195 let mut updated = task.clone();
196 if let Some(title) = &self.title {
197 updated.title.clone_from(title);
198 }
199 if let Some(content) = &self.content {
200 updated.content = Some(content.clone());
201 }
202 if let Some(status) = &self.status {
203 updated.status = status.clone();
204 }
205 if let Some(priority) = self.priority {
206 updated.priority = priority;
207 }
208 for (key, value) in &self.metadata_set {
209 updated
210 .metadata
211 .insert(key.as_str().to_owned(), value.clone());
212 }
213 for key in &self.metadata_remove {
214 updated.metadata.remove(key.as_str());
215 }
216 if let Some(delivers) = &self.delivers {
217 updated.delivers.clone_from(delivers);
218 }
219 if let Some(repositories) = &self.repositories {
220 updated.repositories.clone_from(repositories);
221 }
222 if let Some(assignees) = &self.assignees {
223 updated.assignees = Some(assignees.clone());
224 }
225 updated
226 }
227
228 /// The fields this update names whose value differs between `before` and `after` — which,
229 /// for a source that compares before it writes, is exactly what it wrote.
230 ///
231 /// [`UpdatedField::DependsOn`] is never among them: a [`Task`] carries no edges, so a
232 /// source says whether it wrote those itself.
233 #[must_use]
234 pub fn changed(&self, before: &Task, after: &Task) -> BTreeSet<UpdatedField> {
235 let mut written = BTreeSet::new();
236 if self.title.is_some() && before.title != after.title {
237 written.insert(UpdatedField::Title);
238 }
239 if self.content.is_some() && before.content != after.content {
240 written.insert(UpdatedField::Content);
241 }
242 if self.status.is_some() && before.status != after.status {
243 written.insert(UpdatedField::Status);
244 }
245 if self.priority.is_some() && before.priority != after.priority {
246 written.insert(UpdatedField::Priority);
247 }
248 let named = self
249 .metadata_set
250 .keys()
251 .chain(&self.metadata_remove)
252 .map(MetadataKey::as_str);
253 if named
254 .into_iter()
255 .any(|key| before.metadata.get(key) != after.metadata.get(key))
256 {
257 written.insert(UpdatedField::Metadata);
258 }
259 if self.delivers.is_some() && before.delivers != after.delivers {
260 written.insert(UpdatedField::Delivers);
261 }
262 if self.repositories.is_some() && before.repositories != after.repositories {
263 written.insert(UpdatedField::Repositories);
264 }
265 if self.assignees.is_some()
266 && !crate::work::same_assignees(
267 before.assignees.as_deref().unwrap_or_default(),
268 after.assignees.as_deref().unwrap_or_default(),
269 )
270 {
271 written.insert(UpdatedField::Assignees);
272 }
273 written
274 }
275
276 /// Apply this update to the task `id` of `source` by rewriting it: read it, apply the
277 /// update, and — only when anything differs — [`write_task`](TaskSource::write_task) it
278 /// with its `target` set, then read it back. `None` when `source` holds no such task.
279 ///
280 /// This is what [`TaskSource::update_task`] does for a source that does not override it,
281 /// and it is public so a host forwarding the call to a peer that does not declare the
282 /// targeted update can fall back to exactly it. It is correct and not minimal: a write it
283 /// makes rewrites the whole item, and a source that can send less owes an override.
284 ///
285 /// The forward edges are read whenever they are needed — to compare against a named
286 /// `depends_on`, or to carry unchanged through a rewrite a named `depends_on` does not
287 /// replace — because a [`write_task`](TaskSource::write_task) replaces them.
288 ///
289 /// # Errors
290 ///
291 /// Returns [`SourceError::Refused`] for an update that both sets and removes a key,
292 /// [`SourceError::Malformed`] when the write answers an id other than `id` or the task could
293 /// not be read back after it, and
294 /// whatever the source's own read or write fails with.
295 pub async fn rewrite<S: TaskSource + ?Sized>(
296 &self,
297 source: &S,
298 id: &NativeId,
299 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
300 self.consistent()?;
301 let Some(held) = source.get_task(id).await? else {
302 return Ok(None);
303 };
304 let updated = self.applied_to(&held);
305 let (depends_on, edges_differ) = match &self.depends_on {
306 Some(wanted) => {
307 let current = forward_edges(source, id).await?;
308 (wanted.clone(), !same_edges(¤t, wanted))
309 }
310 None if updated != held => (forward_edges(source, id).await?, false),
311 None => (Vec::new(), false),
312 };
313 if updated == held && !edges_differ {
314 return Ok(Some(TaskUpdateOutcome {
315 delivers_before: held.delivers.clone(),
316 task: held,
317 written: BTreeSet::new(),
318 }));
319 }
320 let wrote = source
321 .write_task(&ItemWrite {
322 target: Some(id.clone()),
323 item: updated,
324 depends_on,
325 })
326 .await?;
327 // A write that names its target answers that target: another id means the source
328 // wrote some other record, and reading `id` back would report an update that never
329 // reached it.
330 if &wrote != id {
331 return Err(SourceError::Malformed {
332 message: format!(
333 "task {id} was updated, and the source answered that it wrote {wrote}"
334 ),
335 });
336 }
337 let task = source
338 .get_task(id)
339 .await?
340 .ok_or_else(|| SourceError::Malformed {
341 message: format!("task {id} was updated and then could not be read back"),
342 })?;
343 let mut written = self.changed(&held, &task);
344 if edges_differ {
345 written.insert(UpdatedField::DependsOn);
346 }
347 Ok(Some(TaskUpdateOutcome {
348 task,
349 written,
350 delivers_before: held.delivers,
351 }))
352 }
353}
354
355/// One field of a task a [`TaskUpdate`] names, as the answer to it reports what was written.
356///
357/// kebab-case on the wire. [`Metadata`](Self::Metadata) stands for every metadata key the
358/// update set or removed together; [`DependsOn`](Self::DependsOn) for the task's forward edges.
359#[derive(
360 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
361)]
362#[serde(rename_all = "kebab-case")]
363pub enum UpdatedField {
364 /// [`TaskUpdate::title`].
365 Title,
366 /// [`TaskUpdate::content`].
367 Content,
368 /// [`TaskUpdate::status`].
369 Status,
370 /// [`TaskUpdate::priority`].
371 Priority,
372 /// [`TaskUpdate::metadata_set`] and [`TaskUpdate::metadata_remove`].
373 Metadata,
374 /// [`TaskUpdate::delivers`].
375 Delivers,
376 /// [`TaskUpdate::depends_on`].
377 DependsOn,
378 /// [`TaskUpdate::repositories`].
379 Repositories,
380 /// [`TaskUpdate::assignees`].
381 Assignees,
382 /// [`TaskUpdate::duplicate_of`]: the task was closed as a duplicate, natively or by the
383 /// link the store records.
384 DuplicateOf,
385}
386
387/// What a source answers a [`TaskUpdate`] of a task it holds with.
388///
389/// Everything the engine reports about the call is read off this, so the engine sends no read
390/// of its own before or after it: `task` is what it answers with, `written` is what it says
391/// was written, and `delivers_before` is what tells it which delivered tasks the update
392/// dropped.
393#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
394pub struct TaskUpdateOutcome {
395 /// The task as this source reads it once the update landed.
396 pub task: Task,
397 /// The fields this source actually wrote — empty when nothing differed, and never a field
398 /// the update did not name. Required on the wire: an answer that leaves it out has not said
399 /// what it wrote, which is not the same as having written nothing.
400 pub written: BTreeSet<UpdatedField>,
401 /// The task's [`Task::delivers`] as this source held it before the update, which is the
402 /// list a named `delivers` replaced. Required on the wire, for the reason `written` is: an
403 /// answer leaving it out would hide every delivered task the update dropped.
404 pub delivers_before: Vec<TaskRef>,
405}
406
407/// Every forward dependency edge `source` reports at `id`, walked to exhaustion.
408async fn forward_edges<S: TaskSource + ?Sized>(
409 source: &S,
410 id: &NativeId,
411) -> Result<Vec<DependencyEdge>, SourceError> {
412 let limit = source.capabilities().max_page_size.max(1);
413 let mut edges = Vec::new();
414 let mut cursor = None;
415 loop {
416 let page = source
417 .task_dependencies(id, Direction::DependsOn, &PageRequest { cursor, limit })
418 .await?;
419 edges.extend(page.items);
420 match page.next {
421 Some(next) => cursor = Some(next),
422 None => return Ok(edges),
423 }
424 }
425}
426
427/// Whether two edge lists name the same far ends by the same kinds, whatever their order and
428/// whatever each says its near end is.
429fn same_edges(held: &[DependencyEdge], wanted: &[DependencyEdge]) -> bool {
430 let far = |edges: &[DependencyEdge]| -> BTreeSet<(String, String, String)> {
431 edges
432 .iter()
433 .map(|edge| {
434 (
435 edge.to.id().to_owned(),
436 format!("{:?}", edge.to.kind),
437 format!("{:?}", edge.kind),
438 )
439 })
440 .collect()
441 };
442 held.len() == wanted.len() && far(held) == far(wanted)
443}