simpleplatform_sdk/
graphql.rs1use serde::de::DeserializeOwned;
56use serde_json::{json, Value};
57
58use crate::codes::Code;
59use crate::error::{Error, Fault};
60use crate::host::{self, DB_EXECUTE};
61
62pub fn query<T: DeserializeOwned>(document: &str, variables: Value) -> Result<T, Error> {
82 let document = document.trim();
83
84 if document.is_empty() {
85 return Err(Error::Input(Fault::new(
86 Code::QueryRequired,
87 "A GraphQL query is required.",
88 ))
89 .hint("Provide a non-empty read-only GraphQL query."));
90 }
91
92 if is_mutation(document) {
93 return Err(Error::Input(Fault::new(
94 Code::QueryNotAllowed,
95 "A mutation was passed to query.",
96 ))
97 .hint("Use simple::graphql::mutate for writes."));
98 }
99
100 let data = execute(document, variables).map_err(|cause| {
101 Error::Query(Fault::new(Code::QueryExecutionFailed, cause.message()))
102 .hint("Do not retry automatically. Review the query and report the execution failure.")
103 })?;
104
105 serde_json::from_value(data).map_err(|cause| {
106 Error::Query(Fault::new(
107 Code::InvalidQueryResponse,
108 format!("The query returned a response this action could not read: {cause}"),
109 ))
110 .hint("Do not retry identical inputs. Report this response-decoding failure.")
111 })
112}
113
114pub fn mutate<T: DeserializeOwned>(document: &str, variables: Value) -> Result<T, Error> {
119 let document = document.trim();
120
121 if document.is_empty() {
122 return Err(Error::Input(Fault::new(
123 Code::MutationRequired,
124 "A GraphQL mutation is required.",
125 ))
126 .hint("Provide a non-empty mutation document."));
127 }
128
129 if !is_mutation(document) {
130 return Err(Error::Input(Fault::new(
131 Code::NotAMutation,
132 "A query was passed to mutate.",
133 ))
134 .hint("Use simple::graphql::query for reads. Nothing was written."));
135 }
136
137 let data = execute(document, variables).map_err(|cause| {
138 Error::Mutation(Fault::new(Code::MutationExecutionFailed, cause.message())).hint(
139 "Treat the effect as unknown: read the target rows back before any further write. \
140 Do not repeat the mutation blindly.",
141 )
142 })?;
143
144 serde_json::from_value(data).map_err(|cause| {
145 Error::Mutation(Fault::new(
146 Code::MutationResultUnreadable,
147 format!("The mutation ran but its result could not be read: {cause}"),
148 ))
149 .hint(
150 "Treat the effect as unknown: read the target rows back to confirm what changed \
151 before any further write.",
152 )
153 })
154}
155
156fn execute(document: &str, variables: Value) -> Result<Value, Error> {
158 host::transport()?.call(
159 DB_EXECUTE.to_string(),
160 json!({ "query": document, "variables": variables }),
161 )
162}
163
164fn is_mutation(document: &str) -> bool {
179 let rest = skip_ignored(document);
180
181 let Some(rest) = rest.strip_prefix("mutation") else {
182 return false;
183 };
184
185 !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
188}
189
190fn skip_ignored(document: &str) -> &str {
196 let mut rest = document.trim_start_matches('\u{feff}');
197
198 loop {
199 rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ',');
200
201 let Some(comment) = rest.strip_prefix('#') else {
202 return rest;
203 };
204
205 rest = comment.find(['\n', '\r']).map_or("", |end| &comment[end..]);
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use serde_json::json;
213
214 use super::*;
215 use crate::testing;
216
217 #[test]
218 fn a_read_answers_with_the_type_that_was_asked_for() {
219 let _session = testing::install(|name, params| {
220 assert_eq!(name, DB_EXECUTE);
221 assert_eq!(params["query"], json!("query Q { rows { id } }"));
222 assert_eq!(params["variables"], json!({ "limit": 1 }));
223
224 Ok(json!({ "rows": [{ "id": "A" }] }))
225 });
226
227 let answer: Value = query("query Q { rows { id } }", json!({ "limit": 1 })).unwrap();
228
229 assert_eq!(answer, json!({ "rows": [{ "id": "A" }] }));
230 }
231
232 #[test]
233 fn a_mutation_sent_to_query_is_refused_before_anything_is_sent() {
234 let session = testing::install(|_name, _params| Ok(json!({})));
235
236 let error = query::<Value>("mutation M { insert_thing { id } }", json!({})).unwrap_err();
237
238 assert_eq!(error.code().as_str(), "QUERY_NOT_ALLOWED");
239 assert!(session.calls().is_empty());
240 }
241
242 #[test]
243 fn a_query_sent_to_mutate_is_refused_before_anything_is_sent() {
244 let session = testing::install(|_name, _params| Ok(json!({})));
245
246 let error = mutate::<Value>("query Q { thing { id } }", json!({})).unwrap_err();
247
248 assert_eq!(error.code().as_str(), "NOT_A_MUTATION");
249 assert!(session.calls().is_empty());
250 }
251
252 #[test]
253 fn an_empty_document_names_which_one_was_missing() {
254 let _session = testing::install(|_name, _params| Ok(json!({})));
255
256 assert_eq!(
257 query::<Value>(" ", json!({}))
258 .unwrap_err()
259 .code()
260 .as_str(),
261 "QUERY_REQUIRED"
262 );
263 assert_eq!(
264 mutate::<Value>("", json!({})).unwrap_err().code().as_str(),
265 "MUTATION_REQUIRED"
266 );
267 }
268
269 #[test]
270 fn a_failed_read_and_a_failed_write_carry_different_codes() {
271 let _session = testing::install(|_name, _params| Err(Error::failed("the host said no")));
272
273 assert_eq!(
274 query::<Value>("query Q { a }", json!({}))
275 .unwrap_err()
276 .code()
277 .as_str(),
278 "QUERY_EXECUTION_FAILED",
279 "a failed read changed nothing"
280 );
281 assert_eq!(
282 mutate::<Value>("mutation M { a }", json!({}))
283 .unwrap_err()
284 .code()
285 .as_str(),
286 "MUTATION_EXECUTION_FAILED",
287 "a failed write may have landed"
288 );
289 }
290
291 #[test]
292 fn an_unreadable_result_says_so_differently_for_a_read_and_a_write() {
293 let _session = testing::install(|_name, _params| Ok(json!({ "rows": "not a list" })));
294
295 #[derive(Debug, serde::Deserialize)]
296 struct Shape {
297 #[allow(dead_code)]
298 rows: Vec<Value>,
299 }
300
301 assert_eq!(
302 query::<Shape>("query Q { rows { a } }", json!({}))
303 .unwrap_err()
304 .code()
305 .as_str(),
306 "INVALID_QUERY_RESPONSE"
307 );
308 assert_eq!(
309 mutate::<Shape>("mutation M { rows { a } }", json!({}))
310 .unwrap_err()
311 .code()
312 .as_str(),
313 "MUTATION_RESULT_UNREADABLE"
314 );
315 }
316
317 #[test]
318 fn the_host_message_survives_into_the_failure() {
319 let _session = testing::install(|_name, _params| Err(Error::failed("permission denied")));
320
321 let error = query::<Value>("query Q { a }", json!({})).unwrap_err();
322
323 assert!(error.message().contains("permission denied"));
324 }
325
326 #[test]
329 fn an_operation_behind_ignored_tokens_is_still_a_mutation() {
330 assert!(is_mutation(
331 "# close the duplicate\nmutation M { update_lead { id } }"
332 ));
333 assert!(is_mutation("#no space\r\nmutation M { x }"));
334 assert!(is_mutation("# one\n # two\n\nmutation M { x }"));
335 assert!(is_mutation("\u{feff}mutation M { x }"));
336 assert!(is_mutation(",,\n mutation M { x }"));
337 }
338
339 #[test]
340 fn an_operation_behind_ignored_tokens_is_still_a_query() {
341 assert!(!is_mutation("# fetch the leads\nquery Q { leads { id } }"));
342 assert!(!is_mutation("# mutation M { x }\nquery Q { leads { id } }"));
343 assert!(!is_mutation("{ leads { id } }"));
344 assert!(!is_mutation(""));
345 assert!(!is_mutation("# a comment and nothing else"));
346 }
347
348 #[test]
350 fn a_name_that_merely_begins_mutation_is_not_the_keyword() {
351 assert!(!is_mutation("mutationLog { id }"));
352 assert!(!is_mutation("mutation_log { id }"));
353 assert!(is_mutation("mutation{ x }"));
354 assert!(is_mutation("mutation M($id: ID!) { x }"));
355 }
356
357 #[test]
358 fn a_commented_mutation_is_written_by_mutate() {
359 let session =
360 testing::install(|_name, _params| Ok(json!({ "update_lead": { "id": "L1" } })));
361
362 const DOCUMENT: &str = "# close the duplicate\nmutation M { update_lead { id } }";
363
364 let answer: Value =
365 mutate(DOCUMENT, json!({})).expect("a commented mutation is a mutation");
366
367 assert_eq!(answer, json!({ "update_lead": { "id": "L1" } }));
368 assert_eq!(session.calls().len(), 1);
369 }
370
371 #[test]
372 fn a_commented_mutation_is_refused_by_query() {
373 let session = testing::install(|_name, _params| Ok(json!(null)));
374
375 const DOCUMENT: &str = "# close the duplicate\nmutation M { update_lead { id } }";
376
377 let error = query::<Value>(DOCUMENT, json!({})).unwrap_err();
378
379 assert_eq!(error.code().as_str(), "QUERY_NOT_ALLOWED");
380 assert_eq!(session.calls().len(), 0, "nothing was sent");
381 }
382}