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, DependencyEdge, Direction, Document, DocumentQuery, ItemWrite, Label, NativeId,
9    Page, PageRequest, Project, ProjectQuery, SourceError, SourceName, Task, TaskQuery,
10    WriteSupport, 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
281/// The factory that turns one configuration block into a live [`TaskSource`].
282///
283/// Having the compile-time registry and the subprocess seam be the same shape is
284/// the whole reason this is a trait rather than a free function.
285pub trait SourcePlugin: Send + Sync + 'static {
286    /// The name a configuration document's `plugin:` field names.
287    fn kind(&self) -> &'static str;
288
289    /// The JSON Schema for this plugin's own `config:` block.
290    fn config_schema(&self) -> Schema;
291
292    /// Build a live source from one configuration block.
293    ///
294    /// `name` is the configured source's name, for error messages only — a
295    /// plugin never learns it for any other purpose.
296    ///
297    /// # Errors
298    ///
299    /// Returns [`SourceError::Config`] when `config` is not valid for this
300    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
301    fn build(
302        &self,
303        name: &SourceName,
304        config: &serde_json::Value,
305        secrets: &dyn SecretResolver,
306    ) -> Result<Box<dyn TaskSource>, SourceError>;
307}
308
309/// How a plugin reads the credential its configuration names.
310///
311/// A configuration document never carries a credential value, only the name of
312/// the environment variable holding it.
313pub trait SecretResolver: Send + Sync {
314    /// The value of `var`, or `None` when nothing defines it.
315    ///
316    /// The returned value is never logged and never appears in `Debug` output.
317    fn get(&self, var: &str) -> Option<SecretString>;
318}