Skip to main content

onetaskgraph_plugin_api/
source.rs

1//! The two traits a plugin implements, and the secret lookup it is handed.
2
3use schemars::{JsonSchema, Schema};
4use secrecy::SecretString;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    Capabilities, Comment, CommentBody, DependencyEdge, Direction, Document, DocumentQuery,
9    ItemWrite, Label, Metering, NativeId, NewComment, Page, PageRequest, Project, ProjectQuery,
10    SourceError, SourceName, Task, TaskQuery, WriteSupport, commentless, documentless, unwritable,
11};
12
13/// Whether a source is answering right now.
14///
15/// # Placement is an open contract question
16///
17/// This type lives here because [`TaskSource::health`] returns it and the trait
18/// lives here: placing it in `onetaskgraph-core` would make this crate depend on
19/// the engine and invert the one direction the crate split exists to establish.
20/// The approved contract enumerates this crate's contents exhaustively and does
21/// not name `Health`, so the enumeration and the trait as written cannot both
22/// stand. Compiling forces the placement below; the resolution — add it to the
23/// enumeration, or redesign `health` so no such type crosses the boundary —
24/// belongs to the contract's owner, not to this crate. See `AGENTS.md`.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
26// 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.
27pub struct Health {
28    /// Whether the source answered.
29    ///
30    /// A bare `bool` beside an untyped `detail` cannot say that an unreachable source
31    /// must explain itself, or keep "reachable with a warning" apart from "reachable";
32    /// an enum carrying the detail in its unreachable variant would.
33    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
34    // restates at this field the justification already recorded at
35    // `Capabilities.max_page_size` (capability.rs), `PageRequest.limit` (query.rs), this
36    // type's own doc comment above, and AGENTS.md's "Open contract question — `Health`":
37    // `Health`'s shape is approved contract text that `TaskSource::health` returns, so an
38    // enum here would change the serialized form and the trait six undispatched nodes
39    // implement. That is the contract owner's call, not this crate's.
40    // 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`".
41    pub reachable: bool,
42    /// What the source said, when it said anything useful.
43    pub detail: Option<String>,
44}
45
46/// One configured source, as the engine drives it.
47///
48/// Dyn-compatible through `async_trait` because the engine holds
49/// `Vec<Box<dyn TaskSource>>` over heterogeneous plugins.
50///
51/// Three rules bind every implementation, and the engine's compensation is only
52/// correct while all three hold:
53///
54/// 1. **Apply** every predicate you declare [`Support::Native`](crate::Support::Native).
55/// 2. **Ignore** every [`Support`](crate::Support)-typed predicate you declare
56///    `Unsupported` — return the *wider* result set, never a narrower one.
57///    Silently dropping rows for a predicate you did not declare is the one
58///    failure no test above the plugin can catch.
59/// 3. Never return a silently empty dependency read. Rule 2 reaches the
60///    `Support`-typed *predicates* alone; a dependency read is always real, and so is a
61///    document read — [`Capabilities::documents`] says whether this source has documents
62///    at all, and a source that says it has none is never asked for one rather than
63///    answering an empty page.
64#[async_trait::async_trait]
65pub trait TaskSource: Send + Sync {
66    /// The plugin kind that built this source, for display and for plan output.
67    fn kind(&self) -> &'static str;
68
69    /// What this source applies itself. Read once per query by the engine.
70    fn capabilities(&self) -> Capabilities;
71
72    /// Whether the source is answering right now.
73    ///
74    /// # Errors
75    ///
76    /// Returns a [`SourceError`] when the check itself could not be made.
77    async fn health(&self) -> Result<Health, SourceError>;
78
79    /// Fetch one task by its native id, or `None` when there is no such task.
80    ///
81    /// # Errors
82    ///
83    /// Returns a [`SourceError`] when the source could not answer.
84    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
85
86    /// Fetch one project by its native id, or `None` when there is no such project.
87    ///
88    /// # Errors
89    ///
90    /// Returns a [`SourceError`] when the source could not answer.
91    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
92
93    /// One page of the tasks matching `query`.
94    ///
95    /// # Errors
96    ///
97    /// Returns a [`SourceError`] when the source could not answer.
98    async fn query_tasks(
99        &self,
100        query: &TaskQuery,
101        page: &PageRequest,
102    ) -> Result<Page<Task>, SourceError>;
103
104    /// One page of the projects matching `query`.
105    ///
106    /// # Errors
107    ///
108    /// Returns a [`SourceError`] when the source could not answer.
109    async fn query_projects(
110        &self,
111        query: &ProjectQuery,
112        page: &PageRequest,
113    ) -> Result<Page<Project>, SourceError>;
114
115    /// One page of every label this source knows.
116    ///
117    /// # Errors
118    ///
119    /// Returns a [`SourceError`] when the source could not answer.
120    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
121
122    /// One page of the task dependency edges at `id`, in `direction`.
123    ///
124    /// # Errors
125    ///
126    /// Returns a [`SourceError`] when the source could not answer.
127    async fn task_dependencies(
128        &self,
129        id: &NativeId,
130        direction: Direction,
131        page: &PageRequest,
132    ) -> Result<Page<DependencyEdge>, SourceError>;
133
134    /// One page of the project dependency edges at `id`, in `direction`.
135    ///
136    /// # Errors
137    ///
138    /// Returns a [`SourceError`] when the source could not answer.
139    async fn project_dependencies(
140        &self,
141        id: &NativeId,
142        direction: Direction,
143        page: &PageRequest,
144    ) -> Result<Page<DependencyEdge>, SourceError>;
145
146    /// Whether this source can be written through at all.
147    ///
148    /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
149    /// interface for every source that has nothing to write into: one that cannot be
150    /// written needs no edit and keeps working. Read before a write is attempted, so a
151    /// copy naming such a source as its destination is refused before anything is read.
152    fn writes(&self) -> WriteSupport {
153        WriteSupport::Unsupported
154    }
155
156    /// Create or update one task, answering with the native id the destination holds it
157    /// under.
158    ///
159    /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
160    /// naming the field, anything it cannot represent rather than dropping it — including
161    /// a metadata key it cannot carry, which it names. It writes every other field it was
162    /// given. And it never creates when [`ItemWrite::target`] names an item it does not
163    /// hold.
164    ///
165    /// # Errors
166    ///
167    /// Returns [`SourceError::Refused`] when this source has no write side, when a field
168    /// or a metadata key cannot be represented, or when `target` names nothing here; and
169    /// whatever else the source could not do the write for.
170    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
171        let _ = write;
172        Err(unwritable(self.kind()))
173    }
174
175    /// Create or update one project, on exactly the terms of
176    /// [`write_task`](Self::write_task).
177    ///
178    /// # Errors
179    ///
180    /// As [`write_task`](Self::write_task).
181    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
182        let _ = write;
183        Err(unwritable(self.kind()))
184    }
185
186    /// Remove one task this destination holds, so a copy that could not finish can put
187    /// the destination back the way it found it.
188    ///
189    /// This is not a verb of the product: nothing a user types deletes anything, and a
190    /// copy never deletes an item it did not itself create in the run that is failing.
191    /// It exists because a copy is either complete or it never happened — a half-written
192    /// project has to be run again, and the re-run is the mutation burst that trips a
193    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
194    /// that retry at source.
195    ///
196    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
197    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
198    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
199    /// is **not** an error — the item is already gone, which is the state this asks for.
200    ///
201    /// # Errors
202    ///
203    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
204    /// else the source could not remove the item for.
205    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
206        let _ = id;
207        Err(unwritable(self.kind()))
208    }
209
210    /// Remove one project this destination holds, on exactly the terms of
211    /// [`delete_task`](Self::delete_task).
212    ///
213    /// # Errors
214    ///
215    /// As [`delete_task`](Self::delete_task).
216    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
217        let _ = id;
218        Err(unwritable(self.kind()))
219    }
220
221    /// Fetch one document by its native id, or `None` when there is no such document.
222    ///
223    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
224    /// than a break: a source with none needs no edit, keeps working, and says so in the
225    /// same words every other document-free source does. A source that has documents
226    /// declares [`Support::Native`](crate::Support::Native) for
227    /// [`Capabilities::documents`] and owes a real implementation here, because that
228    /// declaration is what makes the engine ask.
229    ///
230    /// # Errors
231    ///
232    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
233    /// else the source could not answer for.
234    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
235        let _ = id;
236        Err(documentless(self.kind()))
237    }
238
239    /// One page of the documents matching `query`.
240    ///
241    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
242    /// with no documents refuses rather than answering an empty page: an empty page reads
243    /// as a source that has documents and holds none matching, which is the one wrong
244    /// answer this method can give.
245    ///
246    /// # Errors
247    ///
248    /// As [`get_document`](Self::get_document).
249    async fn query_documents(
250        &self,
251        query: &DocumentQuery,
252        page: &PageRequest,
253    ) -> Result<Page<Document>, SourceError> {
254        let _ = (query, page);
255        Err(documentless(self.kind()))
256    }
257
258    /// Create or update one document, on exactly the terms of
259    /// [`write_task`](Self::write_task).
260    ///
261    /// # Errors
262    ///
263    /// As [`write_task`](Self::write_task).
264    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
265        let _ = write;
266        Err(unwritable(self.kind()))
267    }
268
269    /// Remove one document this destination holds, on exactly the terms of
270    /// [`delete_task`](Self::delete_task).
271    ///
272    /// # Errors
273    ///
274    /// As [`delete_task`](Self::delete_task).
275    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
276        let _ = id;
277        Err(unwritable(self.kind()))
278    }
279
280    /// One page of the comments on `task`, oldest first, or `None` when this source holds
281    /// no such task.
282    ///
283    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
284    /// break: a source with none needs no edit and keeps working. A source whose tasks have
285    /// comments declares [`Support::Native`](crate::Support::Native) for
286    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
287    /// because that declaration is what makes the engine ask.
288    ///
289    /// "No such task" is `None` rather than an error, exactly as it is for
290    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
291    ///
292    /// # Errors
293    ///
294    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
295    /// the source could not answer for.
296    async fn task_comments(
297        &self,
298        task: &NativeId,
299        page: &PageRequest,
300    ) -> Result<Option<Page<Comment>>, SourceError> {
301        let _ = (task, page);
302        Err(commentless(self.kind()))
303    }
304
305    /// Add one comment to `task`, answering with the comment as the source now holds it, or
306    /// `None` when this source holds no such task.
307    ///
308    /// The body is stored byte for byte. A source that records the author itself refuses a
309    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
310    /// represent the body refuses it, naming why, rather than escaping it into something
311    /// else.
312    ///
313    /// # Errors
314    ///
315    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
316    /// written, when it cannot record what it was given, and whatever else it could not do
317    /// the write for.
318    async fn add_comment(
319        &self,
320        task: &NativeId,
321        comment: &NewComment,
322    ) -> Result<Option<Comment>, SourceError> {
323        let _ = (task, comment);
324        Err(commentless(self.kind()))
325    }
326
327    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
328    /// source now holds it, or `None` when this source holds no such task or that task has no
329    /// such comment.
330    ///
331    /// Only the body and the time it last changed move: the id, the author and the time it
332    /// was written are the comment's own.
333    ///
334    /// # Errors
335    ///
336    /// As [`add_comment`](Self::add_comment).
337    async fn edit_comment(
338        &self,
339        task: &NativeId,
340        comment: &NativeId,
341        body: &CommentBody,
342    ) -> Result<Option<Comment>, SourceError> {
343        let _ = (task, comment, body);
344        Err(commentless(self.kind()))
345    }
346
347    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
348    /// when this source holds no such task or that task has no such comment.
349    ///
350    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
351    /// removes a comment they posted — so a comment that is not there is reported as `None`
352    /// for the engine to refuse by name, rather than treated as already gone.
353    ///
354    /// # Errors
355    ///
356    /// As [`add_comment`](Self::add_comment).
357    async fn delete_comment(
358        &self,
359        task: &NativeId,
360        comment: &NativeId,
361    ) -> Result<Option<NativeId>, SourceError> {
362        let _ = (task, comment);
363        Err(commentless(self.kind()))
364    }
365
366    /// What this source has sent to its backend since it was built and what that spent, or
367    /// `None` when it does not meter its own requests.
368    ///
369    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
370    /// source that does not count its requests needs no edit, and is reported as not
371    /// metering rather than as having spent nothing. A source that answers owes a running
372    /// total — see [`Metering`] — because what one command spent is read as the difference
373    /// between two readings.
374    ///
375    /// # Errors
376    ///
377    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
378    /// reports such a source as not metering; what a command cost is never a reason for the
379    /// command to fail.
380    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
381        Ok(None)
382    }
383}
384
385/// The factory that turns one configuration block into a live [`TaskSource`].
386///
387/// Having the compile-time registry and the subprocess seam be the same shape is
388/// the whole reason this is a trait rather than a free function.
389pub trait SourcePlugin: Send + Sync + 'static {
390    /// The name a configuration document's `plugin:` field names.
391    fn kind(&self) -> &'static str;
392
393    /// The JSON Schema for this plugin's own `config:` block.
394    fn config_schema(&self) -> Schema;
395
396    /// Build a live source from one configuration block.
397    ///
398    /// `name` is the configured source's name, for error messages only — a
399    /// plugin never learns it for any other purpose.
400    ///
401    /// # Errors
402    ///
403    /// Returns [`SourceError::Config`] when `config` is not valid for this
404    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
405    fn build(
406        &self,
407        name: &SourceName,
408        config: &serde_json::Value,
409        secrets: &dyn SecretResolver,
410    ) -> Result<Box<dyn TaskSource>, SourceError>;
411}
412
413/// How a plugin reads the credential its configuration names.
414///
415/// A configuration document never carries a credential value, only the name of
416/// the environment variable holding it.
417pub trait SecretResolver: Send + Sync {
418    /// The value of `var`, or `None` when nothing defines it.
419    ///
420    /// The returned value is never logged and never appears in `Debug` output.
421    fn get(&self, var: &str) -> Option<SecretString>;
422}