1use serde::de::DeserializeOwned;
69use serde_json::{json, Value};
70
71use crate::codes::Code;
72use crate::error::{Error, Fault};
73use crate::host;
74
75const SETTINGS_GET: &str = "action:settings/get";
77
78pub 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 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
154fn 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}