Skip to main content

load_knowledge/
load_knowledge.rs

1//! `load-knowledge`: fetch knowledge articles by id, ready to act on.
2//!
3//! A complete action, and a good one to read first. Its whole surface is a
4//! payload, one GraphQL read and a result, which is the smallest shape a real
5//! action has.
6//!
7//! # What to take from it
8//!
9//! **Describe the answer you want, then deserialise into it.** `Loaded` and
10//! `Article` below are the shape the query asks for, so the answer is decoded
11//! once, into types, and the handler works on Rust values from its first line.
12//! An answer that does not fit that shape becomes `INVALID_QUERY_RESPONSE`
13//! before the handler is entered, so there is no shape-checking to write.
14//!
15//! **Let a row be missing what it was not given.** Every member of `Article` is
16//! optional and defaulted, because a GraphQL row may answer `null` for anything
17//! it was asked for. A short row is then a row with empty members.
18//!
19//! **Refuse with a code.** Each refusal here carries one: a malformed or absent
20//! id is `INVALID_TOOL_INPUT` with `details` naming the ids and a `hint` saying
21//! what to do next, and a read the host refused arrives as
22//! `QUERY_EXECUTION_FAILED`, which says a failed read changed nothing. A caller
23//! that gets a code can decide what to do; a caller that gets prose has to
24//! guess.
25
26use std::collections::HashMap;
27
28use simpleplatform_sdk::prelude::*;
29
30/// The advertised input: knowledge record ids.
31///
32/// One constraint, because one is what this action actually asks for: it needs
33/// at least one id to load anything, and `length` on a collection is a count of
34/// its elements. The `KNOW` prefix each id carries is a rule about the strings
35/// inside the collection rather than about the collection, so it is described
36/// in the doc comment and enforced in `wanted_ids`, which is where the refusal
37/// can name the ids that broke it.
38#[derive(Deserialize, Schema)]
39struct Input {
40    /// Knowledge record ids (`KNOW...`).
41    #[simple(length(min = 1))]
42    ids: Vec<String>,
43}
44
45/// The read, in the shape the query asks for.
46#[derive(Deserialize)]
47struct Loaded {
48    knowledge: Vec<Article>,
49}
50
51/// One row of it.
52///
53/// Every member is optional and defaulted, because a GraphQL row may answer
54/// `null` for anything it was asked for and a selection may be narrowed later.
55/// A row that arrives short is then a row with empty members, not a failure.
56#[derive(Default, Deserialize)]
57#[serde(default)]
58struct Article {
59    id: Option<String>,
60    title: Option<String>,
61    body: Option<String>,
62    created_at: Option<String>,
63    updated_at: Option<String>,
64    creator: Option<Person>,
65    editor: Option<Person>,
66}
67
68/// Whoever wrote or last edited a row.
69#[derive(Default, Deserialize)]
70#[serde(default)]
71struct Person {
72    first_name: Option<String>,
73    last_name: Option<String>,
74    email: Option<String>,
75}
76
77impl Person {
78    /// The fullest name this person has, or their email, or nothing.
79    fn full_name(&self) -> String {
80        let first = trimmed(&self.first_name);
81        let last = trimmed(&self.last_name);
82
83        match (first.is_empty(), last.is_empty()) {
84            (false, false) => format!("{first} {last}"),
85            (false, true) => first,
86            (true, false) => last,
87            (true, true) => trimmed(&self.email),
88        }
89    }
90}
91
92/// One article, as this action reports it.
93#[derive(Debug, Serialize)]
94struct Item {
95    id: String,
96    title: String,
97    body: String,
98    updated_by: String,
99    updated_at: String,
100}
101
102/// What the action returns.
103#[derive(Debug, Serialize)]
104struct Output {
105    items: Vec<Item>,
106}
107
108const LOAD_KNOWLEDGE: &str = r#"
109    query LoadKnowledgeBatch($ids: [ID!]!, $limit: Int!) {
110      knowledge: dev_simple_system__knowledge(where: {id: {_in: $ids}}, limit: $limit) {
111        id
112        title
113        body
114        created_at
115        updated_at
116        creator { first_name last_name email }
117        editor { first_name last_name email }
118      }
119    }"#;
120
121fn main() {
122    simple::run(handler)
123}
124
125/// Load one or more knowledge articles by id, with execution-ready fields.
126///
127/// Every article comes back with its title, its body, and the name of whoever
128/// last touched it with the time they did, in the order the ids were given. An
129/// id that matches nothing is named in the refusal rather than dropped from the
130/// answer, so a caller either gets every article it asked for or is told which
131/// one it cannot have.
132///
133/// @tool
134/// @shortdesc Fetch knowledge articles by id, each with its title, body, and who last updated it when.
135/// @usewhen The id of a knowledge article is known and its contents are needed.
136/// @usewhen Several knowledge ids came out of a search and have to be read together.
137/// @parallelsafe
138fn handler(request: Request<Input>) -> Result<Output, Error> {
139    let ids = wanted_ids(request.data.ids)?;
140
141    let loaded: Loaded =
142        simple::graphql::query(LOAD_KNOWLEDGE, json!({ "ids": ids, "limit": ids.len() }))?;
143
144    let mut found: HashMap<String, Item> = loaded
145        .knowledge
146        .into_iter()
147        .filter_map(|article| {
148            let id = trimmed(&article.id);
149
150            if id.is_empty() {
151                return None;
152            }
153
154            Some((id.clone(), item(id, article)))
155        })
156        .collect();
157
158    let missing: Vec<&String> = ids.iter().filter(|id| !found.contains_key(*id)).collect();
159
160    if !missing.is_empty() {
161        return Err(Error::invalid(format!(
162            "Knowledge article(s) not found: {}.",
163            join(&missing)
164        ))
165        .details(json!({ "missing": missing }))
166        .hint("Search for the article before loading it, or drop the id that does not exist."));
167    }
168
169    Ok(Output {
170        items: ids
171            .iter()
172            .filter_map(|id| found.remove(id))
173            .collect::<Vec<Item>>(),
174    })
175}
176
177/// The ids to load: trimmed, de-duplicated, and every one of them a `KNOW` id.
178fn wanted_ids(requested: Vec<String>) -> Result<Vec<String>, Error> {
179    let mut wanted: Vec<String> = Vec::with_capacity(requested.len());
180    let mut invalid: Vec<String> = Vec::new();
181
182    for id in requested {
183        let id = id.trim().to_string();
184
185        if id.is_empty() {
186            continue;
187        }
188
189        if !id.starts_with("KNOW") {
190            invalid.push(id);
191            continue;
192        }
193
194        if !wanted.contains(&id) {
195            wanted.push(id);
196        }
197    }
198
199    if !invalid.is_empty() {
200        return Err(
201            Error::invalid(format!("Invalid knowledge id(s): {}.", join(&invalid)))
202                .details(json!({ "invalid": invalid }))
203                .hint("A knowledge id begins with KNOW."),
204        );
205    }
206
207    if wanted.is_empty() {
208        return Err(Error::invalid("'ids' must contain at least one KNOW id.")
209            .hint("Pass one or more knowledge record ids."));
210    }
211
212    Ok(wanted)
213}
214
215/// One row, reduced to what a caller can act on.
216///
217/// The editor's name is preferred over the creator's, and the updated timestamp
218/// over the created one, because what a reader wants is the state of the article
219/// now rather than its provenance.
220fn item(id: String, article: Article) -> Item {
221    let editor = article.editor.unwrap_or_default().full_name();
222    let creator = article.creator.unwrap_or_default().full_name();
223
224    Item {
225        id,
226        title: trimmed(&article.title),
227        body: trimmed(&article.body),
228        updated_by: if editor.is_empty() { creator } else { editor },
229        updated_at: match trimmed(&article.updated_at) {
230            empty if empty.is_empty() => trimmed(&article.created_at),
231            updated => updated,
232        },
233    }
234}
235
236/// A value the row may not have carried, as a trimmed string.
237fn trimmed(value: &Option<String>) -> String {
238    value.as_deref().unwrap_or_default().trim().to_string()
239}
240
241/// A list of names, for a sentence.
242fn join<T: std::fmt::Display>(values: &[T]) -> String {
243    values
244        .iter()
245        .map(T::to_string)
246        .collect::<Vec<String>>()
247        .join(", ")
248}
249
250#[cfg(test)]
251mod tests {
252    use simpleplatform_sdk::testing;
253
254    use super::*;
255
256    fn article(id: &str) -> Value {
257        json!({
258            "id": id,
259            "title": format!("Title of {id}"),
260            "body": "  Body.  ",
261            "created_at": "2026-01-01T00:00:00Z",
262            "updated_at": "2026-02-02T00:00:00Z",
263            "creator": { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@acme.test" },
264            "editor": { "first_name": "Grace", "last_name": null, "email": "grace@acme.test" }
265        })
266    }
267
268    #[test]
269    fn it_loads_articles_in_the_order_they_were_asked_for() {
270        let session = testing::install(|_name, params| {
271            assert_eq!(params["variables"]["ids"], json!(["KNOW2", "KNOW1"]));
272            assert_eq!(params["variables"]["limit"], json!(2));
273
274            Ok(json!({ "knowledge": [article("KNOW1"), article("KNOW2")] }))
275        });
276
277        let output = handler(Request::new(Input {
278            ids: vec!["KNOW2".into(), " KNOW1 ".into(), "KNOW2".into()],
279        }))
280        .unwrap();
281
282        assert_eq!(
283            output.items.iter().map(|item| &item.id).collect::<Vec<_>>(),
284            vec!["KNOW2", "KNOW1"]
285        );
286        assert_eq!(output.items[0].body, "Body.");
287        assert_eq!(output.items[0].updated_by, "Grace");
288        assert_eq!(output.items[0].updated_at, "2026-02-02T00:00:00Z");
289        assert_eq!(session.calls().len(), 1);
290    }
291
292    #[test]
293    fn a_row_with_no_editor_falls_back_to_its_creator() {
294        let _session = testing::install(|_name, _params| {
295            Ok(json!({
296                "knowledge": [{
297                    "id": "KNOW1",
298                    "title": "T",
299                    "body": "B",
300                    "created_at": "2026-01-01T00:00:00Z",
301                    "updated_at": null,
302                    "creator": { "first_name": "Ada", "last_name": "Lovelace" },
303                    "editor": null
304                }]
305            }))
306        });
307
308        let output = handler(Request::new(Input {
309            ids: vec!["KNOW1".into()],
310        }))
311        .unwrap();
312
313        assert_eq!(output.items[0].updated_by, "Ada Lovelace");
314        assert_eq!(output.items[0].updated_at, "2026-01-01T00:00:00Z");
315    }
316
317    #[test]
318    fn an_id_that_is_not_a_knowledge_id_is_refused_before_the_read() {
319        let session = testing::install(|_name, _params| Ok(json!({ "knowledge": [] })));
320
321        let error = handler(Request::new(Input {
322            ids: vec!["KNOW1".into(), "PROJ9".into()],
323        }))
324        .unwrap_err();
325
326        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
327        assert!(error.message().contains("PROJ9"));
328        assert!(session.calls().is_empty());
329    }
330
331    #[test]
332    fn an_article_that_does_not_exist_is_named() {
333        let _session =
334            testing::install(|_name, _params| Ok(json!({ "knowledge": [article("KNOW1")] })));
335
336        let error = handler(Request::new(Input {
337            ids: vec!["KNOW1".into(), "KNOW404".into()],
338        }))
339        .unwrap_err();
340
341        assert!(error.message().contains("KNOW404"));
342        assert_eq!(error.fault().details()["missing"], json!(["KNOW404"]));
343    }
344
345    #[test]
346    fn a_read_that_answers_with_the_wrong_shape_is_a_response_failure() {
347        let _session = testing::install(|_name, _params| Ok(json!({ "knowledge": "nope" })));
348
349        let error = handler(Request::new(Input {
350            ids: vec!["KNOW1".into()],
351        }))
352        .unwrap_err();
353
354        assert_eq!(error.code().as_str(), "INVALID_QUERY_RESPONSE");
355    }
356
357    #[test]
358    fn a_read_the_host_refused_says_a_failed_read_changed_nothing() {
359        let _session =
360            testing::install(|_name, _params| Err(Error::failed("database unavailable")));
361
362        let error = handler(Request::new(Input {
363            ids: vec!["KNOW1".into()],
364        }))
365        .unwrap_err();
366
367        assert_eq!(error.code().as_str(), "QUERY_EXECUTION_FAILED");
368    }
369
370    #[test]
371    fn the_whole_run_reports_one_readable_envelope() {
372        let session =
373            testing::install(|_name, _params| Ok(json!({ "knowledge": [article("KNOW1")] })))
374                .with_request(json!({ "ids": ["KNOW1"] }));
375
376        simple::run(handler);
377
378        let done = session.done().unwrap();
379
380        assert_eq!(done["ok"], json!(true));
381        assert_eq!(done["errors"], json!([]));
382        assert_eq!(done["data"]["items"][0]["id"], json!("KNOW1"));
383    }
384
385    #[test]
386    fn a_failing_run_reports_a_failure_the_platform_can_read() {
387        let session = testing::install(|_name, _params| Ok(json!({ "knowledge": [] })))
388            .with_request(json!({ "ids": ["NOPE"] }));
389
390        simple::run(handler);
391
392        let extensions = session.done().unwrap()["data"]["error"]["extensions"].clone();
393
394        assert_eq!(extensions["code"], json!("INVALID_TOOL_INPUT"));
395        assert_eq!(extensions["category"], json!("validation"));
396        assert_eq!(extensions["retryable"], json!(false));
397        assert!(extensions["details"].is_object());
398        assert!(extensions["hint"].is_string());
399    }
400}