use std::cell::RefCell;
use std::rc::Rc;
use serde_json::{json, Value};
use crate::error::Error;
use crate::host::{self, Transport, DONE};
use crate::run::Context;
#[derive(Clone, Debug)]
pub struct Call {
pub name: String,
pub params: Value,
}
type BytesReply = Box<dyn Fn(String, Value) -> Result<Vec<u8>, Error>>;
#[derive(Default)]
struct Recorder {
calls: RefCell<Vec<Call>>,
done: RefCell<Option<Value>>,
request: RefCell<String>,
context: RefCell<Context>,
bytes: RefCell<Option<BytesReply>>,
}
struct Mock {
reply: Box<dyn Fn(String, Value) -> Result<Value, Error>>,
recorder: Rc<Recorder>,
}
impl Transport for Mock {
fn call(&self, name: String, params: Value) -> Result<Value, Error> {
if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
calls.push(Call {
name: name.clone(),
params: params.clone(),
});
}
let reply = match (self.reply)(name.clone(), params) {
Ok(data) => json!({ "ok": true, "data": data }),
Err(refusal) => json!({ "ok": false, "error": { "message": refusal.message() } }),
};
host::unwrap_reply(&name, reply)
}
fn call_bytes(&self, name: String, params: Value, into: &mut Vec<u8>) -> Result<usize, Error> {
if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
calls.push(Call {
name: name.clone(),
params: params.clone(),
});
}
let answer = match self.recorder.bytes.try_borrow() {
Ok(reply) => match reply.as_ref() {
Some(reply) => reply(name.clone(), params),
None => {
return Err(Error::failed(format!(
"{name} answers with bytes, and this session was given no way to."
))
.hint("Answer it with Session::with_bytes."))
}
},
Err(_busy) => {
return Err(Error::failed(format!(
"{name} was called from inside the session's own reply."
)))
}
};
match answer {
Ok(bytes) => {
into.extend_from_slice(&bytes);
Ok(bytes.len())
}
Err(refusal) => host::unwrap_reply(
&name,
json!({ "ok": false, "error": { "message": refusal.message() } }),
)
.map(|_never| 0),
}
}
fn cast(&self, name: String, params: Value) {
if name == DONE {
if let Ok(mut done) = self.recorder.done.try_borrow_mut() {
*done = Some(params);
}
return;
}
if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
calls.push(Call { name, params });
}
}
fn context(&self) -> Option<String> {
let request = self.recorder.request.try_borrow().ok()?.clone();
let context = self.recorder.context.try_borrow().ok()?.clone();
Some(
json!({
"context": context,
"data": request,
"headers": {},
})
.to_string(),
)
}
}
pub struct Session {
recorder: Rc<Recorder>,
}
impl Session {
pub fn calls(&self) -> Vec<Call> {
self.recorder
.calls
.try_borrow()
.map(|calls| calls.clone())
.unwrap_or_default()
}
pub fn done(&self) -> Option<Value> {
self.recorder
.done
.try_borrow()
.ok()
.and_then(|done| done.clone())
}
pub fn with_request(self, data: Value) -> Session {
if let Ok(mut request) = self.recorder.request.try_borrow_mut() {
*request = data.to_string();
}
self
}
pub fn with_bytes<F>(self, reply: F) -> Session
where
F: Fn(String, Value) -> Result<Vec<u8>, Error> + 'static,
{
if let Ok(mut slot) = self.recorder.bytes.try_borrow_mut() {
*slot = Some(Box::new(reply));
}
self
}
pub fn with_context(self, context: Context) -> Session {
if let Ok(mut slot) = self.recorder.context.try_borrow_mut() {
*slot = context;
}
self
}
}
impl Drop for Session {
fn drop(&mut self) {
host::set(None);
}
}
pub fn install<F>(reply: F) -> Session
where
F: Fn(String, Value) -> Result<Value, Error> + 'static,
{
let recorder = Rc::new(Recorder {
request: RefCell::new("null".to_string()),
..Recorder::default()
});
host::set(Some(Rc::new(Mock {
reply: Box::new(reply),
recorder: Rc::clone(&recorder),
})));
Session { recorder }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::run::Request;
#[test]
fn a_session_records_what_it_was_asked() {
let session = install(|_name, _params| Ok(json!({ "rows": [] })));
let _: Value = crate::graphql::query("query Q { rows { a } }", json!({ "x": 1 })).unwrap();
let calls = session.calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].name, "action:db/execute");
assert_eq!(calls[0].params["variables"], json!({ "x": 1 }));
}
#[test]
fn a_refusing_host_reaches_the_caller_as_an_error() {
let _session = install(|_name, _params| Err(Error::denied("nope")));
let error = crate::graphql::query::<Value>("query Q { a }", json!({})).unwrap_err();
assert!(error.message().contains("nope"));
}
#[test]
fn the_slot_is_empty_once_the_session_is_dropped() {
{
let _session = install(|_name, _params| Ok(json!(null)));
assert!(host::transport().is_ok());
}
assert!(host::transport().is_err());
}
#[test]
fn run_reports_a_success_envelope() {
let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
crate::run(|request: Request<Value>| Ok(json!({ "seen": request.data })));
assert_eq!(
session.done().unwrap(),
json!({ "data": { "seen": { "a": 1 } }, "errors": [], "ok": true })
);
}
#[test]
fn run_reports_a_failure_envelope_and_still_says_ok() {
let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
crate::run(|_request: Request<Value>| {
Err::<Value, Error>(Error::invalid("no id").hint("Send an id."))
});
let done = session.done().unwrap();
assert_eq!(done["ok"], json!(true));
assert_eq!(
done["data"]["error"]["extensions"]["code"],
json!("INVALID_TOOL_INPUT")
);
assert_eq!(
done["data"]["error"]["extensions"]["retryable"],
json!(false)
);
assert_eq!(
done["data"]["error"]["extensions"]["hint"],
json!("Send an id.")
);
}
#[test]
fn run_reports_exactly_once_even_when_the_handler_panics() {
let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
crate::run(|_request: Request<Value>| -> Result<Value, Error> {
panic!("the action fell over")
});
let done = session.done().unwrap();
assert!(done["data"]["error"]["message"]
.as_str()
.unwrap()
.contains("the action fell over"));
}
#[test]
fn a_payload_that_does_not_match_never_reaches_the_handler() {
let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
#[derive(Debug, serde::Deserialize)]
struct Needs {
#[allow(dead_code)]
required: String,
}
crate::run(|_request: Request<Needs>| -> Result<Value, Error> {
panic!("the handler must not run")
});
assert_eq!(
session.done().unwrap()["data"]["error"]["extensions"]["code"],
json!("INVALID_TOOL_INPUT")
);
}
#[test]
fn the_context_the_session_was_given_reaches_the_handler() {
let mut context = Context::default();
context.logic.execution_id = "EXEC9".to_string();
context.tenant.name = "acme".to_string();
let session = install(|_name, _params| Ok(json!(null)))
.with_request(json!({}))
.with_context(context);
crate::run(|request: Request<Value>| {
Ok(json!({
"execution": request.context.logic.execution_id,
"tenant": request.context.tenant.name,
}))
});
assert_eq!(
session.done().unwrap()["data"],
json!({ "execution": "EXEC9", "tenant": "acme" })
);
}
}