onetaskgraph_plugin_api/source.rs
1//! The two traits a plugin implements, and the secret lookup it is handed.
2
3use std::cmp::Ordering;
4use std::collections::BTreeMap;
5
6use schemars::{JsonSchema, Schema};
7use secrecy::SecretString;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::{
12 Asset, AssetName, AssetWrite, AssetsWritten, Capabilities, Classification, Comment,
13 CommentBody, CommentCopy, DependencyEdge, Direction, Document, DocumentQuery,
14 DocumentVersionCoverage, IssueHolding, IssueRef, ItemKind, ItemWrite, Label, Location,
15 MetadataKey, MetadataRecord, Metering, NativeId, NewComment, Page, PageRequest, Priority,
16 Project, ProjectQuery, ProjectVersionCoverage, Repository, SharedClock, SourceError,
17 SourceName, Status, StatusCategory, StatusContradiction, Task, TaskDetailRead, TaskQuery,
18 TaskRef, TaskUpdate, TaskUpdateOutcome, VersionCoverage, Visibility, WriteJournal,
19 WriteSupport, WriteTarget, assetless, commentless, documentless, unwritable, unwritable_field,
20 unwritable_metadata,
21};
22
23/// Whether a source is answering right now.
24///
25/// # Placement is an open contract question
26///
27/// This type lives here because [`TaskSource::health`] returns it and the trait
28/// lives here: placing it in `onetaskgraph-core` would make this crate depend on
29/// the engine and invert the one direction the crate split exists to establish.
30/// The approved contract enumerates this crate's contents exhaustively and does
31/// not name `Health`, so the enumeration and the trait as written cannot both
32/// stand. Compiling forces the placement below; the resolution — add it to the
33/// enumeration, or redesign `health` so no such type crosses the boundary —
34/// belongs to the contract's owner, not to this crate. See `AGENTS.md`.
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
36// llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this restates at a new site the justification already recorded at `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs), and a third time in this type's own doc comment above and in AGENTS.md's "Open contract question — `Health`": `Health`'s shape is approved contract text that `TaskSource::health` returns, so an enum here would change the serialized form and the trait six undispatched nodes implement. That is the contract owner's call, not this crate's.
37pub struct Health {
38 /// Whether the source answered.
39 ///
40 /// A bare `bool` beside an untyped `detail` cannot say that an unreachable source
41 /// must explain itself, or keep "reachable with a warning" apart from "reachable";
42 /// an enum carrying the detail in its unreachable variant would.
43 // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
44 // restates at this field the justification already recorded at
45 // `Capabilities.max_page_size` (capability.rs), `PageRequest.limit` (query.rs), this
46 // type's own doc comment above, and AGENTS.md's "Open contract question — `Health`":
47 // `Health`'s shape is approved contract text that `TaskSource::health` returns, so an
48 // enum here would change the serialized form and the trait six undispatched nodes
49 // implement. That is the contract owner's call, not this crate's.
50 // llmlint: ignore[boundary_inputs_validated] making "unreachable with no reason given" unrepresentable means an enum here, which changes the serialized form and the trait six undispatched nodes implement. Deferred to the contract's owner — AGENTS.md, "Open contract question — `Health`".
51 pub reachable: bool,
52 /// What the source said, when it said anything useful.
53 pub detail: Option<String>,
54}
55
56/// The task query whose [`TaskQuery::origin_matches`] is the one statement of what "copied
57/// from `origin`" means, so the by-origin defaults read a project's and a document's entry
58/// exactly as a task's is read.
59fn origin_query(origin: &str) -> TaskQuery {
60 TaskQuery {
61 origin: Some(origin.to_owned()),
62 ..TaskQuery::default()
63 }
64}
65
66/// Refuse a page of the listing a by-origin default walks that holds more rows than it was
67/// asked for, in the words the engine refuses one in: a source may return fewer and never
68/// more, and a default that narrowed such a page would hide the defect behind it.
69fn overran(returned: usize, asked_for: u32) -> Result<(), SourceError> {
70 if returned as u64 <= u64::from(asked_for) {
71 return Ok(());
72 }
73 Err(SourceError::Malformed {
74 message: format!(
75 "the source returned {returned} rows for a page of at most {asked_for}; a source \
76 may return fewer than it was asked for and never more"
77 ),
78 })
79}
80
81/// What a by-origin default answers when the listing it walks hands back a cursor it has
82/// already handed out, which would walk forever.
83fn repeated_cursor() -> SourceError {
84 SourceError::Malformed {
85 message: "the source returned a cursor it had already handed out while its listing \
86 was walked for one origin, so the walk would never end"
87 .to_owned(),
88 }
89}
90
91/// The page `page` asks for of `matched`, every item a by-origin default kept: the cursor
92/// it hands out is the position of the next match, so a walk of its pages neither repeats
93/// nor drops one while the listing under it holds still.
94fn page_of_matches<T>(matched: Vec<T>, page: &PageRequest) -> Result<Page<T>, SourceError> {
95 let start = match &page.cursor {
96 None => 0,
97 Some(cursor) => cursor
98 .0
99 .strip_prefix(MATCHED_PAGE_CURSOR)
100 .and_then(|position| position.parse::<usize>().ok())
101 .filter(|position| *position <= matched.len())
102 .ok_or_else(|| SourceError::Refused {
103 message: format!(
104 "cursor {:?} was not handed out by this by-origin listing; start the walk \
105 again without one",
106 cursor.0
107 ),
108 })?,
109 };
110 let end = start.saturating_add(page.limit as usize).min(matched.len());
111 let next = (end < matched.len()).then(|| crate::Cursor(format!("{MATCHED_PAGE_CURSOR}{end}")));
112 Ok(Page {
113 items: matched.into_iter().skip(start).take(end - start).collect(),
114 next,
115 })
116}
117
118const MATCHED_PAGE_CURSOR: &str = "origin:";
119
120/// One configured source, as the engine drives it.
121///
122/// Dyn-compatible through `async_trait` because the engine holds
123/// `Vec<Box<dyn TaskSource>>` over heterogeneous plugins.
124///
125/// Three rules bind every implementation, and the engine's compensation is only
126/// correct while all three hold:
127///
128/// 1. **Apply** every predicate you declare [`Support::Native`](crate::Support::Native).
129/// 2. **Ignore** every [`Support`](crate::Support)-typed predicate you declare
130/// `Unsupported` — return the *wider* result set, never a narrower one.
131/// Silently dropping rows for a predicate you did not declare is the one
132/// failure no test above the plugin can catch.
133/// 3. Never return a silently empty dependency read. Rule 2 reaches the
134/// `Support`-typed *predicates* alone; a dependency read is always real, and so is a
135/// document read — [`Capabilities::documents`] says whether this source has documents
136/// at all, and a source that says it has none is never asked for one rather than
137/// answering an empty page.
138#[async_trait::async_trait]
139pub trait TaskSource: Send + Sync {
140 /// The plugin kind that built this source, for display and for plan output.
141 fn kind(&self) -> &'static str;
142
143 /// What this source applies itself. Read once per query by the engine.
144 fn capabilities(&self) -> Capabilities;
145
146 /// How `a`, a [`Task::version`] this source gave one of its tasks, stands to `b`, another
147 /// it gave the same task: `Greater` when `a` is the later, `Less` when it is the earlier,
148 /// `Equal` when nothing the token covers changed between them, and `None` when the two
149 /// cannot be put in order — a value this source cannot read, or two versions its token
150 /// says differ without saying which came first.
151 ///
152 /// A token's format and its order are the one source's that spells it, so the engine asks
153 /// the source that gave both rather than reading inside either.
154 ///
155 /// Defaulted to equality alone: two identical tokens are one version, and any two others
156 /// are unordered, which a reader takes as *changed, read it again* and never as
157 /// unchanged. A source whose token says which of two versions is the later overrides it.
158 fn order_versions(&self, a: &str, b: &str) -> Option<Ordering> {
159 (a == b).then_some(Ordering::Equal)
160 }
161
162 /// Which parts of a task this source's [`Task::version`] vouches for, which is what the
163 /// store's local cache may serve a task's parts from.
164 ///
165 /// Defaulted to no part, which keeps the cache from ever serving what a token was never
166 /// promised to cover: a source overrides it only for the parts its token covers, as
167 /// `docs/plugin-protocol.md` §4.13d states them.
168 fn version_coverage(&self) -> VersionCoverage {
169 VersionCoverage::none(format!(
170 "the {} plugin does not declare that its change token covers a task",
171 self.kind()
172 ))
173 }
174
175 /// Which parts of a task a copy may take this source's unchanged [`Task::version`] as
176 /// vouching for, when it decides to skip a task its destination already holds as written:
177 /// the task's fields, its comments when the copy carries them, and its forward edges. A copy
178 /// skips only a task whose source covers every one of those it writes.
179 ///
180 /// Defaulted to [`version_coverage`](Self::version_coverage). A source overrides it only to
181 /// state, with its measured bound, a claim about a copy's skip that is not one the cache may
182 /// serve from — as `docs/plugin-protocol.md` §4.13d does for the one plugin that does.
183 fn copy_version_coverage(&self) -> VersionCoverage {
184 self.version_coverage()
185 }
186
187 /// Which parts of a project this source's [`Project::version`] vouches for, on the terms
188 /// of [`version_coverage`](Self::version_coverage).
189 ///
190 /// Defaulted to no part, for the same reason.
191 fn project_version_coverage(&self) -> ProjectVersionCoverage {
192 ProjectVersionCoverage::none(format!(
193 "the {} plugin does not declare that its change token covers a project",
194 self.kind()
195 ))
196 }
197
198 /// Which parts of a document this source's [`Document::version`] vouches for, on the terms
199 /// of [`version_coverage`](Self::version_coverage).
200 ///
201 /// Defaulted to no part, for the same reason.
202 fn document_version_coverage(&self) -> DocumentVersionCoverage {
203 DocumentVersionCoverage::none(format!(
204 "the {} plugin does not declare that its change token covers a document",
205 self.kind()
206 ))
207 }
208
209 /// Tell this source the store's local cache now stands in front of it.
210 ///
211 /// Called exactly once, by the cache as it wraps the source, before any read and before
212 /// any coverage is read — so a source whose token needs a part only a wider selection
213 /// carries can widen its reads here, and declare the coverage that widening buys. Never
214 /// carried over the plugin protocol, as [`version_coverage`](Self::version_coverage) is
215 /// not.
216 ///
217 /// Defaulted to doing nothing: a source not overriding it reads exactly as it did.
218 fn attach_cache(&self) {}
219
220 /// The change token the response that answered this source's last
221 /// [`Direction::DependsOn`] read of task `id` in this process spelled, or `None` when it
222 /// spelled none.
223 ///
224 /// What lets the store's cache keep a task's forward edges by the version they were read
225 /// at when nothing else in the command read the task: those edges are served only to a pin
226 /// that version is at or after, and never vouch for the task's own fields. Synchronous, and
227 /// never carried over the plugin protocol, as [`version_coverage`](Self::version_coverage)
228 /// is not.
229 ///
230 /// Defaulted to `None`: a source whose dependency read spells no token keeps its edges
231 /// remote unless a read of the task itself vouched for them.
232 fn forward_edges_version(&self, id: &NativeId) -> Option<String> {
233 let _ = id;
234 None
235 }
236
237 /// The change token the response that answered this source's last dependency read of the
238 /// `kind` item `id` in `direction`, from its first page, spelled — or `None` when it spelled
239 /// none — on the terms of [`forward_edges_version`](Self::forward_edges_version), which is
240 /// what it answers for a task's [`Direction::DependsOn`].
241 ///
242 /// What lets the store's cache keep a project's forward edges, and either kind's reverse
243 /// ones, by the version they were read at: a project's forward edges are served only where
244 /// [`project_version_coverage`](Self::project_version_coverage) covers them, reverse ones only
245 /// where [`reverse_edges_coverage`](Self::reverse_edges_coverage) covers that kind's, and each
246 /// only to a pin that version is at or after. Synchronous, and never
247 /// carried over the plugin protocol.
248 ///
249 /// Defaulted to [`forward_edges_version`](Self::forward_edges_version) for a task's forward
250 /// edges and to `None` for every other read, which keeps those remote.
251 fn edges_version(&self, kind: ItemKind, id: &NativeId, direction: Direction) -> Option<String> {
252 match (kind, direction) {
253 (ItemKind::Task, Direction::DependsOn) => self.forward_edges_version(id),
254 _ => None,
255 }
256 }
257
258 /// Whether this source's token for a `kind` item — [`Task::version`] or
259 /// [`Project::version`] — vouches for its reverse edges, what a [`Direction::DependedOnBy`]
260 /// read answers, so the store's cache may serve them.
261 ///
262 /// A reverse edge is recorded on another item, so a token vouches for one only where it
263 /// carries a part that moves whenever one is added to or removed from that other item —
264 /// which no part of an item's own fields does. Never carried over the plugin protocol.
265 ///
266 /// Defaulted to not covering them, with that reason.
267 fn reverse_edges_coverage(&self, kind: ItemKind) -> crate::Coverage {
268 crate::Coverage::Uncovered {
269 reason: format!(
270 "the {} plugin does not declare that its change token covers a {}'s reverse \
271 edges, which are recorded on the items that depend on it",
272 self.kind(),
273 match kind {
274 ItemKind::Task => "task",
275 ItemKind::Project => "project",
276 }
277 ),
278 }
279 }
280
281 /// What this source holds about task `id` — the item it read last in this process — that
282 /// a later write expecting that version of it could take instead of reading it again, or
283 /// `None` when it holds nothing of the kind.
284 ///
285 /// Opaque to the engine, which keeps it beside the cached task and hands it back through
286 /// [`prime_write`](Self::prime_write). Defaulted to `None`: a source whose writes read
287 /// nothing first has nothing to keep.
288 fn write_context(&self, id: &NativeId) -> Option<serde_json::Value> {
289 let _ = id;
290 None
291 }
292
293 /// What this source holds about the container every task of it shares — a board's field
294 /// and option ids — that a write could take instead of reading it, or `None`.
295 ///
296 /// Defaulted to `None`, on the terms of [`write_context`](Self::write_context).
297 fn board_context(&self) -> Option<serde_json::Value> {
298 None
299 }
300
301 /// Hold `context`, which [`write_context`](Self::write_context) gave for task `id` at a
302 /// version the caller expects it still at, and `board`, which
303 /// [`board_context`](Self::board_context) gave, so the next write of `id` takes them
304 /// instead of reading — answering whether it took them.
305 ///
306 /// A context this source cannot read is not taken, and the write then reads as it always
307 /// does. Defaulted to taking nothing.
308 fn prime_write(
309 &self,
310 id: &NativeId,
311 context: &serde_json::Value,
312 board: Option<&serde_json::Value>,
313 ) -> bool {
314 let _ = (id, context, board);
315 false
316 }
317
318 /// Drop whatever [`prime_write`](Self::prime_write) took for `id`, and the board context
319 /// with it, so the next write of it reads afresh.
320 fn unprime(&self, id: &NativeId) {
321 let _ = id;
322 }
323
324 /// Start recording every request this source sends, for [`end_journal`](Self::end_journal).
325 ///
326 /// The engine opens one journal around one write at a time. Defaulted to recording
327 /// nothing.
328 fn begin_journal(&self) {}
329
330 /// Stop recording, answering with every request sent since
331 /// [`begin_journal`](Self::begin_journal) — or `None` for a source that records none.
332 fn end_journal(&self) -> Option<WriteJournal> {
333 None
334 }
335
336 /// Whether the source is answering right now.
337 ///
338 /// # Errors
339 ///
340 /// Returns a [`SourceError`] when the check itself could not be made.
341 async fn health(&self) -> Result<Health, SourceError>;
342
343 /// The [`Designator`](crate::Designator) naming the tracker this source reads, built by
344 /// [`Designator::of_backend`](crate::Designator::of_backend) over the backend's own opaque
345 /// identifier of itself — or `None` for a backend with none, whose configuration may
346 /// declare a `public_alias` instead.
347 ///
348 /// At most one request. The engine keeps the answer per host, so a source is asked once.
349 /// The default is `None`.
350 ///
351 /// # Errors
352 ///
353 /// Returns a [`SourceError`] when the backend could not be asked.
354 async fn designator(&self) -> Result<Option<crate::Designator>, SourceError> {
355 Ok(None)
356 }
357
358 /// Fetch one task by its native id, or `None` when there is no such task.
359 ///
360 /// # Errors
361 ///
362 /// Returns a [`SourceError`] when the source could not answer.
363 async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
364
365 /// Fetch several tasks by their native ids, each with the first page of its comments
366 /// when `comments` names the page to read — one answer per id, in the order they were
367 /// given.
368 ///
369 /// Each answer is what [`get_task`](Self::get_task) answers for that id, so a task that
370 /// is not there is `Ok(None)` and a read that failed fails that id alone. Its
371 /// [`TaskDetailRead::comments`] is what [`task_comments`](Self::task_comments) answers
372 /// for `comments`. The engine passes `comments` only to a source declaring
373 /// [`Capabilities::comments`](crate::Capabilities::comments) native.
374 ///
375 /// Defaulted to exactly those calls, item by item, so a source that implements nothing
376 /// here answers as it always did. A source that can read many items — or an item and its
377 /// comments — in fewer requests than that overrides it, which is the whole reason it
378 /// exists: a caller holding twenty ids pays for one batch rather than forty reads.
379 async fn get_task_details(
380 &self,
381 ids: &[NativeId],
382 comments: Option<&PageRequest>,
383 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
384 let mut read = Vec::with_capacity(ids.len());
385 for id in ids {
386 read.push(match self.get_task(id).await {
387 Ok(Some(task)) => {
388 let comments = match comments {
389 Some(page) => Some(self.task_comments(id, page).await),
390 None => None,
391 };
392 Ok(Some(TaskDetailRead { task, comments }))
393 }
394 Ok(None) => Ok(None),
395 Err(error) => Err(error),
396 });
397 }
398 read
399 }
400
401 /// Fetch one project by its native id, or `None` when there is no such project.
402 ///
403 /// # Errors
404 ///
405 /// Returns a [`SourceError`] when the source could not answer.
406 async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
407
408 /// One page of the tasks matching `query`.
409 ///
410 /// # Errors
411 ///
412 /// Returns a [`SourceError`] when the source could not answer.
413 async fn query_tasks(
414 &self,
415 query: &TaskQuery,
416 page: &PageRequest,
417 ) -> Result<Page<Task>, SourceError>;
418
419 /// One page of the projects matching `query`.
420 ///
421 /// # Errors
422 ///
423 /// Returns a [`SourceError`] when the source could not answer.
424 async fn query_projects(
425 &self,
426 query: &ProjectQuery,
427 page: &PageRequest,
428 ) -> Result<Page<Project>, SourceError>;
429
430 /// One page of the projects whose [`TaskQuery::ORIGIN_KEY`] entry is a string equal to
431 /// `origin`, exactly — the projects copied from that qualified id, and none other.
432 ///
433 /// `origin` is compared byte for byte, on the terms [`TaskQuery::origin`] states, and is
434 /// never constructed or interpreted here. Zero, one or several projects may match; which
435 /// of several a caller wants is the caller's question.
436 ///
437 /// Defaulted to [`query_projects`](Self::query_projects) unfiltered, walked to its end on
438 /// every call and narrowed here, so a source that implements nothing answers exactly what
439 /// its own listing holds; the default's cursor is a position among the matches. A source
440 /// that can ask its store for one origin overrides it, which is the whole reason it
441 /// exists: a caller looking for the copies of one plan pays for those copies rather than
442 /// for every project the store holds.
443 ///
444 /// # Errors
445 ///
446 /// Returns a [`SourceError`] when the source could not answer, and
447 /// [`SourceError::Refused`] for a cursor the default did not hand out.
448 async fn query_projects_by_origin(
449 &self,
450 origin: &str,
451 page: &PageRequest,
452 ) -> Result<Page<Project>, SourceError> {
453 let wanted = origin_query(origin);
454 let mut matched = Vec::new();
455 let mut cursor: Option<crate::Cursor> = None;
456 // Every cursor the listing handed out, so one cycling through several is caught as
457 // one repeating the last is.
458 let mut visited: Vec<String> = Vec::new();
459 loop {
460 let listed = self
461 .query_projects(
462 &ProjectQuery::default(),
463 &PageRequest {
464 cursor: cursor.clone(),
465 limit: page.limit,
466 },
467 )
468 .await?;
469 overran(listed.items.len(), page.limit)?;
470 matched.extend(
471 listed
472 .items
473 .into_iter()
474 .filter(|project| wanted.origin_matches(&project.metadata)),
475 );
476 cursor = match listed.next {
477 None => break,
478 Some(next) if visited.contains(&next.0) => return Err(repeated_cursor()),
479 Some(next) => {
480 visited.push(next.0.clone());
481 Some(next)
482 }
483 };
484 }
485 page_of_matches(matched, page)
486 }
487
488 /// One page of every label this source knows.
489 ///
490 /// # Errors
491 ///
492 /// Returns a [`SourceError`] when the source could not answer.
493 async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
494
495 /// One page of the task dependency edges at `id`, in `direction`.
496 ///
497 /// # Errors
498 ///
499 /// Returns a [`SourceError`] when the source could not answer.
500 async fn task_dependencies(
501 &self,
502 id: &NativeId,
503 direction: Direction,
504 page: &PageRequest,
505 ) -> Result<Page<DependencyEdge>, SourceError>;
506
507 /// One page of the project dependency edges at `id`, in `direction`.
508 ///
509 /// # Errors
510 ///
511 /// Returns a [`SourceError`] when the source could not answer.
512 async fn project_dependencies(
513 &self,
514 id: &NativeId,
515 direction: Direction,
516 page: &PageRequest,
517 ) -> Result<Page<DependencyEdge>, SourceError>;
518
519 /// Whether this source can be written through at all.
520 ///
521 /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
522 /// interface for every source that has nothing to write into: one that cannot be
523 /// written needs no edit and keeps working. Read before a write is attempted, so a
524 /// copy naming such a source as its destination is refused before anything is read.
525 fn writes(&self) -> WriteSupport {
526 WriteSupport::Unsupported
527 }
528
529 /// The status this source's backend holds once an item of `kind` is written at `status`:
530 /// the name it records for the category, where it names a category itself rather than
531 /// keeping the name it was given.
532 ///
533 /// What a copy compares a destination item's status with, so an item whose category it
534 /// already holds reads as unchanged rather than as differing by a name no write could
535 /// change. Defaulted to `status` as given: a backend that keeps the name it is written
536 /// declares nothing.
537 ///
538 /// Asynchronous and fallible because a source hosted over the stdio plugin protocol asks
539 /// the plugin that declares it; an in-process source answers at once and never fails.
540 ///
541 /// # Errors
542 ///
543 /// A [`SourceError`] when the source could not say what its backend holds — never the
544 /// status as given in its place.
545 async fn stored_status(&self, kind: ItemKind, status: &Status) -> Result<Status, SourceError> {
546 let _ = kind;
547 Ok(status.clone())
548 }
549
550 /// The content the backend answered it now holds for the `record` `id`, as the response
551 /// to this instance's latest write of that item's content reported it — taken, so a second
552 /// call answers `None` until the next such write.
553 ///
554 /// The content is as a read reports content — the metadata slot, and whatever separates
555 /// it from the content, removed — and it is read off the write's own response, never by a
556 /// request of its own. It is what the engine takes as the record of what the item holds: a
557 /// backend may rewrite the Markdown it is written, keeping its rendered meaning, and where
558 /// this differs from what was sent the engine records each fingerprint it keeps over this
559 /// content instead — a rendering's `body_digest`, a copy's
560 /// [`MetadataKey::COPIED_DESTINATION_VERSION_KEY`] — and writes it back once, beside them,
561 /// as its own request. That follow-up write's own answer is then compared with this
562 /// content byte for byte, and a backend that does not hold its own stored content stable
563 /// is refused as `stored-content-diverged`. Defaulted to `None`: a backend that stores what
564 /// it is given says nothing, and nothing is compared or written again.
565 fn stored_content(&self, record: MetadataRecord, id: &NativeId) -> Option<String> {
566 let _ = (record, id);
567 None
568 }
569
570 /// Create or update one task, answering with the native id the destination holds it
571 /// under.
572 ///
573 /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
574 /// naming the field, anything it cannot represent rather than dropping it — including
575 /// a metadata key it cannot carry, which it names. It writes every other field it was
576 /// given. And it never creates when [`ItemWrite::target`] names an item it does not
577 /// hold.
578 ///
579 /// # Errors
580 ///
581 /// Returns [`SourceError::Refused`] when this source has no write side, when a field
582 /// or a metadata key cannot be represented, or when `target` names nothing here; and
583 /// whatever else the source could not do the write for.
584 async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
585 let _ = write;
586 Err(unwritable(self.kind()))
587 }
588
589 /// Create or update one project, on exactly the terms of
590 /// [`write_task`](Self::write_task).
591 ///
592 /// # Errors
593 ///
594 /// As [`write_task`](Self::write_task).
595 async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
596 let _ = write;
597 Err(unwritable(self.kind()))
598 }
599
600 /// Whether this source can represent every field of `write` — its status, its content, the
601 /// tasks it delivers and every other field a [`write_task`](Self::write_task) of it would
602 /// refuse as "cannot represent the field …" — asked before anything is written and changing
603 /// nothing.
604 ///
605 /// A task copy asks it of every task it plans before its first write, and leaves out each
606 /// task this refuses — answered `failed`, with this refusal as its reason — writing the rest
607 /// as one copy. It answers what the write itself would refuse in the same words; and it is a
608 /// promise only about representability, so a write may still fail for any other reason.
609 ///
610 /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses such a
611 /// write in its write, which a copy then takes back whole, exactly as before.
612 ///
613 /// # Errors
614 ///
615 /// Returns [`SourceError::Refused`] naming the field this source cannot represent; and
616 /// whatever else kept it from finding out.
617 async fn check_task_write(&self, write: &ItemWrite<Task>) -> Result<(), SourceError> {
618 let _ = write;
619 Ok(())
620 }
621
622 /// Whether a write of an item of `kind` at `category` — over the item `target` names, or
623 /// creating one when it is `None` — would have a status to write, asked before the write
624 /// and changing nothing.
625 ///
626 /// A caller that has to put an item back when a later write of it fails — a copy, whose
627 /// journal records what an item held before overwriting it — asks this first, so a status
628 /// this source has no name for is refused while nothing has been recorded or written, and
629 /// nothing has to be put back. It answers what the write itself would refuse a status
630 /// with, in the same words, and sends no request a write of that status would not have
631 /// sent anyway: what it reads to answer, it holds for the write that follows.
632 ///
633 /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses the
634 /// status in its write, exactly as before.
635 ///
636 /// # Errors
637 ///
638 /// Returns [`SourceError::Refused`] naming the kind, the category and what is missing
639 /// when this source has no name for that status; and whatever else kept it from finding
640 /// out.
641 async fn check_status_write(
642 &self,
643 kind: ItemKind,
644 category: StatusCategory,
645 target: Option<&NativeId>,
646 ) -> Result<(), SourceError> {
647 let _ = (kind, category, target);
648 Ok(())
649 }
650
651 /// The status an item of `kind` reads back as once this source has written `status` for
652 /// it, asked without writing or reading anything.
653 ///
654 /// A source that keeps a status's name as it was given answers `status` itself. One that
655 /// writes a category to a name of its own — a board's `Status` option the category maps
656 /// to — answers that name, so a caller comparing what it would write with what the source
657 /// holds does not read a difference of spelling alone as a change: a copy then leaves an
658 /// item that already reads as the source does unwritten.
659 ///
660 /// Defaulted to `status` itself, which is what every source keeping names verbatim reads
661 /// back, and what a caller compared against before this was asked.
662 fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
663 let _ = kind;
664 status.clone()
665 }
666
667 /// Set the status of one task this source holds, and change nothing else about it,
668 /// answering with the status as this source now reads it — or `None` when this source
669 /// holds no such task.
670 ///
671 /// The category lands where this source's own mapping sends it, exactly as a
672 /// [`write_task`](Self::write_task) of a task in that category would: a category this
673 /// source has disabled is refused in the words a write of it is refused with. Title,
674 /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
675 /// project and comments are left exactly as they are.
676 ///
677 /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
678 /// break: a source that cannot write a status on its own needs no edit and refuses by
679 /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
680 ///
681 /// [`Task::delivers`]: crate::Task::delivers
682 /// [`Task::delivered_by`]: crate::Task::delivered_by
683 ///
684 /// # Errors
685 ///
686 /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
687 /// write this one; and whatever else the source could not do the write for.
688 async fn set_task_status(
689 &self,
690 id: &NativeId,
691 category: StatusCategory,
692 ) -> Result<Option<Status>, SourceError> {
693 let _ = (id, category);
694 Err(unwritable_field(self.kind(), "status"))
695 }
696
697 /// Set the status of one project this source holds, and change nothing else about it,
698 /// answering with the status as this source now reads it — or `None` when this source
699 /// holds no such project.
700 ///
701 /// The category lands where this source's own mapping sends it for a project, exactly as a
702 /// [`write_project`](Self::write_project) of a project in that category would: a category
703 /// this source has disabled is refused in the words a write of it is refused with. Title,
704 /// content, labels, metadata, repositories, dependencies and the project's tasks are left
705 /// exactly as they are. A project delivers no task, so nothing is kept in step after it.
706 ///
707 /// Defaulted to the refusal [`set_task_status`](Self::set_task_status) defaults to,
708 /// [`unwritable_field`] naming `status`, which is what keeps this an addition rather than a
709 /// break: a source that does not implement it needs no edit. A source declaring
710 /// [`WriteSupport::Unsupported`] is never asked.
711 ///
712 /// # Errors
713 ///
714 /// Returns [`SourceError::Refused`] when this source cannot write a project's status, or
715 /// cannot write this one; and whatever else the source could not do the write for.
716 async fn set_project_status(
717 &self,
718 id: &NativeId,
719 category: StatusCategory,
720 ) -> Result<Option<Status>, SourceError> {
721 let _ = (id, category);
722 Err(unwritable_field(self.kind(), "status"))
723 }
724
725 /// Set the status of one task this source holds, as [`set_task_status`](Self::set_task_status)
726 /// does, and answer with the whole task as this source now reads it — its
727 /// [`Task::delivers`] among what a caller keeping delivered tasks in step needs — or `None`
728 /// when this source holds no such task.
729 ///
730 /// Defaulted to exactly the two calls a caller would otherwise make: [`get_task`] first,
731 /// answering `None` with nothing written when it does, then `set_task_status`, the status
732 /// it answers put on the task read. A source whose status write answers the whole task in
733 /// the same round trip overrides it to save the read.
734 ///
735 /// [`Task::delivers`]: crate::Task::delivers
736 /// [`get_task`]: Self::get_task
737 ///
738 /// # Errors
739 ///
740 /// As [`get_task`](Self::get_task) and [`set_task_status`](Self::set_task_status).
741 async fn set_task_status_reading(
742 &self,
743 id: &NativeId,
744 category: StatusCategory,
745 ) -> Result<Option<Task>, SourceError> {
746 let Some(mut task) = self.get_task(id).await? else {
747 return Ok(None);
748 };
749 let Some(status) = self.set_task_status(id, category).await? else {
750 return Ok(None);
751 };
752 task.status = status;
753 Ok(Some(task))
754 }
755
756 /// Every task this source holds whose card contradicts its issue's closure, each with the
757 /// status that brings it in line — what `task status reconcile` writes, through
758 /// [`set_task_status`](Self::set_task_status), one task at a time.
759 ///
760 /// A task needs it when its issue is closed with a reason that reads `done` or
761 /// `cancelled` and its card does not sit at the option this source's mapping gives that
762 /// category. An open task, a closure that reads `unknown` and a card already in line are
763 /// never answered. Changes nothing.
764 ///
765 /// Asked only of a source declaring
766 /// [`Capabilities::reconcile_status`](crate::Capabilities::reconcile_status); defaulted to a
767 /// refusal saying so, which no caller holding to that declaration ever receives.
768 ///
769 /// # Errors
770 ///
771 /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
772 /// kept it from reading its items.
773 async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
774 Err(SourceError::Refused {
775 message: format!(
776 "a {} source's status is its closure, so nothing needs reconciling",
777 self.kind()
778 ),
779 })
780 }
781
782 /// For each issue in `issues`, in order and once each, the task this source holds for it
783 /// and what moving it to `done` comes to — what `task status complete` writes, through
784 /// [`set_task_status`](Self::set_task_status), for each one answered
785 /// [`Completion::Due`](crate::Completion::Due).
786 ///
787 /// The read is proportional to `issues` and never to the size of what this source holds,
788 /// and an empty `issues` reads nothing. Changes nothing.
789 ///
790 /// Asked only of a source declaring
791 /// [`Capabilities::complete_by_issue`](crate::Capabilities::complete_by_issue); defaulted
792 /// to a refusal saying so, which no caller holding to that declaration ever receives.
793 ///
794 /// # Errors
795 ///
796 /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
797 /// kept it from reading the issues.
798 async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
799 let _ = issues;
800 Err(SourceError::Refused {
801 message: format!("a {} source holds no items by issue reference", self.kind()),
802 })
803 }
804
805 /// Set the priority of one task this source holds, and change nothing else about it,
806 /// answering with the priority as this source now reads it — or `None` when this source
807 /// holds no such task.
808 ///
809 /// [`Priority::None`] clears the priority. Title, content, status, labels, metadata,
810 /// repositories, dependencies and comments are left exactly as they are. Nothing about
811 /// the task's status moves, so the engine re-evaluates no delivered task after it.
812 ///
813 /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
814 /// break. A source declaring [`WriteSupport::Unsupported`], or declaring
815 /// [`Capabilities::priority`] unsupported, is never asked.
816 ///
817 /// # Errors
818 ///
819 /// Returns [`SourceError::Refused`] when this source cannot write a priority, or cannot
820 /// write this one — a board with no option for it, naming the option; and whatever else
821 /// the source could not do the write for.
822 async fn set_task_priority(
823 &self,
824 id: &NativeId,
825 priority: Priority,
826 ) -> Result<Option<Priority>, SourceError> {
827 let _ = (id, priority);
828 Err(unwritable_field(self.kind(), "priority"))
829 }
830
831 /// Replace the content of one task this source holds with `content`, byte for byte, and
832 /// change nothing else about it — or answer `None` when this source holds no such task.
833 ///
834 /// The content is [`Task::content`] exactly as this source reports it: what a later read
835 /// answers there is `content`. Where the source keeps something else inside the same
836 /// backend field — a metadata block in an issue body — that is kept as it was, and so is
837 /// every other member: title, status, priority, labels, metadata, repositories,
838 /// dependencies, project and comments. Nothing about the task's status moves, so the
839 /// engine re-evaluates no delivered task after it.
840 ///
841 /// Defaulted to [`unwritable_field`] on exactly the terms of
842 /// [`set_task_status`](Self::set_task_status). A source declaring
843 /// [`WriteSupport::Unsupported`] is never asked.
844 ///
845 /// # Errors
846 ///
847 /// Returns [`SourceError::Refused`] when this source cannot write a task's content on its
848 /// own, or cannot represent this one; and whatever else the source could not do the write
849 /// for.
850 async fn set_task_content(
851 &self,
852 id: &NativeId,
853 content: &str,
854 ) -> Result<Option<()>, SourceError> {
855 let _ = (id, content);
856 Err(unwritable_field(self.kind(), "content"))
857 }
858
859 /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
860 /// else about it — or answer `None` when this source holds no such task.
861 ///
862 /// Every entry is a qualified id, and the list is the whole of it: what the task held
863 /// there before is replaced, not merged. It is the store's to keep in step — the engine
864 /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
865 /// reaches it directly.
866 ///
867 /// Defaulted to [`unwritable_field`] on exactly the terms of
868 /// [`set_task_status`](Self::set_task_status).
869 ///
870 /// [`Task::delivers`]: crate::Task::delivers
871 /// [`Task::delivered_by`]: crate::Task::delivered_by
872 ///
873 /// # Errors
874 ///
875 /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
876 /// else it could not do the write for.
877 async fn set_delivered_by(
878 &self,
879 id: &NativeId,
880 delivered_by: &[TaskRef],
881 ) -> Result<Option<()>, SourceError> {
882 let _ = (id, delivered_by);
883 Err(unwritable_field(self.kind(), "delivered_by"))
884 }
885
886 /// Set one key of the metadata of one task this source holds, and change nothing else
887 /// about it, answering with the task as this source reads it back after the write — or
888 /// `None` when this source holds no such task.
889 ///
890 /// The key is added when the task does not hold it and replaced when it does; every other
891 /// metadata key, and every other field of the task, is left exactly as it was. A `value`
892 /// the task already holds under `key` is a write that changes nothing, and a source owes
893 /// it no write at all. The answer is a read, not an echo: what the engine reports as the
894 /// value is what the returned task holds under `key`.
895 ///
896 /// Nothing about the task's status or its [`Task::delivers`] moves, so the engine
897 /// re-evaluates no delivered task after this write.
898 ///
899 /// Defaulted to [`unwritable_metadata`] on exactly the terms of
900 /// [`set_task_status`](Self::set_task_status): a source that cannot write one key on its
901 /// own needs no edit and refuses by saying so. A source declaring
902 /// [`WriteSupport::Unsupported`] is never asked.
903 ///
904 /// [`Task::delivers`]: crate::Task::delivers
905 ///
906 /// # Errors
907 ///
908 /// Returns [`SourceError::Refused`] when this source cannot write one key of a task's
909 /// metadata on its own, or cannot write this one without changing something else; and
910 /// whatever else the source could not do the write for.
911 async fn set_task_metadata(
912 &self,
913 id: &NativeId,
914 key: &MetadataKey,
915 value: &Value,
916 ) -> Result<Option<Task>, SourceError> {
917 let _ = (id, key, value);
918 Err(unwritable_metadata(self.kind(), MetadataRecord::Task))
919 }
920
921 /// Apply a targeted update to one task this source holds — every field `update` names, and
922 /// nothing else — answering with a [`TaskUpdateOutcome`], or `None` when this source holds
923 /// no such task.
924 ///
925 /// The outcome is everything the engine reports about the call, so it reads nothing of its
926 /// own: the task as this source reads it once the update landed — from the one read it made
927 /// and what it then wrote, where its backend answers a write with what it holds — the
928 /// fields it actually wrote, and the `delivers` the task held before.
929 ///
930 /// A field already holding the requested value is sent no write, and an update in which
931 /// nothing differs sends no write at all. Every field `update` leaves unnamed — labels,
932 /// repositories, project, [`Task::delivered_by`] and comments always among them — is left
933 /// exactly as it is. An update naming one metadata key both to set and to remove is refused
934 /// before anything is written, in the words of [`TaskUpdate::consistent`].
935 ///
936 /// Defaulted to [`TaskUpdate::rewrite`]: read the task, apply the update, and — only when
937 /// anything differs — [`write_task`](Self::write_task) it with its `target` set. That keeps
938 /// this an addition rather than a break, and a source that predates it behaves correctly and
939 /// is merely not minimal; one whose backend can take a field on its own owes an override
940 /// that sends only what differs. A source declaring [`WriteSupport::Unsupported`] is never
941 /// asked.
942 ///
943 /// [`Task::delivered_by`]: crate::Task::delivered_by
944 ///
945 /// # Errors
946 ///
947 /// Returns [`SourceError::Refused`] when the update contradicts itself, when a field it
948 /// names cannot be represented here — a category this source has disabled included — and
949 /// whatever else the source could not do the write for.
950 async fn update_task(
951 &self,
952 id: &NativeId,
953 update: &TaskUpdate,
954 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
955 update.rewrite(self, id).await
956 }
957
958 /// Set one key of the metadata of one project this source holds, on exactly the terms of
959 /// [`set_task_metadata`](Self::set_task_metadata).
960 ///
961 /// # Errors
962 ///
963 /// As [`set_task_metadata`](Self::set_task_metadata).
964 async fn set_project_metadata(
965 &self,
966 id: &NativeId,
967 key: &MetadataKey,
968 value: &Value,
969 ) -> Result<Option<Project>, SourceError> {
970 let _ = (id, key, value);
971 Err(unwritable_metadata(self.kind(), MetadataRecord::Project))
972 }
973
974 /// Set one key of the metadata of one document this source holds, on exactly the terms of
975 /// [`set_task_metadata`](Self::set_task_metadata).
976 ///
977 /// A source declaring [`Capabilities::documents`] unsupported is never asked, exactly as
978 /// it is never asked for a document read.
979 ///
980 /// # Errors
981 ///
982 /// As [`set_task_metadata`](Self::set_task_metadata).
983 async fn set_document_metadata(
984 &self,
985 id: &NativeId,
986 key: &MetadataKey,
987 value: &Value,
988 ) -> Result<Option<Document>, SourceError> {
989 let _ = (id, key, value);
990 Err(unwritable_metadata(self.kind(), MetadataRecord::Document))
991 }
992
993 /// Remove one task this destination holds, so a copy that could not finish can put
994 /// the destination back the way it found it.
995 ///
996 /// This is not a verb of the product: nothing a user types deletes anything, and a
997 /// copy never deletes an item it did not itself create in the run that is failing.
998 /// It exists because a copy is either complete or it never happened — a half-written
999 /// project has to be run again, and the re-run is the mutation burst that trips a
1000 /// hosted destination's rate limiter. Undoing this run's own creates is what removes
1001 /// that retry at source.
1002 ///
1003 /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
1004 /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
1005 /// there, so it has to be able to remove the ones it created. An `id` naming nothing
1006 /// is **not** an error — the item is already gone, which is the state this asks for.
1007 ///
1008 /// # Errors
1009 ///
1010 /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
1011 /// else the source could not remove the item for.
1012 async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
1013 let _ = id;
1014 Err(unwritable(self.kind()))
1015 }
1016
1017 /// Remove one project this destination holds, on exactly the terms of
1018 /// [`delete_task`](Self::delete_task).
1019 ///
1020 /// # Errors
1021 ///
1022 /// As [`delete_task`](Self::delete_task).
1023 async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
1024 let _ = id;
1025 Err(unwritable(self.kind()))
1026 }
1027
1028 /// Fetch one document by its native id, or `None` when there is no such document.
1029 ///
1030 /// Defaulted to [`documentless`], which is what keeps documents an addition rather
1031 /// than a break: a source with none needs no edit, keeps working, and says so in the
1032 /// same words every other document-free source does. A source that has documents
1033 /// declares [`Support::Native`](crate::Support::Native) for
1034 /// [`Capabilities::documents`] and owes a real implementation here, because that
1035 /// declaration is what makes the engine ask.
1036 ///
1037 /// # Errors
1038 ///
1039 /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
1040 /// else the source could not answer for.
1041 async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
1042 let _ = id;
1043 Err(documentless(self.kind()))
1044 }
1045
1046 /// One page of the documents matching `query`.
1047 ///
1048 /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
1049 /// with no documents refuses rather than answering an empty page: an empty page reads
1050 /// as a source that has documents and holds none matching, which is the one wrong
1051 /// answer this method can give.
1052 ///
1053 /// # Errors
1054 ///
1055 /// As [`get_document`](Self::get_document).
1056 async fn query_documents(
1057 &self,
1058 query: &DocumentQuery,
1059 page: &PageRequest,
1060 ) -> Result<Page<Document>, SourceError> {
1061 let _ = (query, page);
1062 Err(documentless(self.kind()))
1063 }
1064
1065 /// One page of the documents whose [`TaskQuery::ORIGIN_KEY`] entry is a string equal to
1066 /// `origin`, exactly, on the terms of
1067 /// [`query_projects_by_origin`](Self::query_projects_by_origin).
1068 ///
1069 /// Defaulted to [`query_documents`](Self::query_documents) unfiltered, walked and narrowed
1070 /// as that default is — so a source with no documents refuses exactly as its
1071 /// `query_documents` does.
1072 ///
1073 /// # Errors
1074 ///
1075 /// As [`query_documents`](Self::query_documents), and [`SourceError::Refused`] for a
1076 /// cursor the default did not hand out.
1077 async fn query_documents_by_origin(
1078 &self,
1079 origin: &str,
1080 page: &PageRequest,
1081 ) -> Result<Page<Document>, SourceError> {
1082 let wanted = origin_query(origin);
1083 let mut matched = Vec::new();
1084 let mut cursor: Option<crate::Cursor> = None;
1085 // Every cursor the listing handed out, so one cycling through several is caught as
1086 // one repeating the last is.
1087 let mut visited: Vec<String> = Vec::new();
1088 loop {
1089 let listed = self
1090 .query_documents(
1091 &DocumentQuery::default(),
1092 &PageRequest {
1093 cursor: cursor.clone(),
1094 limit: page.limit,
1095 },
1096 )
1097 .await?;
1098 overran(listed.items.len(), page.limit)?;
1099 matched.extend(
1100 listed
1101 .items
1102 .into_iter()
1103 .filter(|document| wanted.origin_matches(&document.metadata)),
1104 );
1105 cursor = match listed.next {
1106 None => break,
1107 Some(next) if visited.contains(&next.0) => return Err(repeated_cursor()),
1108 Some(next) => {
1109 visited.push(next.0.clone());
1110 Some(next)
1111 }
1112 };
1113 }
1114 page_of_matches(matched, page)
1115 }
1116
1117 /// Create or update one document, on exactly the terms of
1118 /// [`write_task`](Self::write_task).
1119 ///
1120 /// # Errors
1121 ///
1122 /// As [`write_task`](Self::write_task).
1123 async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
1124 let _ = write;
1125 Err(unwritable(self.kind()))
1126 }
1127
1128 /// Remove one document this destination holds, on exactly the terms of
1129 /// [`delete_task`](Self::delete_task).
1130 ///
1131 /// # Errors
1132 ///
1133 /// As [`delete_task`](Self::delete_task).
1134 async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
1135 let _ = id;
1136 Err(unwritable(self.kind()))
1137 }
1138
1139 /// One page of the comments on `task`, oldest first, or `None` when this source holds
1140 /// no such task.
1141 ///
1142 /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
1143 /// break: a source with none needs no edit and keeps working. A source whose tasks have
1144 /// comments declares [`Support::Native`](crate::Support::Native) for
1145 /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
1146 /// because that declaration is what makes the engine ask.
1147 ///
1148 /// "No such task" is `None` rather than an error, exactly as it is for
1149 /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
1150 ///
1151 /// # Errors
1152 ///
1153 /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
1154 /// the source could not answer for.
1155 async fn task_comments(
1156 &self,
1157 task: &NativeId,
1158 page: &PageRequest,
1159 ) -> Result<Option<Page<Comment>>, SourceError> {
1160 let _ = (task, page);
1161 Err(commentless(self.kind()))
1162 }
1163
1164 /// [`get_task_details`](Self::get_task_details) as a copy reads the tasks it carries: each
1165 /// with the first page of its comments `comments` names — and, where the same request can
1166 /// carry them, what this source needs to answer [`task_dependencies`](Self::task_dependencies)
1167 /// for it without another, since a copy reads every task's edges next.
1168 ///
1169 /// Defaulted to `get_task_details(ids, Some(comments))`, which is exactly what it answers.
1170 /// A source whose detail read is priced by what it selects overrides it with a read that
1171 /// also carries the edges, so a copy of a changed task costs its detail read and nothing
1172 /// more; one whose reads are free has no reason to.
1173 async fn get_task_details_for_copy(
1174 &self,
1175 ids: &[NativeId],
1176 comments: &PageRequest,
1177 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
1178 self.get_task_details(ids, Some(comments)).await
1179 }
1180
1181 /// Read the items `ids` names — tasks, projects and documents alike, whatever kind each
1182 /// is — together, as a copy reads the counterparts it is about to write, and hold each for
1183 /// this command so that the next [`get_task`](Self::get_task),
1184 /// [`get_project`](Self::get_project) or [`get_document`](Self::get_document) of it is
1185 /// answered from that read, once, instead of being sent on its own.
1186 ///
1187 /// What is held is exactly what that read by id would have answered — the item's fields,
1188 /// its edges, its asset manifest and its change token — and only until the next read of
1189 /// it, a write naming it, or [`end_command`](Self::end_command), whichever comes first, so
1190 /// a read answered from it is never staler than the read-before-write it stands in for.
1191 ///
1192 /// Defaulted to doing nothing, so every read is sent as it always was: a source whose
1193 /// reads are free has no reason to override it, and one priced per request overrides it
1194 /// with a batched read. An id the batched read finds nothing at is either held as absent —
1195 /// its next read answers `None`, exactly as that read would have — or not held, and its own
1196 /// read answers as it always does.
1197 ///
1198 /// # Errors
1199 ///
1200 /// Returns a [`SourceError`] when the batched read could not be made. Nothing is then
1201 /// held, and each item's own read answers as it would have.
1202 async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
1203 let _ = ids;
1204 Ok(())
1205 }
1206
1207 /// Ask, together, which items were copied from each of `origins` — the qualified ids a copy
1208 /// is about to look for at this destination by the `onetaskgraph.origin` each item records
1209 /// — and hold each answer
1210 /// for this command, so that the next query for the items copied from one of them (a
1211 /// [`TaskQuery::origin`] task query, [`query_projects_by_origin`](Self::query_projects_by_origin)
1212 /// or [`query_documents_by_origin`](Self::query_documents_by_origin)) is answered from it,
1213 /// once, instead of being sent on its own. A source may carry in the same read whatever its
1214 /// creating an item would read first, since a copy finding nothing creates — and its
1215 /// [`designator`](Self::designator), which a copy writing edges asks next: a designator
1216 /// carried in that read answers the next [`designator`](Self::designator) of the command
1217 /// without a request of its own.
1218 ///
1219 /// What is held is exactly what those queries would have answered, and only until the next
1220 /// write or [`end_command`](Self::end_command); a designator, which no write moves, until
1221 /// [`end_command`](Self::end_command). An origin is held as having no counterpart only when
1222 /// the read answered it whole: one whose answer the read could not see the end of is left
1223 /// to its own query. Defaulted to doing nothing, so each query is sent as it always was.
1224 ///
1225 /// # Errors
1226 ///
1227 /// Returns a [`SourceError`] when the read could not be made. Nothing is then held, and each
1228 /// query answers as it would have.
1229 async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
1230 let _ = origins;
1231 Ok(())
1232 }
1233
1234 /// Who may read each member of the project `project` — every task and document filed under
1235 /// it — as the classification and repositories each one's record holds, read by whatever
1236 /// this source holds for this command rather than by its whole records: what a write the
1237 /// public boundary screens reads of a project before it is held to it.
1238 ///
1239 /// `None` is no such read, and is the default: the engine then reads the members as it
1240 /// always has, through [`query_tasks`](Self::query_tasks) narrowed to the project and
1241 /// [`query_documents`](Self::query_documents), so every source answers exactly as before. A
1242 /// source answers `Some` only with every member — a page that says there is more is no
1243 /// answer, and is left to that path — and never with fewer members than those queries
1244 /// would have listed. A source may hold such a page from a read it made beside another,
1245 /// such as the one [`read_ahead_for_copy`](Self::read_ahead_for_copy) names the project to.
1246 ///
1247 /// # Errors
1248 ///
1249 /// Returns a [`SourceError`] when the read could not be made.
1250 async fn member_classifications(
1251 &self,
1252 project: &NativeId,
1253 ) -> Result<Option<Vec<(Classification, Vec<Repository>)>>, SourceError> {
1254 let _ = project;
1255 Ok(None)
1256 }
1257
1258 /// How many tasks this source creates in one [`write_tasks`](Self::write_tasks): more than
1259 /// one only for a source that creates several in one request.
1260 ///
1261 /// A copy hands such a source the tasks it creates together, and names each one's edges to
1262 /// the others in a write after they all exist. Defaulted to one, which has a copy write every
1263 /// task on its own, exactly as before.
1264 fn create_batch_limit(&self) -> usize {
1265 1
1266 }
1267
1268 /// Create every task of `writes` — each [`ItemWrite::target`] `None` — answering with the
1269 /// native ids they were created under, in order.
1270 ///
1271 /// All of them or none: a source that cannot create every one takes back each it did create
1272 /// before refusing, on the terms §4.9 of the protocol puts on [`write_task`](Self::write_task).
1273 /// Defaulted to creating them one at a time through [`write_task`](Self::write_task), taking
1274 /// back those created when a later one is refused.
1275 ///
1276 /// # Errors
1277 ///
1278 /// Refused, before anything is written, when a write names an existing target; otherwise
1279 /// whatever [`write_task`](Self::write_task) of one of them refuses with.
1280 // llmlint: ignore[invalid_states_unrepresentable] Approved by the contract's owner as an additive method taking `ItemWrite<Task>` exactly as `write_task` does; a create-only input type would be a new contract type. A write naming an existing target is refused below before anything is written, so rollback only ever takes back what this call created.
1281 async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
1282 if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
1283 return Err(SourceError::Refused {
1284 message: format!(
1285 "write_tasks creates tasks, and the write of {} names an existing target; \
1286 next: update it with write_task",
1287 write.item.id
1288 ),
1289 });
1290 }
1291 let mut created = Vec::with_capacity(writes.len());
1292 for write in writes {
1293 match self.write_task(write).await {
1294 Ok(id) => created.push(id),
1295 Err(error) => {
1296 // The caller is never handed these ids, so one this source will not take
1297 // back is named here or by nobody.
1298 let mut left: Vec<&str> = Vec::new();
1299 for id in &created {
1300 if self.delete_task(id).await.is_err() {
1301 left.push(id.0.as_str());
1302 }
1303 }
1304 if left.is_empty() {
1305 return Err(error);
1306 }
1307 return Err(SourceError::Refused {
1308 message: format!(
1309 "{error}; this source then refused to take back {}, which this \
1310 write created and which it still holds; next: delete {} before \
1311 writing again",
1312 left.join(", "),
1313 if left.len() == 1 { "it" } else { "them" }
1314 ),
1315 });
1316 }
1317 }
1318 }
1319 Ok(created)
1320 }
1321
1322 /// From here until [`finish_writes`](Self::finish_writes), a source may hold back the part of
1323 /// each write that can land later — a created item's fields and edges — and send it together
1324 /// with the others' when that is called.
1325 ///
1326 /// A caller asks for this only when it will call `finish_writes` before it reads what it
1327 /// wrote from anywhere but this source, or reports it written. Defaulted to holding nothing
1328 /// back, so every write lands whole as it is made.
1329 fn begin_deferred_writes(&self) {}
1330
1331 /// Send whatever this source has held back since [`begin_deferred_writes`](Self::begin_deferred_writes),
1332 /// and hold nothing back after it.
1333 ///
1334 /// All or nothing for the items it created: a source that cannot finish them takes them back
1335 /// before refusing, so a caller undoing its writes finds them gone. Defaulted to doing
1336 /// nothing, since nothing was held.
1337 ///
1338 /// # Errors
1339 ///
1340 /// Whatever sending what was held back was refused with.
1341 async fn finish_writes(&self) -> Result<(), SourceError> {
1342 Ok(())
1343 }
1344
1345 /// Where an item this source wrote in the current command is, when the write's own answer
1346 /// said so: `record` names which kind of item `id` is.
1347 ///
1348 /// Answered only from what a write already returned — never by a request — so a caller may
1349 /// ask it after every write for free. A caller treats `None` as not knowing, and reads the
1350 /// item when it needs its location. Defaulted to `None`.
1351 fn written_location(&self, record: MetadataRecord, id: &NativeId) -> Option<Location> {
1352 let _ = (record, id);
1353 None
1354 }
1355
1356 /// Add one comment to `task`, answering with the comment as the source now holds it, or
1357 /// `None` when this source holds no such task.
1358 ///
1359 /// The body is stored byte for byte. A source that records the author itself refuses a
1360 /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
1361 /// represent the body refuses it, naming why, rather than escaping it into something
1362 /// else.
1363 ///
1364 /// # Errors
1365 ///
1366 /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
1367 /// written, when it cannot record what it was given, and whatever else it could not do
1368 /// the write for.
1369 async fn add_comment(
1370 &self,
1371 task: &NativeId,
1372 comment: &NewComment,
1373 ) -> Result<Option<Comment>, SourceError> {
1374 let _ = (task, comment);
1375 Err(commentless(self.kind()))
1376 }
1377
1378 /// Replace the body of the comment `comment` on `task`, answering with the comment as the
1379 /// source now holds it, or `None` when this source holds no such task or that task has no
1380 /// such comment.
1381 ///
1382 /// Only the body and the time it last changed move: the id, the author and the time it
1383 /// was written are the comment's own.
1384 ///
1385 /// # Errors
1386 ///
1387 /// As [`add_comment`](Self::add_comment).
1388 async fn edit_comment(
1389 &self,
1390 task: &NativeId,
1391 comment: &NativeId,
1392 body: &CommentBody,
1393 ) -> Result<Option<Comment>, SourceError> {
1394 let _ = (task, comment, body);
1395 Err(commentless(self.kind()))
1396 }
1397
1398 /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
1399 /// when this source holds no such task or that task has no such comment.
1400 ///
1401 /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
1402 /// removes a comment they posted — so a comment that is not there is reported as `None`
1403 /// for the engine to refuse by name, rather than treated as already gone.
1404 ///
1405 /// # Errors
1406 ///
1407 /// As [`add_comment`](Self::add_comment).
1408 async fn delete_comment(
1409 &self,
1410 task: &NativeId,
1411 comment: &NativeId,
1412 ) -> Result<Option<NativeId>, SourceError> {
1413 let _ = (task, comment);
1414 Err(commentless(self.kind()))
1415 }
1416
1417 /// Write one comment a copy carries onto `task`: a new one when `existing` is `None`, and
1418 /// otherwise the comment `existing`, which a copy wrote before, made to say `copy` — or
1419 /// `None` when this source holds no such task or no such comment.
1420 ///
1421 /// The answer reports [`Comment::origin`] as `copy.origin`, however the source keeps it.
1422 ///
1423 /// **Defaulted to the hidden marker**, which is right for every source that records a
1424 /// comment's author and times itself: the body is written through
1425 /// [`add_comment`](Self::add_comment) or [`edit_comment`](Self::edit_comment) with
1426 /// [`CommentOrigin::mark`](crate::CommentOrigin::mark) appended, and read back
1427 /// [`unmarked`](Comment::unmarked). A source that can store the origin natively — and so
1428 /// takes the origin's own id, author and times for the copy — overrides this.
1429 ///
1430 /// # Errors
1431 ///
1432 /// As [`add_comment`](Self::add_comment).
1433 async fn write_comment_copy(
1434 &self,
1435 task: &NativeId,
1436 existing: Option<&NativeId>,
1437 copy: &CommentCopy,
1438 ) -> Result<Option<Comment>, SourceError> {
1439 let body = CommentBody::new(copy.origin.qualified()?.mark(copy.body.as_str()))?;
1440 let written = match existing {
1441 Some(comment) => self.edit_comment(task, comment, &body).await?,
1442 None => {
1443 self.add_comment(task, &NewComment { body, author: None })
1444 .await?
1445 }
1446 };
1447 Ok(written.map(Comment::unmarked))
1448 }
1449
1450 /// Whether this source keeps template answers beside its items at all.
1451 ///
1452 /// What lets a regenerate tell an item whose answers went missing — a block deleted by
1453 /// hand, which the regenerate writes back — from an item of a source that never keeps any,
1454 /// where a missing answer is no difference. Defaulted to `false`, as
1455 /// [`task_template_answers`](Self::task_template_answers) is defaulted to `None`; a source
1456 /// that keeps answers answers `true` here.
1457 fn keeps_template_answers(&self) -> bool {
1458 false
1459 }
1460
1461 /// The template answers the task `id` was last rendered from, as this source keeps them
1462 /// beside the task — or `None` when it keeps none for it, or holds no such task.
1463 ///
1464 /// Keeping answers is a source's own choice, never an obligation: a source whose items
1465 /// are one record in a hosted system has no room beside the item that is not the item, and
1466 /// answers written into its content or its metadata would duplicate what the content
1467 /// already says. Defaulted to `None`, which is what keeps this an addition rather than a
1468 /// break. A source that keeps them owes three things: they are in neither
1469 /// [`Task::content`] nor [`Task::metadata`], they are written only by
1470 /// [`write_task_rendered`](Self::write_task_rendered) and
1471 /// [`set_task_rendering`](Self::set_task_rendering), and they come back here exactly as
1472 /// they were written, JSON types intact.
1473 ///
1474 /// # Errors
1475 ///
1476 /// Returns a [`SourceError`] when the source could not answer, a record whose answers it
1477 /// cannot read included.
1478 async fn task_template_answers(
1479 &self,
1480 id: &NativeId,
1481 ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1482 let _ = id;
1483 Ok(None)
1484 }
1485
1486 /// The template answers the document `id` was last rendered from, on exactly the terms of
1487 /// [`task_template_answers`](Self::task_template_answers).
1488 ///
1489 /// # Errors
1490 ///
1491 /// As [`task_template_answers`](Self::task_template_answers).
1492 async fn document_template_answers(
1493 &self,
1494 id: &NativeId,
1495 ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1496 let _ = id;
1497 Ok(None)
1498 }
1499
1500 /// The template answers the project `id` was last rendered from, on exactly the terms of
1501 /// [`task_template_answers`](Self::task_template_answers).
1502 ///
1503 /// # Errors
1504 ///
1505 /// As [`task_template_answers`](Self::task_template_answers).
1506 async fn project_template_answers(
1507 &self,
1508 id: &NativeId,
1509 ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1510 let _ = id;
1511 Ok(None)
1512 }
1513
1514 /// Create or update one task exactly as [`write_task`](Self::write_task) does, keeping
1515 /// `answers` — the answers its content was rendered from — beside it in the same write
1516 /// where this source keeps answers at all.
1517 ///
1518 /// The task arrives carrying its provenance under [`MetadataKey::TEMPLATE_KEY`] like any
1519 /// other metadata entry. Defaulted to [`write_task`](Self::write_task) alone: a source that
1520 /// keeps no answers writes the task and nothing beside it, which is the whole of what it
1521 /// owes. A source that keeps them writes the task and the answers together, so a reader
1522 /// never finds one without the other.
1523 ///
1524 /// # Errors
1525 ///
1526 /// As [`write_task`](Self::write_task).
1527 async fn write_task_rendered(
1528 &self,
1529 write: &ItemWrite<Task>,
1530 answers: &BTreeMap<String, Value>,
1531 ) -> Result<NativeId, SourceError> {
1532 let _ = answers;
1533 self.write_task(write).await
1534 }
1535
1536 /// Create or update one document, on exactly the terms of
1537 /// [`write_task_rendered`](Self::write_task_rendered).
1538 ///
1539 /// # Errors
1540 ///
1541 /// As [`write_document`](Self::write_document).
1542 async fn write_document_rendered(
1543 &self,
1544 write: &ItemWrite<Document>,
1545 answers: &BTreeMap<String, Value>,
1546 ) -> Result<NativeId, SourceError> {
1547 let _ = answers;
1548 self.write_document(write).await
1549 }
1550
1551 /// Create or update one project, on exactly the terms of
1552 /// [`write_task_rendered`](Self::write_task_rendered).
1553 ///
1554 /// # Errors
1555 ///
1556 /// As [`write_project`](Self::write_project).
1557 async fn write_project_rendered(
1558 &self,
1559 write: &ItemWrite<Project>,
1560 answers: &BTreeMap<String, Value>,
1561 ) -> Result<NativeId, SourceError> {
1562 let _ = answers;
1563 self.write_project(write).await
1564 }
1565
1566 /// Replace one task's rendering — its content, byte for byte, its
1567 /// [`MetadataKey::TEMPLATE_KEY`] entry, set to `provenance`, and the answers it keeps
1568 /// beside the task where it keeps any — in one write, and change nothing else about it;
1569 /// or answer `None` when this source holds no such task.
1570 ///
1571 /// The content is [`Task::content`] exactly as a later read reports it, on the terms of
1572 /// [`set_task_content`](Self::set_task_content). Title, status, priority, labels, every
1573 /// other metadata entry, repositories, dependencies, [`Task::delivers`],
1574 /// [`Task::delivered_by`], project and comments are left exactly as they are. The write is
1575 /// one write: a reader sees the task as it was or as it is now, never a new content beside
1576 /// the old provenance or the old answers.
1577 ///
1578 /// Defaulted to [`unwritable_field`] on exactly the terms of
1579 /// [`set_task_status`](Self::set_task_status). A source declaring
1580 /// [`WriteSupport::Unsupported`] is never asked.
1581 ///
1582 /// [`Task::delivers`]: crate::Task::delivers
1583 /// [`Task::delivered_by`]: crate::Task::delivered_by
1584 ///
1585 /// # Errors
1586 ///
1587 /// Returns [`SourceError::Refused`] when this source cannot replace a task's rendering on
1588 /// its own, or cannot represent this one; and whatever else the source could not do the
1589 /// write for.
1590 async fn set_task_rendering(
1591 &self,
1592 id: &NativeId,
1593 content: &str,
1594 provenance: &Value,
1595 answers: &BTreeMap<String, Value>,
1596 ) -> Result<Option<()>, SourceError> {
1597 let _ = (id, content, provenance, answers);
1598 Err(unwritable_field(self.kind(), "rendering"))
1599 }
1600
1601 /// Replace one document's rendering, on exactly the terms of
1602 /// [`set_task_rendering`](Self::set_task_rendering). A source declaring
1603 /// [`Capabilities::documents`] unsupported is never asked.
1604 ///
1605 /// # Errors
1606 ///
1607 /// As [`set_task_rendering`](Self::set_task_rendering).
1608 async fn set_document_rendering(
1609 &self,
1610 id: &NativeId,
1611 content: &str,
1612 provenance: &Value,
1613 answers: &BTreeMap<String, Value>,
1614 ) -> Result<Option<()>, SourceError> {
1615 let _ = (id, content, provenance, answers);
1616 Err(SourceError::Refused {
1617 message: format!(
1618 "the {} plugin cannot write a document's rendering on its own",
1619 self.kind()
1620 ),
1621 })
1622 }
1623
1624 /// Replace one project's rendering, on exactly the terms of
1625 /// [`set_task_rendering`](Self::set_task_rendering): its content, its
1626 /// [`MetadataKey::TEMPLATE_KEY`] entry and the answers kept beside it change, and its
1627 /// title, status, labels, every other metadata entry, repositories and dependencies are
1628 /// left exactly as they are.
1629 ///
1630 /// # Errors
1631 ///
1632 /// As [`set_task_rendering`](Self::set_task_rendering).
1633 async fn set_project_rendering(
1634 &self,
1635 id: &NativeId,
1636 content: &str,
1637 provenance: &Value,
1638 answers: &BTreeMap<String, Value>,
1639 ) -> Result<Option<()>, SourceError> {
1640 let _ = (id, content, provenance, answers);
1641 Err(SourceError::Refused {
1642 message: format!(
1643 "the {} plugin cannot write a project's rendering on its own",
1644 self.kind()
1645 ),
1646 })
1647 }
1648
1649 /// The image assets the task `id` holds, or none when it holds none or this source holds
1650 /// no such task.
1651 ///
1652 /// Defaulted to none, which is what keeps assets an addition rather than a break: a source
1653 /// that keeps no assets needs no edit and reports every record as holding none. A source
1654 /// declaring [`Capabilities::assets`] native answers what it holds for the record, in any
1655 /// order — the engine orders them by the content's first reference.
1656 ///
1657 /// # Errors
1658 ///
1659 /// Returns a [`SourceError`] when the source could not answer.
1660 async fn task_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
1661 let _ = id;
1662 Ok(Vec::new())
1663 }
1664
1665 /// The image assets the document `id` holds, on exactly the terms of
1666 /// [`task_assets`](Self::task_assets).
1667 ///
1668 /// # Errors
1669 ///
1670 /// As [`task_assets`](Self::task_assets).
1671 async fn document_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
1672 let _ = id;
1673 Ok(Vec::new())
1674 }
1675
1676 /// The bytes of the asset `name` the task `id` holds, or `None` when it holds no such asset
1677 /// or this source holds no such task.
1678 ///
1679 /// Defaulted to `None`, on the terms of [`task_assets`](Self::task_assets).
1680 ///
1681 /// # Errors
1682 ///
1683 /// Returns a [`SourceError`] when the source could not answer.
1684 async fn task_asset(
1685 &self,
1686 id: &NativeId,
1687 name: &AssetName,
1688 ) -> Result<Option<Vec<u8>>, SourceError> {
1689 let _ = (id, name);
1690 Ok(None)
1691 }
1692
1693 /// The bytes of the asset `name` the document `id` holds, on exactly the terms of
1694 /// [`task_asset`](Self::task_asset).
1695 ///
1696 /// # Errors
1697 ///
1698 /// As [`task_asset`](Self::task_asset).
1699 async fn document_asset(
1700 &self,
1701 id: &NativeId,
1702 name: &AssetName,
1703 ) -> Result<Option<Vec<u8>>, SourceError> {
1704 let _ = (id, name);
1705 Ok(None)
1706 }
1707
1708 /// Create or update one task carrying image assets, in one write: the task as
1709 /// [`write_task`](Self::write_task) writes it — or, with `answers`, as
1710 /// [`write_task_rendered`](Self::write_task_rendered) does — and `assets` as the record's
1711 /// whole asset set, answering with where it landed and the content as stored.
1712 ///
1713 /// Only a source declaring [`Capabilities::assets`] native is asked, and the engine has
1714 /// already checked that every reference in the content names one of `assets` and every one
1715 /// of `assets` is referenced. A source that keeps the bytes beside the record stores each
1716 /// payload under its name, removes every asset the record held that `assets` does not
1717 /// name, and answers the content unchanged. A source that serves them at a URL uploads each
1718 /// payload that carries bytes, reuses the URL [`AssetWrite::recorded_assets`] records for
1719 /// each that does not, and writes the record through
1720 /// [`serve_asset_references`](crate::serve_asset_references) — so its references point at
1721 /// those URLs, its [`MetadataKey::ASSETS_KEY`] records each `{sha256, url}`, and a
1722 /// rendering's `body_digest` stays true of what landed — answering the content it wrote.
1723 ///
1724 /// Defaulted to [`assetless`], which is what a source with no assets answers.
1725 ///
1726 /// # Errors
1727 ///
1728 /// As [`write_task`](Self::write_task), and [`SourceError::Refused`] from a source that
1729 /// keeps no assets.
1730 async fn write_task_with_assets(
1731 &self,
1732 write: &ItemWrite<Task>,
1733 answers: Option<&BTreeMap<String, Value>>,
1734 assets: &AssetWrite,
1735 ) -> Result<AssetsWritten, SourceError> {
1736 let _ = (write, answers, assets);
1737 Err(assetless(self.kind()))
1738 }
1739
1740 /// Create or update one document carrying image assets, on exactly the terms of
1741 /// [`write_task_with_assets`](Self::write_task_with_assets).
1742 ///
1743 /// # Errors
1744 ///
1745 /// As [`write_task_with_assets`](Self::write_task_with_assets).
1746 async fn write_document_with_assets(
1747 &self,
1748 write: &ItemWrite<Document>,
1749 answers: Option<&BTreeMap<String, Value>>,
1750 assets: &AssetWrite,
1751 ) -> Result<AssetsWritten, SourceError> {
1752 let _ = (write, answers, assets);
1753 Err(assetless(self.kind()))
1754 }
1755
1756 /// Replace one task's rendering as [`set_task_rendering`](Self::set_task_rendering) does,
1757 /// and its asset set as [`write_task_with_assets`](Self::write_task_with_assets) does, in
1758 /// one write; or answer `None` when this source holds no such task.
1759 ///
1760 /// Defaulted to [`assetless`].
1761 ///
1762 /// # Errors
1763 ///
1764 /// As [`set_task_rendering`](Self::set_task_rendering), and [`SourceError::Refused`] from a
1765 /// source that keeps no assets.
1766 async fn set_task_rendering_with_assets(
1767 &self,
1768 id: &NativeId,
1769 content: &str,
1770 provenance: &Value,
1771 answers: &BTreeMap<String, Value>,
1772 assets: &AssetWrite,
1773 ) -> Result<Option<AssetsWritten>, SourceError> {
1774 let _ = (id, content, provenance, answers, assets);
1775 Err(assetless(self.kind()))
1776 }
1777
1778 /// Replace one document's rendering and its asset set, on exactly the terms of
1779 /// [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
1780 ///
1781 /// # Errors
1782 ///
1783 /// As [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
1784 async fn set_document_rendering_with_assets(
1785 &self,
1786 id: &NativeId,
1787 content: &str,
1788 provenance: &Value,
1789 answers: &BTreeMap<String, Value>,
1790 assets: &AssetWrite,
1791 ) -> Result<Option<AssetsWritten>, SourceError> {
1792 let _ = (id, content, provenance, answers, assets);
1793 Err(assetless(self.kind()))
1794 }
1795
1796 /// What this source has sent to its backend since it was built and what that spent, or
1797 /// `None` when it does not meter its own requests.
1798 ///
1799 /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
1800 /// source that does not count its requests needs no edit, and is reported as not
1801 /// metering rather than as having spent nothing. A source that answers owes a running
1802 /// total — see [`Metering`] — because what one command spent is read as the difference
1803 /// between two readings.
1804 ///
1805 /// # Errors
1806 ///
1807 /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
1808 /// reports such a source as not metering; what a command cost is never a reason for the
1809 /// command to fail.
1810 async fn metering(&self) -> Result<Option<Metering>, SourceError> {
1811 Ok(None)
1812 }
1813
1814 /// End one command: drop everything held that a person can change.
1815 ///
1816 /// A command is one unit of work — one invocation of the binary, or whatever a caller
1817 /// holding one engine for many units of work calls between them. Within a command a
1818 /// source may hold what it read and reuse it; across this call it may not. After it
1819 /// returns, a source answers no read and bases no write on item content, statuses, board
1820 /// contents or search results it held before the call. It may keep only identifiers and
1821 /// vocabulary that stay valid in normal use — a repository's node id, a team's workflow
1822 /// states — and only where a lookup that misses one re-reads rather than refusing.
1823 ///
1824 /// Defaulted to doing nothing, which is right for a source that holds nothing between
1825 /// calls or holds only what the rule above lets it keep. A source that holds more owes
1826 /// an override. Never called by the engine on its own: the binary's one command is its
1827 /// whole process, so only a caller that outlives a command calls it.
1828 ///
1829 /// # Errors
1830 ///
1831 /// Returns a [`SourceError`] when the source could not be sure it dropped what it held —
1832 /// ordinarily a hosted plugin that did not answer. A caller should not go on to the next
1833 /// command on that source's earlier reads.
1834 async fn end_command(&self) -> Result<(), SourceError> {
1835 Ok(())
1836 }
1837
1838 /// Who can read where `target` lands, read live from the backend.
1839 ///
1840 /// This is the destination's reality, which the engine holds a declaration against
1841 /// before it lets a write through: a source a configuration declares private receives an
1842 /// item that may only be written somewhere private only while this answers
1843 /// [`Visibility::Private`]. The engine asks immediately before the write it is about, so
1844 /// a source must not answer from anything it read for an earlier write unless its
1845 /// backend's visibility cannot change in between.
1846 ///
1847 /// Defaulted to [`Visibility::Unknown`], which is the answer of a source that cannot say
1848 /// and is never treated as private. A source on this machine answers `Private` — what it
1849 /// writes stays on the host — and a hosted source reads its backend.
1850 ///
1851 /// # Errors
1852 ///
1853 /// Returns a [`SourceError`] when the backend could not be asked or would not answer —
1854 /// a credential lacking the scope the read needs among them. An unreadable visibility is
1855 /// never guessed: the engine refuses the write.
1856 async fn visibility(&self, target: &WriteTarget<'_>) -> Result<Visibility, SourceError> {
1857 let _ = target;
1858 Ok(Visibility::Unknown)
1859 }
1860}
1861
1862/// The factory that turns one configuration block into a live [`TaskSource`].
1863///
1864/// Having the compile-time registry and the subprocess seam be the same shape is
1865/// the whole reason this is a trait rather than a free function.
1866pub trait SourcePlugin: Send + Sync + 'static {
1867 /// The name a configuration document's `plugin:` field names.
1868 fn kind(&self) -> &'static str;
1869
1870 /// The JSON Schema for this plugin's own `config:` block.
1871 fn config_schema(&self) -> Schema;
1872
1873 /// Build a live source from one configuration block.
1874 ///
1875 /// `name` is the configured source's name, for error messages only — a
1876 /// plugin never learns it for any other purpose.
1877 ///
1878 /// # Errors
1879 ///
1880 /// Returns [`SourceError::Config`] when `config` is not valid for this
1881 /// plugin, or [`SourceError::Auth`] when a named credential is absent.
1882 fn build(
1883 &self,
1884 name: &SourceName,
1885 config: &serde_json::Value,
1886 secrets: &dyn SecretResolver,
1887 ) -> Result<Box<dyn TaskSource>, SourceError>;
1888
1889 /// Build a live source from one configuration block, handing it the clock it paces and
1890 /// backs off on.
1891 ///
1892 /// The binary builds every in-process source through this, with the process's one
1893 /// [`SharedClock`] — [`system_clock`](crate::system_clock) unless a test asked for
1894 /// simulated time. Defaulted to [`build`](Self::build), which ignores the clock: a plugin
1895 /// that never waits needs no edit, and one that does overrides this and routes its waits
1896 /// through `clock`.
1897 ///
1898 /// # Errors
1899 ///
1900 /// As [`build`](Self::build).
1901 fn build_with_clock(
1902 &self,
1903 name: &SourceName,
1904 config: &serde_json::Value,
1905 secrets: &dyn SecretResolver,
1906 clock: SharedClock,
1907 ) -> Result<Box<dyn TaskSource>, SourceError> {
1908 let _ = clock;
1909 self.build(name, config, secrets)
1910 }
1911
1912 /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
1913 /// paths into that block.
1914 ///
1915 /// A relative value at one of these, **supplied by a configuration document**, is
1916 /// resolved against the directory holding that document before [`Self::build`] sees it;
1917 /// supplied through the environment or a flag it keeps resolving against the process
1918 /// working directory, because there is no document to rebase it on. A plugin is handed
1919 /// values and no origins, so this declaration is the only way it can say which of its
1920 /// own fields that rule reaches.
1921 ///
1922 /// Defaulted to none, which is what keeps this an addition rather than a break: a
1923 /// plugin whose block holds no path needs no edit, and a caller asks every plugin
1924 /// rather than keeping a table of which ones answer.
1925 // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
1926 // is a name, and no type can make a wrong one unrepresentable here: every string is a
1927 // syntactically valid dotted path, so a newtype would validate nothing and would only
1928 // move where a name that is not a field of *this* plugin is accepted. What decides that
1929 // is whether the name is a property of the schema `config_schema` publishes — a
1930 // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
1931 // `document_relative_fields_are_fields_this_plugin_declares` in
1932 // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
1933 // own copy of.
1934 fn document_relative_paths(&self) -> &'static [&'static str] {
1935 &[]
1936 }
1937
1938 /// What names the remote store a source built from `config` reads — a board's owner and
1939 /// number, a Linear endpoint and team — or `None` for a source with no remote.
1940 ///
1941 /// The store's local cache of a remote source lives under a digest of this, so every
1942 /// process configuring the same remote shares one cache and no two remotes share one.
1943 /// Defaulted to `None`, which is what a source keeping its work on this machine — a
1944 /// folder of Markdown — answers: it has nothing to cache, and its cache setting is
1945 /// ignored. A `config` this plugin would refuse answers `None` too.
1946 fn remote_identity(&self, config: &serde_json::Value) -> Option<String> {
1947 let _ = config;
1948 None
1949 }
1950}
1951
1952/// How a plugin reads the credential its configuration names.
1953///
1954/// A configuration document never carries a credential value, only the name of
1955/// the environment variable holding it.
1956pub trait SecretResolver: Send + Sync {
1957 /// The value of `var`, or `None` when nothing defines it.
1958 ///
1959 /// The returned value is never logged and never appears in `Debug` output.
1960 fn get(&self, var: &str) -> Option<SecretString>;
1961}