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> {
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
177fn 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
215fn 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
236fn trimmed(value: &Option<String>) -> String {
238 value.as_deref().unwrap_or_default().trim().to_string()
239}
240
241fn 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}