use crate::global::Global;
use serde_json::Value;
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReadMode {
First,
All,
}
#[derive(Debug, Clone, PartialEq)]
pub enum JsonOutcome {
Value(serde_json::Value),
Nothing,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JsonCallError {
InvalidArgs(String),
Business(String),
Transport(String),
}
pub type JsonResult = Result<JsonOutcome, JsonCallError>;
#[async_trait::async_trait]
pub trait JsonInvoker: Send + Sync {
fn service_name(&self) -> &'static str;
async fn invoke_json(
&self,
method: &str,
args: serde_json::Value,
read: ReadMode,
) -> Option<Result<JsonOutcome, JsonCallError>>;
}
pub const JSON_CALL_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug)]
pub enum JsonCallEvent {
Event(Value),
Failed(String),
}
pub struct JsonCallStream {
receiver: async_channel::Receiver<Value>,
answered: bool,
}
impl JsonCallStream {
#[must_use]
pub fn channel() -> (Self, async_channel::Sender<Value>) {
let (sender, receiver) = async_channel::unbounded();
(
Self {
receiver,
answered: false,
},
sender,
)
}
pub async fn next(&mut self) -> Option<JsonCallEvent> {
if self.answered {
return self.receiver.recv().await.ok().map(JsonCallEvent::Event);
}
match crate::rt::timeout(JSON_CALL_TIMEOUT, self.receiver.recv()).await {
Ok(Ok(value)) => {
self.answered = true;
Some(JsonCallEvent::Event(value))
}
Ok(Err(_)) => None,
Err(_) => Some(JsonCallEvent::Failed(format!(
"the JSON host did not answer within {}s",
JSON_CALL_TIMEOUT.as_secs()
))),
}
}
}
#[async_trait::async_trait]
pub trait JsonDispatcher: Send + Sync + 'static {
async fn dispatch_json(
&self,
cid: [u8; 16],
service: &str,
method: &str,
args: Value,
) -> Result<JsonCallStream, String>;
}
static DISPATCHER: Global<Arc<dyn JsonDispatcher>> = Global::new();
pub fn set_json_dispatcher(dispatcher: Arc<dyn JsonDispatcher>) {
DISPATCHER.get_or_init(|| dispatcher);
}
pub fn json_dispatcher() -> Option<&'static Arc<dyn JsonDispatcher>> {
DISPATCHER.get()
}
pub async fn dispatch_json(
cid: [u8; 16],
service: &str,
method: &str,
args: Value,
) -> Result<JsonCallStream, String> {
match DISPATCHER.get() {
Some(dispatcher) => dispatcher.dispatch_json(cid, service, method, args).await,
None => Err("no JSON dispatcher registered — call \
ice_rpc::json::set_json_dispatcher() first"
.to_string()),
}
}
pub async fn read_json<T, E>(
stream: crate::Observable<T, E>,
read: ReadMode,
) -> Result<JsonOutcome, JsonCallError>
where
T: serde::Serialize,
E: std::fmt::Display,
{
match read {
ReadMode::First => match stream.first_value().await {
Ok(value) => serde_json::to_value(&value)
.map(JsonOutcome::Value)
.map_err(|e| {
JsonCallError::Transport(format!("failed to serialize the response: {e}"))
}),
Err(crate::ObservableError::Business(e)) => Err(JsonCallError::Business(e.to_string())),
Err(crate::ObservableError::Technical(e)) => {
Err(JsonCallError::Transport(e.to_string()))
}
Err(crate::ObservableError::Empty) => Ok(JsonOutcome::Nothing),
},
ReadMode::All => match stream.collect().await {
Ok(values) => values
.iter()
.map(serde_json::to_value)
.collect::<Result<Vec<_>, _>>()
.map(|values| JsonOutcome::Value(serde_json::Value::Array(values)))
.map_err(|e| JsonCallError::Transport(format!("failed to serialize a value: {e}"))),
Err(crate::ObservableError::Business(e)) => Err(JsonCallError::Business(e.to_string())),
Err(crate::ObservableError::Technical(e)) => {
Err(JsonCallError::Transport(e.to_string()))
}
Err(crate::ObservableError::Empty) => {
Ok(JsonOutcome::Value(serde_json::Value::Array(Vec::new())))
}
},
}
}
#[cfg(test)]
mod tests {
use super::*;
struct EchoHost;
#[async_trait::async_trait]
impl JsonDispatcher for EchoHost {
async fn dispatch_json(
&self,
_cid: [u8; 16],
service: &str,
method: &str,
args: Value,
) -> Result<JsonCallStream, String> {
let (stream, sender) = JsonCallStream::channel();
let _ = sender.try_send(serde_json::json!({
"service": service,
"method": method,
"args": args,
}));
drop(sender);
Ok(stream)
}
}
#[test]
fn a_registered_host_receives_the_call_and_its_events_are_read() {
set_json_dispatcher(Arc::new(EchoHost));
let events = crate::rt::test_block_on(async {
let mut stream = dispatch_json(
[7u8; 16],
"DatabaseService",
"get_user_age",
serde_json::json!({ "name": "Alice" }),
)
.await
.expect("a registered host accepts the call");
let mut collected = Vec::new();
while let Some(event) = stream.next().await {
match event {
JsonCallEvent::Event(value) => collected.push(value),
JsonCallEvent::Failed(message) => panic!("unexpected failure: {message}"),
}
}
collected
});
assert_eq!(
events,
vec![serde_json::json!({
"service": "DatabaseService",
"method": "get_user_age",
"args": { "name": "Alice" },
})]
);
let registered = json_dispatcher().expect("a registered host stays reachable");
assert_eq!(
Arc::strong_count(registered),
1,
"the framework holds the single reference to the host"
);
set_json_dispatcher(Arc::new(EchoHost));
assert_eq!(
Arc::strong_count(json_dispatcher().expect("the first host is still there")),
1,
"the second host is dropped, the first one is kept"
);
}
#[test]
fn a_stream_whose_sender_is_dropped_ends_without_an_event() {
let (mut stream, sender) = JsonCallStream::channel();
drop(sender);
assert!(
crate::rt::test_block_on(stream.next()).is_none(),
"a dropped sender ends the stream"
);
}
fn values(
events: impl IntoIterator<Item = crate::Event<i32, String>>,
) -> crate::Observable<i32, String> {
crate::Observable::from_events(events)
}
#[test]
fn first_mode_reads_only_the_first_value() {
let stream = values([
crate::Event::Next(1),
crate::Event::Next(2),
crate::Event::Complete,
]);
let outcome = crate::rt::test_block_on(read_json(stream, ReadMode::First)).expect("ok");
assert_eq!(outcome, JsonOutcome::Value(serde_json::json!(1)));
}
#[test]
fn all_mode_collects_every_value_in_order() {
let stream = values([
crate::Event::Next(1),
crate::Event::Next(2),
crate::Event::Next(3),
crate::Event::Complete,
]);
let outcome = crate::rt::test_block_on(read_json(stream, ReadMode::All)).expect("ok");
assert_eq!(outcome, JsonOutcome::Value(serde_json::json!([1, 2, 3])));
}
#[test]
fn a_completion_without_any_value_is_not_a_failure() {
let nothing =
crate::rt::test_block_on(read_json(values([crate::Event::Complete]), ReadMode::First))
.expect("an empty completion is legitimate");
assert_eq!(nothing, JsonOutcome::Nothing);
let all =
crate::rt::test_block_on(read_json(values([crate::Event::Complete]), ReadMode::All))
.expect("an empty stream is legitimate");
assert_eq!(all, JsonOutcome::Value(serde_json::json!([])));
}
#[test]
fn a_business_error_maps_to_a_business_failure_in_both_modes() {
let error = |mode| {
let stream = values([crate::Event::Error(crate::ObservableError::Business(
String::from("denied"),
))]);
crate::rt::test_block_on(read_json(stream, mode))
};
assert_eq!(
error(ReadMode::First),
Err(JsonCallError::Business(String::from("denied")))
);
assert_eq!(
error(ReadMode::All),
Err(JsonCallError::Business(String::from("denied")))
);
}
#[test]
fn a_technical_error_maps_to_a_transport_failure_in_both_modes() {
let error = |mode| {
let stream = values([crate::Event::Error(crate::ObservableError::Technical(
crate::RpcError::TransportError(String::from("link down")),
))]);
crate::rt::test_block_on(read_json(stream, mode))
};
for mode in [ReadMode::First, ReadMode::All] {
match error(mode) {
Err(JsonCallError::Transport(message)) => {
assert!(message.contains("link down"), "{message}");
}
other => panic!("expected a transport failure, got {other:?}"),
}
}
}
#[test]
fn a_value_json_cannot_represent_is_a_transport_failure() {
use std::collections::HashMap;
let failing = || {
crate::Observable::<HashMap<Vec<u8>, i32>, String>::from_events([
crate::Event::Next(HashMap::from([(vec![1, 2, 3], 2)])),
crate::Event::Complete,
])
};
let first = crate::rt::test_block_on(read_json(failing(), ReadMode::First))
.expect_err("the value cannot be serialized");
assert!(
matches!(&first, JsonCallError::Transport(message)
if message.contains("failed to serialize the response")),
"{first:?}"
);
let all = crate::rt::test_block_on(read_json(failing(), ReadMode::All))
.expect_err("the value cannot be serialized");
assert!(
matches!(&all, JsonCallError::Transport(message)
if message.contains("failed to serialize a value")),
"{all:?}"
);
}
}