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.
137fn handler(request: Request<Input>) -> Result<Output, Error> {
138    let ids = wanted_ids(request.data.ids)?;
139
140    let loaded: Loaded =
141        simple::graphql::query(LOAD_KNOWLEDGE, json!({ "ids": ids, "limit": ids.len() }))?;
142
143    let mut found: HashMap<String, Item> = loaded
144        .knowledge
145        .into_iter()
146        .filter_map(|article| {
147            let id = trimmed(&article.id);
148
149            if id.is_empty() {
150                return None;
151            }
152
153            Some((id.clone(), item(id, article)))
154        })
155        .collect();
156
157    let missing: Vec<&String> = ids.iter().filter(|id| !found.contains_key(*id)).collect();
158
159    if !missing.is_empty() {
160        return Err(Error::invalid(format!(
161            "Knowledge article(s) not found: {}.",
162            join(&missing)
163        ))
164        .details(json!({ "missing": missing }))
165        .hint("Search for the article before loading it, or drop the id that does not exist."));
166    }
167
168    Ok(Output {
169        items: ids
170            .iter()
171            .filter_map(|id| found.remove(id))
172            .collect::<Vec<Item>>(),
173    })
174}
175
176/// The ids to load: trimmed, de-duplicated, and every one of them a `KNOW` id.
177fn wanted_ids(requested: Vec<String>) -> Result<Vec<String>, Error> {
178    let mut wanted: Vec<String> = Vec::with_capacity(requested.len());
179    let mut invalid: Vec<String> = Vec::new();
180
181    for id in requested {
182        let id = id.trim().to_string();
183
184        if id.is_empty() {
185            continue;
186        }
187
188        if !id.starts_with("KNOW") {
189            invalid.push(id);
190            continue;
191        }
192
193        if !wanted.contains(&id) {
194            wanted.push(id);
195        }
196    }
197
198    if !invalid.is_empty() {
199        return Err(
200            Error::invalid(format!("Invalid knowledge id(s): {}.", join(&invalid)))
201                .details(json!({ "invalid": invalid }))
202                .hint("A knowledge id begins with KNOW."),
203        );
204    }
205
206    if wanted.is_empty() {
207        return Err(Error::invalid("'ids' must contain at least one KNOW id.")
208            .hint("Pass one or more knowledge record ids."));
209    }
210
211    Ok(wanted)
212}
213
214/// One row, reduced to what a caller can act on.
215///
216/// The editor's name is preferred over the creator's, and the updated timestamp
217/// over the created one, because what a reader wants is the state of the article
218/// now rather than its provenance.
219fn item(id: String, article: Article) -> Item {
220    let editor = article.editor.unwrap_or_default().full_name();
221    let creator = article.creator.unwrap_or_default().full_name();
222
223    Item {
224        id,
225        title: trimmed(&article.title),
226        body: trimmed(&article.body),
227        updated_by: if editor.is_empty() { creator } else { editor },
228        updated_at: match trimmed(&article.updated_at) {
229            empty if empty.is_empty() => trimmed(&article.created_at),
230            updated => updated,
231        },
232    }
233}
234
235/// A value the row may not have carried, as a trimmed string.
236fn trimmed(value: &Option<String>) -> String {
237    value.as_deref().unwrap_or_default().trim().to_string()
238}
239
240/// A list of names, for a sentence.
241fn join<T: std::fmt::Display>(values: &[T]) -> String {
242    values
243        .iter()
244        .map(T::to_string)
245        .collect::<Vec<String>>()
246        .join(", ")
247}
248
249#[cfg(test)]
250mod tests {
251    use simpleplatform_sdk::testing;
252
253    use super::*;
254
255    fn article(id: &str) -> Value {
256        json!({
257            "id": id,
258            "title": format!("Title of {id}"),
259            "body": "  Body.  ",
260            "created_at": "2026-01-01T00:00:00Z",
261            "updated_at": "2026-02-02T00:00:00Z",
262            "creator": { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@acme.test" },
263            "editor": { "first_name": "Grace", "last_name": null, "email": "grace@acme.test" }
264        })
265    }
266
267    #[test]
268    fn it_loads_articles_in_the_order_they_were_asked_for() {
269        let session = testing::install(|_name, params| {
270            assert_eq!(params["variables"]["ids"], json!(["KNOW2", "KNOW1"]));
271            assert_eq!(params["variables"]["limit"], json!(2));
272
273            Ok(json!({ "knowledge": [article("KNOW1"), article("KNOW2")] }))
274        });
275
276        let output = handler(Request::new(Input {
277            ids: vec!["KNOW2".into(), " KNOW1 ".into(), "KNOW2".into()],
278        }))
279        .unwrap();
280
281        assert_eq!(
282            output.items.iter().map(|item| &item.id).collect::<Vec<_>>(),
283            vec!["KNOW2", "KNOW1"]
284        );
285        assert_eq!(output.items[0].body, "Body.");
286        assert_eq!(output.items[0].updated_by, "Grace");
287        assert_eq!(output.items[0].updated_at, "2026-02-02T00:00:00Z");
288        assert_eq!(session.calls().len(), 1);
289    }
290
291    #[test]
292    fn a_row_with_no_editor_falls_back_to_its_creator() {
293        let _session = testing::install(|_name, _params| {
294            Ok(json!({
295                "knowledge": [{
296                    "id": "KNOW1",
297                    "title": "T",
298                    "body": "B",
299                    "created_at": "2026-01-01T00:00:00Z",
300                    "updated_at": null,
301                    "creator": { "first_name": "Ada", "last_name": "Lovelace" },
302                    "editor": null
303                }]
304            }))
305        });
306
307        let output = handler(Request::new(Input {
308            ids: vec!["KNOW1".into()],
309        }))
310        .unwrap();
311
312        assert_eq!(output.items[0].updated_by, "Ada Lovelace");
313        assert_eq!(output.items[0].updated_at, "2026-01-01T00:00:00Z");
314    }
315
316    #[test]
317    fn an_id_that_is_not_a_knowledge_id_is_refused_before_the_read() {
318        let session = testing::install(|_name, _params| Ok(json!({ "knowledge": [] })));
319
320        let error = handler(Request::new(Input {
321            ids: vec!["KNOW1".into(), "PROJ9".into()],
322        }))
323        .unwrap_err();
324
325        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
326        assert!(error.message().contains("PROJ9"));
327        assert!(session.calls().is_empty());
328    }
329
330    #[test]
331    fn an_article_that_does_not_exist_is_named() {
332        let _session =
333            testing::install(|_name, _params| Ok(json!({ "knowledge": [article("KNOW1")] })));
334
335        let error = handler(Request::new(Input {
336            ids: vec!["KNOW1".into(), "KNOW404".into()],
337        }))
338        .unwrap_err();
339
340        assert!(error.message().contains("KNOW404"));
341        assert_eq!(error.fault().details()["missing"], json!(["KNOW404"]));
342    }
343
344    #[test]
345    fn a_read_that_answers_with_the_wrong_shape_is_a_response_failure() {
346        let _session = testing::install(|_name, _params| Ok(json!({ "knowledge": "nope" })));
347
348        let error = handler(Request::new(Input {
349            ids: vec!["KNOW1".into()],
350        }))
351        .unwrap_err();
352
353        assert_eq!(error.code().as_str(), "INVALID_QUERY_RESPONSE");
354    }
355
356    #[test]
357    fn a_read_the_host_refused_says_a_failed_read_changed_nothing() {
358        let _session =
359            testing::install(|_name, _params| Err(Error::failed("database unavailable")));
360
361        let error = handler(Request::new(Input {
362            ids: vec!["KNOW1".into()],
363        }))
364        .unwrap_err();
365
366        assert_eq!(error.code().as_str(), "QUERY_EXECUTION_FAILED");
367    }
368
369    #[test]
370    fn the_whole_run_reports_one_readable_envelope() {
371        let session =
372            testing::install(|_name, _params| Ok(json!({ "knowledge": [article("KNOW1")] })))
373                .with_request(json!({ "ids": ["KNOW1"] }));
374
375        simple::run(handler);
376
377        let done = session.done().unwrap();
378
379        assert_eq!(done["ok"], json!(true));
380        assert_eq!(done["errors"], json!([]));
381        assert_eq!(done["data"]["items"][0]["id"], json!("KNOW1"));
382    }
383
384    #[test]
385    fn a_failing_run_reports_a_failure_the_platform_can_read() {
386        let session = testing::install(|_name, _params| Ok(json!({ "knowledge": [] })))
387            .with_request(json!({ "ids": ["NOPE"] }));
388
389        simple::run(handler);
390
391        let extensions = session.done().unwrap()["data"]["error"]["extensions"].clone();
392
393        assert_eq!(extensions["code"], json!("INVALID_TOOL_INPUT"));
394        assert_eq!(extensions["category"], json!("validation"));
395        assert_eq!(extensions["retryable"], json!(false));
396        assert!(extensions["details"].is_object());
397        assert!(extensions["hint"].is_string());
398    }
399}