Skip to main content

simpleplatform_sdk/
graphql.rs

1//! Reading and writing tenant data.
2//!
3//! Two functions, both of which answer with the type you asked for:
4//!
5//! ```
6//! # use simpleplatform_sdk::prelude::*;
7//! # use simpleplatform_sdk::testing;
8//! #[derive(Deserialize)]
9//! struct Invoice {
10//!     amount: f64,
11//! }
12//!
13//! #[derive(Deserialize)]
14//! struct Open {
15//!     invoices: Vec<Invoice>,
16//! }
17//!
18//! const OPEN: &str = r#"
19//!   query Open($id: ID!) {
20//!     invoices: crm__invoice(where: {customer_id: {_eq: $id}}, limit: 100) { amount }
21//!   }"#;
22//!
23//! # let _session = testing::install(|_name, _params| {
24//! #     Ok(json!({ "invoices": [{ "amount": 12.5 }, { "amount": 7.5 }] }))
25//! # });
26//! let open: Open = simple::graphql::query(OPEN, json!({ "id": "CUS1" }))?;
27//! let total: f64 = open.invoices.iter().map(|invoice| invoice.amount).sum();
28//!
29//! assert_eq!(total, 20.0);
30//! # Ok::<(), Error>(())
31//! ```
32//!
33//! # Why the read and the write are separate functions
34//!
35//! A read that fails changed nothing; a write that fails *may have landed*, and
36//! that single bit decides whether the call may be repeated. The party that knows
37//! which of the two happened is the function that made the call, so each reports
38//! its own outcome: [`query`] reports `QUERY_EXECUTION_FAILED` and [`mutate`]
39//! reports `MUTATION_EXECUTION_FAILED`. An action author gets the right one by
40//! calling the right function.
41//!
42//! The same split runs through the rest: a read whose response cannot be decoded
43//! is `INVALID_QUERY_RESPONSE`, and a write whose result cannot be decoded is
44//! `MUTATION_RESULT_UNREADABLE` — a write that ran and whose effect was never
45//! established, which is never retried and always reported.
46//!
47//! # One function per intent
48//!
49//! There is no combined `execute`. Which function you call *is* the declaration
50//! of intent, so what a failure means is settled at the call site. The document
51//! check below stays what it is — a guard against an obvious mix-up, a mutation
52//! handed to [`query`] or a query handed to [`mutate`] — and never the thing that
53//! decides whether a write may be repeated.
54
55use 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
62/// Read tenant data.
63///
64/// Refuses a document that is empty or that begins `mutation`, before anything
65/// is sent.
66///
67/// ```
68/// # use simpleplatform_sdk::prelude::*;
69/// # use simpleplatform_sdk::testing;
70/// # let _session = testing::install(|_name, _params| Ok(json!({ "rows": [] })));
71/// #[derive(Deserialize)]
72/// struct Answer {
73///     rows: Vec<Value>,
74/// }
75///
76/// let answer: Answer = simple::graphql::query("query Q { rows: app__thing { id } }", json!({}))?;
77///
78/// assert!(answer.rows.is_empty());
79/// # Ok::<(), Error>(())
80/// ```
81pub 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
114/// Write tenant data.
115///
116/// Refuses a document that is empty or that does not begin `mutation`, before
117/// anything is sent.
118pub 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
156/// One document, one round trip, one unwrapped result.
157fn 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
164/// Whether a document asks for a write.
165///
166/// This is a guard against an obvious mix-up, and never the thing that decides
167/// what a failure means. That decision is made by which function was called.
168///
169/// The operation is read past anything GraphQL ignores, so a document is
170/// classified by its operation whatever precedes it. An author who writes
171///
172/// ```graphql
173/// # close the duplicate
174/// mutation M { update_lead { id } }
175/// ```
176///
177/// has written a mutation, and [`mutate`] sends it.
178fn 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    // `mutationFoo` is not the mutation keyword. A name carries on with a name
186    // character; anything else — `{`, `(`, `@`, a space, or the end — ends it.
187    !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
188}
189
190/// Drops what GraphQL ignores before a document's first real token.
191///
192/// Whitespace, line terminators, commas, a byte-order mark, and `#` comments to
193/// the end of their line. Commas are ignored tokens in GraphQL exactly as
194/// whitespace is, which is why they are here rather than being a typo.
195fn 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        // A comment runs to the line terminator, and the last line may have none.
206        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    // Whatever GraphQL ignores comes off first, so the operation is what
327    // classifies the document.
328    #[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    // `mutation` is a keyword, not a prefix.
349    #[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}