Skip to main content

simpleplatform_sdk/
settings.rs

1//! Reading the settings an application was configured with.
2//!
3//! One function, [`get`], and it answers with the type you asked for:
4//!
5//! ```
6//! # use simpleplatform_sdk::prelude::*;
7//! # use simpleplatform_sdk::testing;
8//! #[derive(Deserialize)]
9//! struct Billing {
10//!     region: String,
11//!     retries: u8,
12//! }
13//!
14//! # let _session = testing::install(|_name, _params| {
15//! #     Ok(json!({ "region": "eu-west", "retries": 3 }))
16//! # });
17//! let billing: Billing = simple::settings::get("billing", &["region", "retries"])?;
18//!
19//! assert_eq!(billing.region, "eu-west");
20//! assert_eq!(billing.retries, 3);
21//! # Ok::<(), Error>(())
22//! ```
23//!
24//! # Why the answer is your own type
25//!
26//! A settings read answers with a map of setting name to value, and a `Value`
27//! holding that map is a faithful description of the wire. It is also the shape
28//! an action then has to walk by hand: index a key, ask whether it is a string,
29//! decide what to do when it is not — at every use site, in every action, for a
30//! set of keys the action already knew when it wrote the call.
31//!
32//! Naming a type moves all of that into one line. The keys asked for and the
33//! fields read back are declared together, `retries` arrives as a `u8` because
34//! that is what it was declared as, and a value that does not fit the
35//! declaration is reported once, at the call, rather than at the first use.
36//! This is the same bargain [`crate::graphql`] makes for a query result, and it
37//! is made the same way — `serde`, and one type parameter — so an action author
38//! learns it once.
39//!
40//! # Asking for the map itself
41//!
42//! Some settings are chosen at runtime, and then the keys are not known when the
43//! call is written. `Value` is a type like any other, so asking for it hands back
44//! the map exactly as it arrived:
45//!
46//! ```
47//! # use simpleplatform_sdk::prelude::*;
48//! # use simpleplatform_sdk::testing;
49//! # let _session = testing::install(|_name, _params| Ok(json!({ "region": "eu-west" })));
50//! let chosen = "region";
51//! let settings: Value = simple::settings::get("billing", &[chosen])?;
52//!
53//! assert_eq!(settings[chosen], json!("eu-west"));
54//! # Ok::<(), Error>(())
55//! ```
56//!
57//! Both readings are the same call and the same wire. Which one you get is
58//! decided by the type on the left, and nothing else.
59//!
60//! # What is settled before anything is sent
61//!
62//! A read names an application and at least one key, so [`get`] establishes both
63//! at the call and reports a call that names neither without a round trip —
64//! exactly as [`crate::graphql::query`] establishes that it was handed a
65//! document. The refusal carries `INVALID_TOOL_INPUT`, and the host is left
66//! alone.
67
68use serde::de::DeserializeOwned;
69use serde_json::{json, Value};
70
71use crate::codes::Code;
72use crate::error::{Error, Fault};
73use crate::host;
74
75/// The host action that reads application settings.
76const SETTINGS_GET: &str = "action:settings/get";
77
78/// Read the settings an application was configured with.
79///
80/// `app_id` names the application the settings belong to and `keys` names the
81/// settings to read. The answer is the map of setting name to value, read into
82/// `T` — your own type, or [`Value`] for the map as it arrived.
83///
84/// An application id that is only space, and an empty key list, are reported
85/// before anything is sent.
86///
87/// ```
88/// # use simpleplatform_sdk::prelude::*;
89/// # use simpleplatform_sdk::testing;
90/// # let _session = testing::install(|_name, _params| Ok(json!({ "region": "eu-west" })));
91/// #[derive(Deserialize)]
92/// struct Billing {
93///     region: String,
94/// }
95///
96/// let billing: Billing = simple::settings::get("billing", &["region"])?;
97///
98/// assert_eq!(billing.region, "eu-west");
99/// # Ok::<(), Error>(())
100/// ```
101pub fn get<T: DeserializeOwned>(app_id: &str, keys: &[&str]) -> Result<T, Error> {
102    let app_id = app_id.trim();
103
104    if app_id.is_empty() {
105        return Err(
106            Error::invalid("An application id is required to read settings.")
107                .hint("Pass the id of the application the settings belong to."),
108        );
109    }
110
111    if keys.is_empty() {
112        return Err(Error::invalid("At least one setting key is required.")
113            .hint("Pass the names of the settings to read. Nothing was sent."));
114    }
115
116    let settings = host::transport()?
117        .call(
118            SETTINGS_GET.to_string(),
119            json!({ "app_id": app_id, "keys": keys }),
120        )
121        .map_err(|cause| {
122            Error::Host(Fault::new(Code::unspecified(), cause.message())).hint(
123                "Confirm the application id and the key names, then read again. \
124                 A settings read writes nothing.",
125            )
126        })?;
127
128    // A settings read answers with a map of setting name to value, so anything
129    // else is reported here rather than reaching `T` as a decoding failure that
130    // would describe the field instead of the answer.
131    if !settings.is_object() {
132        return Err(Error::Json(Fault::new(
133            Code::unspecified(),
134            format!(
135                "Settings arrive as a map of setting name to value, and this read answered with {}.",
136                shape_of(&settings)
137            ),
138        ))
139        .hint("Report this answer. A settings read writes nothing."));
140    }
141
142    serde_json::from_value(settings).map_err(|cause| {
143        Error::Json(Fault::new(
144            Code::unspecified(),
145            format!("The settings read answered with a map this action could not read: {cause}"),
146        ))
147        .hint(
148            "Match the fields of the type you asked for to the keys you asked for, \
149             or read the answer as Value. A settings read writes nothing.",
150        )
151    })
152}
153
154/// What arrived, in the words a message uses for it.
155fn shape_of(value: &Value) -> &'static str {
156    match value {
157        Value::Null => "nothing",
158        Value::Bool(_) => "a true or false value",
159        Value::Number(_) => "a number",
160        Value::String(_) => "a string",
161        Value::Array(_) => "a list",
162        Value::Object(_) => "a map",
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use serde::Deserialize;
169    use serde_json::json;
170
171    use super::*;
172    use crate::testing;
173
174    #[derive(Debug, Deserialize)]
175    struct Billing {
176        region: String,
177        retries: u8,
178    }
179
180    #[test]
181    fn a_read_answers_with_the_type_that_was_asked_for() {
182        let _session = testing::install(|name, params| {
183            assert_eq!(name, SETTINGS_GET);
184            assert_eq!(params["app_id"], json!("billing"));
185            assert_eq!(params["keys"], json!(["region", "retries"]));
186
187            Ok(json!({ "region": "eu-west", "retries": 3 }))
188        });
189
190        let billing: Billing = get("billing", &["region", "retries"]).unwrap();
191
192        assert_eq!(billing.region, "eu-west");
193        assert_eq!(billing.retries, 3);
194    }
195
196    #[test]
197    fn the_map_itself_is_had_by_asking_for_value() {
198        let _session = testing::install(|_name, _params| Ok(json!({ "region": "eu-west" })));
199
200        let settings: Value = get("billing", &["region"]).unwrap();
201
202        assert_eq!(settings, json!({ "region": "eu-west" }));
203    }
204
205    #[test]
206    fn one_call_carries_the_application_and_every_key_in_the_order_given() {
207        let session = testing::install(|_name, _params| Ok(json!({})));
208
209        let _: Value = get("billing", &["retries", "region", "currency"]).unwrap();
210
211        let calls = session.calls();
212
213        assert_eq!(calls.len(), 1, "one read is one round trip");
214        assert_eq!(calls[0].name, "action:settings/get");
215        assert_eq!(
216            calls[0].params,
217            json!({ "app_id": "billing", "keys": ["retries", "region", "currency"] })
218        );
219    }
220
221    #[test]
222    fn an_empty_key_list_is_reported_before_anything_is_sent() {
223        let session = testing::install(|_name, _params| Ok(json!({})));
224
225        let error = get::<Value>("billing", &[]).unwrap_err();
226
227        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
228        assert!(session.calls().is_empty(), "nothing was sent");
229    }
230
231    #[test]
232    fn an_application_id_that_names_nothing_is_reported_before_anything_is_sent() {
233        let session = testing::install(|_name, _params| Ok(json!({})));
234
235        assert_eq!(
236            get::<Value>("", &["region"]).unwrap_err().code().as_str(),
237            "INVALID_TOOL_INPUT"
238        );
239        assert_eq!(
240            get::<Value>("   ", &["region"])
241                .unwrap_err()
242                .code()
243                .as_str(),
244            "INVALID_TOOL_INPUT"
245        );
246        assert!(session.calls().is_empty(), "nothing was sent");
247    }
248
249    #[test]
250    fn both_refusals_say_which_one_was_missing() {
251        let _session = testing::install(|_name, _params| Ok(json!({})));
252
253        assert!(get::<Value>(" ", &["region"])
254            .unwrap_err()
255            .message()
256            .contains("application id"));
257        assert!(get::<Value>("billing", &[])
258            .unwrap_err()
259            .message()
260            .contains("setting key"));
261    }
262
263    #[test]
264    fn the_application_id_is_sent_without_the_space_around_it() {
265        let session = testing::install(|_name, _params| Ok(json!({})));
266
267        let _: Value = get("  billing\n", &["region"]).unwrap();
268
269        assert_eq!(session.calls()[0].params["app_id"], json!("billing"));
270    }
271
272    #[test]
273    fn a_host_refusal_keeps_its_own_message() {
274        let _session = testing::install(|_name, _params| Err(Error::failed("permission denied")));
275
276        let error = get::<Value>("billing", &["region"]).unwrap_err();
277
278        assert!(error.message().contains("permission denied"));
279        assert!(matches!(error, Error::Host(_)));
280    }
281
282    #[test]
283    fn an_answer_that_is_not_a_map_says_what_arrived() {
284        let _session = testing::install(|_name, _params| Ok(json!(["region"])));
285
286        let error = get::<Value>("billing", &["region"]).unwrap_err();
287
288        assert_eq!(error.code().as_str(), "ACTION_FAILED");
289        assert!(error.message().contains("a list"));
290    }
291
292    #[test]
293    fn an_answer_whose_values_do_not_fit_the_type_is_reported_at_the_call() {
294        let _session =
295            testing::install(|_name, _params| Ok(json!({ "region": "eu-west", "retries": "3" })));
296
297        let error = get::<Billing>("billing", &["region", "retries"]).unwrap_err();
298
299        assert_eq!(error.code().as_str(), "ACTION_FAILED");
300        assert!(matches!(error, Error::Json(_)));
301    }
302
303    #[test]
304    fn a_key_the_type_declares_and_the_answer_omits_is_reported_at_the_call() {
305        let _session = testing::install(|_name, _params| Ok(json!({ "region": "eu-west" })));
306
307        let error = get::<Billing>("billing", &["region", "retries"]).unwrap_err();
308
309        assert!(error.message().contains("retries"));
310    }
311
312    #[test]
313    fn every_shape_the_wire_carries_has_a_word() {
314        assert_eq!(shape_of(&json!(null)), "nothing");
315        assert_eq!(shape_of(&json!(true)), "a true or false value");
316        assert_eq!(shape_of(&json!(3)), "a number");
317        assert_eq!(shape_of(&json!("region")), "a string");
318        assert_eq!(shape_of(&json!([])), "a list");
319        assert_eq!(shape_of(&json!({})), "a map");
320    }
321
322    #[test]
323    fn a_read_with_no_host_installed_is_an_error_and_not_a_panic() {
324        let error = get::<Value>("billing", &["region"]).unwrap_err();
325
326        assert!(error.message().contains("No host is installed"));
327    }
328}