1use std::cell::RefCell;
76use std::rc::Rc;
77
78use serde_json::{json, Value};
79
80use crate::error::Error;
81use crate::host::{self, Transport, DONE};
82use crate::run::Context;
83
84#[derive(Clone, Debug)]
86pub struct Call {
87 pub name: String,
89 pub params: Value,
91}
92
93type BytesReply = Box<dyn Fn(String, Value) -> Result<Vec<u8>, Error>>;
95
96#[derive(Default)]
98struct Recorder {
99 calls: RefCell<Vec<Call>>,
100 done: RefCell<Option<Value>>,
101 request: RefCell<String>,
102 context: RefCell<Context>,
103 bytes: RefCell<Option<BytesReply>>,
104}
105
106struct Mock {
108 reply: Box<dyn Fn(String, Value) -> Result<Value, Error>>,
109 recorder: Rc<Recorder>,
110}
111
112impl Transport for Mock {
113 fn call(&self, name: String, params: Value) -> Result<Value, Error> {
120 if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
121 calls.push(Call {
122 name: name.clone(),
123 params: params.clone(),
124 });
125 }
126
127 let reply = match (self.reply)(name.clone(), params) {
128 Ok(data) => json!({ "ok": true, "data": data }),
129 Err(refusal) => json!({ "ok": false, "error": { "message": refusal.message() } }),
130 };
131
132 host::unwrap_reply(&name, reply)
133 }
134
135 fn call_bytes(&self, name: String, params: Value, into: &mut Vec<u8>) -> Result<usize, Error> {
139 if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
140 calls.push(Call {
141 name: name.clone(),
142 params: params.clone(),
143 });
144 }
145
146 let answer = match self.recorder.bytes.try_borrow() {
147 Ok(reply) => match reply.as_ref() {
148 Some(reply) => reply(name.clone(), params),
149 None => {
150 return Err(Error::failed(format!(
151 "{name} answers with bytes, and this session was given no way to."
152 ))
153 .hint("Answer it with Session::with_bytes."))
154 }
155 },
156 Err(_busy) => {
157 return Err(Error::failed(format!(
158 "{name} was called from inside the session's own reply."
159 )))
160 }
161 };
162
163 match answer {
164 Ok(bytes) => {
165 into.extend_from_slice(&bytes);
166 Ok(bytes.len())
167 }
168 Err(refusal) => host::unwrap_reply(
169 &name,
170 json!({ "ok": false, "error": { "message": refusal.message() } }),
171 )
172 .map(|_never| 0),
173 }
174 }
175
176 fn cast(&self, name: String, params: Value) {
177 if name == DONE {
178 if let Ok(mut done) = self.recorder.done.try_borrow_mut() {
179 *done = Some(params);
180 }
181
182 return;
183 }
184
185 if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
186 calls.push(Call { name, params });
187 }
188 }
189
190 fn context(&self) -> Option<String> {
191 let request = self.recorder.request.try_borrow().ok()?.clone();
192 let context = self.recorder.context.try_borrow().ok()?.clone();
193
194 Some(
195 json!({
196 "context": context,
197 "data": request,
198 "headers": {},
199 })
200 .to_string(),
201 )
202 }
203}
204
205pub struct Session {
211 recorder: Rc<Recorder>,
212}
213
214impl Session {
215 pub fn calls(&self) -> Vec<Call> {
219 self.recorder
220 .calls
221 .try_borrow()
222 .map(|calls| calls.clone())
223 .unwrap_or_default()
224 }
225
226 pub fn done(&self) -> Option<Value> {
228 self.recorder
229 .done
230 .try_borrow()
231 .ok()
232 .and_then(|done| done.clone())
233 }
234
235 pub fn with_request(self, data: Value) -> Session {
237 if let Ok(mut request) = self.recorder.request.try_borrow_mut() {
238 *request = data.to_string();
239 }
240
241 self
242 }
243
244 pub fn with_bytes<F>(self, reply: F) -> Session
252 where
253 F: Fn(String, Value) -> Result<Vec<u8>, Error> + 'static,
254 {
255 if let Ok(mut slot) = self.recorder.bytes.try_borrow_mut() {
256 *slot = Some(Box::new(reply));
257 }
258
259 self
260 }
261
262 pub fn with_context(self, context: Context) -> Session {
264 if let Ok(mut slot) = self.recorder.context.try_borrow_mut() {
265 *slot = context;
266 }
267
268 self
269 }
270}
271
272impl Drop for Session {
273 fn drop(&mut self) {
274 host::set(None);
275 }
276}
277
278pub fn install<F>(reply: F) -> Session
283where
284 F: Fn(String, Value) -> Result<Value, Error> + 'static,
285{
286 let recorder = Rc::new(Recorder {
287 request: RefCell::new("null".to_string()),
288 ..Recorder::default()
289 });
290
291 host::set(Some(Rc::new(Mock {
292 reply: Box::new(reply),
293 recorder: Rc::clone(&recorder),
294 })));
295
296 Session { recorder }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302 use crate::run::Request;
303
304 #[test]
305 fn a_session_records_what_it_was_asked() {
306 let session = install(|_name, _params| Ok(json!({ "rows": [] })));
307
308 let _: Value = crate::graphql::query("query Q { rows { a } }", json!({ "x": 1 })).unwrap();
309
310 let calls = session.calls();
311
312 assert_eq!(calls.len(), 1);
313 assert_eq!(calls[0].name, "action:db/execute");
314 assert_eq!(calls[0].params["variables"], json!({ "x": 1 }));
315 }
316
317 #[test]
318 fn a_refusing_host_reaches_the_caller_as_an_error() {
319 let _session = install(|_name, _params| Err(Error::denied("nope")));
320
321 let error = crate::graphql::query::<Value>("query Q { a }", json!({})).unwrap_err();
322
323 assert!(error.message().contains("nope"));
324 }
325
326 #[test]
327 fn the_slot_is_empty_once_the_session_is_dropped() {
328 {
329 let _session = install(|_name, _params| Ok(json!(null)));
330 assert!(host::transport().is_ok());
331 }
332
333 assert!(host::transport().is_err());
334 }
335
336 #[test]
337 fn run_reports_a_success_envelope() {
338 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
339
340 crate::run(|request: Request<Value>| Ok(json!({ "seen": request.data })));
341
342 assert_eq!(
343 session.done().unwrap(),
344 json!({ "data": { "seen": { "a": 1 } }, "errors": [], "ok": true })
345 );
346 }
347
348 #[test]
349 fn run_reports_a_failure_envelope_and_still_says_ok() {
350 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
351
352 crate::run(|_request: Request<Value>| {
353 Err::<Value, Error>(Error::invalid("no id").hint("Send an id."))
354 });
355
356 let done = session.done().unwrap();
357
358 assert_eq!(done["ok"], json!(true));
359 assert_eq!(
360 done["data"]["error"]["extensions"]["code"],
361 json!("INVALID_TOOL_INPUT")
362 );
363 assert_eq!(
364 done["data"]["error"]["extensions"]["retryable"],
365 json!(false)
366 );
367 assert_eq!(
368 done["data"]["error"]["extensions"]["hint"],
369 json!("Send an id.")
370 );
371 }
372
373 #[test]
374 fn run_reports_exactly_once_even_when_the_handler_panics() {
375 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
376
377 crate::run(|_request: Request<Value>| -> Result<Value, Error> {
378 panic!("the action fell over")
379 });
380
381 let done = session.done().unwrap();
382
383 assert!(done["data"]["error"]["message"]
384 .as_str()
385 .unwrap()
386 .contains("the action fell over"));
387 }
388
389 #[test]
390 fn a_payload_that_does_not_match_never_reaches_the_handler() {
391 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
392
393 #[derive(Debug, serde::Deserialize)]
394 struct Needs {
395 #[allow(dead_code)]
396 required: String,
397 }
398
399 crate::run(|_request: Request<Needs>| -> Result<Value, Error> {
400 panic!("the handler must not run")
401 });
402
403 assert_eq!(
404 session.done().unwrap()["data"]["error"]["extensions"]["code"],
405 json!("INVALID_TOOL_INPUT")
406 );
407 }
408
409 #[test]
410 fn the_context_the_session_was_given_reaches_the_handler() {
411 let mut context = Context::default();
412 context.logic.execution_id = "EXEC9".to_string();
413 context.tenant.name = "acme".to_string();
414
415 let session = install(|_name, _params| Ok(json!(null)))
416 .with_request(json!({}))
417 .with_context(context);
418
419 crate::run(|request: Request<Value>| {
420 Ok(json!({
421 "execution": request.context.logic.execution_id,
422 "tenant": request.context.tenant.name,
423 }))
424 });
425
426 assert_eq!(
427 session.done().unwrap()["data"],
428 json!({ "execution": "EXEC9", "tenant": "acme" })
429 );
430 }
431}