1use std::collections::HashMap;
27
28use simpleplatform_sdk::prelude::*;
29
30#[derive(Deserialize, Schema)]
39struct Input {
40 #[simple(length(min = 1))]
42 ids: Vec<String>,
43}
44
45#[derive(Deserialize)]
47struct Loaded {
48 knowledge: Vec<Article>,
49}
50
51#[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#[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 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#[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#[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
125fn 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
176fn 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
214fn 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
235fn trimmed(value: &Option<String>) -> String {
237 value.as_deref().unwrap_or_default().trim().to_string()
238}
239
240fn 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}