use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use futures::future::BoxFuture;
use jmap_types::JmapError;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use tokio::sync::mpsc;
const CORE_TYPES: [&str; 6] = [
"Request",
"WebSocketPushEnable",
"WebSocketPushDisable",
"Response",
"RequestError",
"StateChange",
];
const RESERVED_PROBLEM_MEMBERS: [&str; 8] = [
"@type",
"requestId",
"type",
"status",
"title",
"detail",
"instance",
"limit",
];
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct ExtensionMessage {
pub message_type: String,
pub id: Option<String>,
pub body: Map<String, Value>,
}
impl ExtensionMessage {
pub fn new(message_type: impl Into<String>, body: Map<String, Value>) -> Self {
let id = body.get("id").and_then(Value::as_str).map(str::to_owned);
Self {
message_type: message_type.into(),
id,
body,
}
}
pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T, JmapError> {
serde_json::from_value(Value::Object(self.body.clone())).map_err(|e| {
let mut err = JmapError::not_request();
err.description = Some(format!("Malformed {}: {e}", self.message_type));
err
})
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ExtensionSendError {
#[error("the connection's extension message queue is full")]
Full,
#[error("the connection has ended")]
Closed,
#[error("an extension message must be a JSON object whose @type is not an RFC 8887 type")]
NotAnExtensionMessage,
#[error("serializing an extension message failed")]
Serialize(#[source] serde_json::Error),
}
#[derive(Debug, Clone)]
pub struct ExtensionSender {
tx: mpsc::Sender<String>,
}
impl ExtensionSender {
pub(super) fn new(tx: mpsc::Sender<String>) -> Self {
Self { tx }
}
pub async fn send<T: Serialize + ?Sized>(&self, message: &T) -> Result<(), ExtensionSendError> {
let text = extension_text(message)?;
self.tx
.send(text)
.await
.map_err(|_| ExtensionSendError::Closed)
}
pub fn try_send<T: Serialize + ?Sized>(&self, message: &T) -> Result<(), ExtensionSendError> {
let text = extension_text(message)?;
self.tx.try_send(text).map_err(|e| match e {
mpsc::error::TrySendError::Full(_) => ExtensionSendError::Full,
mpsc::error::TrySendError::Closed(_) => ExtensionSendError::Closed,
})
}
pub fn is_closed(&self) -> bool {
self.tx.is_closed()
}
pub async fn closed(&self) {
self.tx.closed().await;
}
}
fn extension_text<T: Serialize + ?Sized>(message: &T) -> Result<String, ExtensionSendError> {
let value = serde_json::to_value(message).map_err(ExtensionSendError::Serialize)?;
match value.get("@type").and_then(Value::as_str) {
Some(ty) if !CORE_TYPES.contains(&ty) => {}
_ => return Err(ExtensionSendError::NotAnExtensionMessage),
}
serde_json::to_string(&value).map_err(ExtensionSendError::Serialize)
}
pub trait ExtensionHandler: Send + 'static {
fn message_types(&self) -> &[&str];
fn start(&mut self, events: ExtensionSender) {
let _ = events;
}
fn handle(
&mut self,
message: ExtensionMessage,
) -> impl Future<Output = Result<(), JmapError>> + Send;
fn close(&mut self) -> impl Future<Output = ()> + Send {
async {}
}
}
trait ErasedHandler: Send {
fn start(&mut self, events: ExtensionSender);
fn handle(&mut self, message: ExtensionMessage) -> BoxFuture<'_, Result<(), JmapError>>;
fn close(&mut self) -> BoxFuture<'_, ()>;
}
impl<T: ExtensionHandler> ErasedHandler for T {
fn start(&mut self, events: ExtensionSender) {
ExtensionHandler::start(self, events);
}
fn handle(&mut self, message: ExtensionMessage) -> BoxFuture<'_, Result<(), JmapError>> {
Box::pin(ExtensionHandler::handle(self, message))
}
fn close(&mut self) -> BoxFuture<'_, ()> {
Box::pin(ExtensionHandler::close(self))
}
}
type Handled = (
usize,
Box<dyn ErasedHandler>,
Option<String>,
Result<(), JmapError>,
);
#[derive(Default)]
pub(super) struct Extensions {
handlers: Vec<Option<Box<dyn ErasedHandler>>>,
by_type: HashMap<String, usize>,
in_flight: Option<Pin<Box<dyn Future<Output = Handled> + Send>>>,
}
impl fmt::Debug for Extensions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut types: Vec<&str> = self.by_type.keys().map(String::as_str).collect();
types.sort_unstable();
f.debug_list().entries(types).finish()
}
}
impl Extensions {
pub(super) fn register<X: ExtensionHandler>(&mut self, handler: X) {
let index = self.handlers.len();
for &ty in handler.message_types() {
assert!(
!CORE_TYPES.contains(&ty),
"extension message type {ty:?} is an RFC 8887 type"
);
let previous = self.by_type.insert(ty.to_owned(), index);
assert!(
previous.is_none_or(|p| p == index),
"extension message type {ty:?} is registered twice"
);
}
self.handlers.push(Some(Box::new(handler)));
}
pub(super) fn handles(&self, ty: &str) -> bool {
self.by_type.contains_key(ty)
}
pub(super) fn is_busy(&self) -> bool {
self.in_flight.is_some()
}
pub(super) fn start(&mut self, capacity: usize) -> Option<mpsc::Receiver<String>> {
if self.handlers.is_empty() {
return None;
}
let (tx, rx) = mpsc::channel(capacity);
for handler in self.handlers.iter_mut().flatten() {
handler.start(ExtensionSender::new(tx.clone()));
}
Some(rx)
}
pub(super) fn dispatch(&mut self, message: ExtensionMessage) {
let index = self.by_type[&message.message_type];
let mut handler = self.handlers[index]
.take()
.expect("handlers run one message at a time");
let id = message.id.clone();
self.in_flight = Some(Box::pin(async move {
let result = handler.handle(message).await;
(index, handler, id, result)
}));
}
pub(super) async fn next_done(&mut self) -> (Option<String>, Result<(), JmapError>) {
let Some(in_flight) = self.in_flight.as_mut() else {
return std::future::pending().await;
};
let (index, handler, id, result) = in_flight.await;
self.in_flight = None;
self.handlers[index] = Some(handler);
(id, result)
}
pub(super) async fn close(&mut self) {
if self.in_flight.is_some() {
let _ = self.next_done().await;
}
for handler in self.handlers.iter_mut().flatten() {
handler.close().await;
}
}
}
pub(super) fn extension_error(
err: &JmapError,
request_id: Option<String>,
) -> crate::WsRequestError {
let mut error = super::request_error(err, request_id);
for (name, value) in &err.extra {
if !RESERVED_PROBLEM_MEMBERS.contains(&name.as_str()) {
error.problem.extra.insert(name.clone(), value.clone());
}
}
error
}