use serde::{Serialize, Serializer};
use serde_json::{Value, json};
use socketio_next::engineio;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
SocketIo(#[from] socketio_next::Error),
#[error("no socket.io client with id `{0}`")]
UnknownClient(String),
#[error("a socket.io client with id `{0}` is registered already")]
AlreadyExists(String),
#[error("socket.io client `{0}` is read-only for the webview")]
AccessDenied(String),
#[error("no pending server ack {0} for this webview (answered, expired or unknown)")]
UnknownAck(u64),
#[error("the id `{0}` is reserved for a client registered from Rust")]
Reserved(String),
#[error("the server URL is not allowed by the socketio plugin configuration")]
UrlNotAllowed,
#[error("too many socket.io subscriptions for this webview (at most {0})")]
TooManySubscriptions(usize),
#[error("too many socket.io clients connected by this webview (at most {0})")]
TooManyClients(usize),
#[error("socket.io client `{0}` was registered from Rust: its connect values are Rust's")]
NotConfigurable(String),
#[error("invalid options: {0}")]
InvalidOptions(String),
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ErrorPayload {
pub kind: &'static str,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl ErrorPayload {
pub(crate) fn from_core(err: &socketio_next::Error) -> Self {
use socketio_next::Error as E;
let mut data = None;
let kind = match err {
E::InvalidUrl(_) => "InvalidUrl",
E::Engine(e) => engine_kind(e, &mut data),
E::Protocol(_) => "Protocol",
E::ConnectTimeout(_) => "ConnectTimeout",
E::ConnectRejected { data: d, .. } => {
data.clone_from(d);
"ConnectRejected"
}
E::IncompatibleServer => "IncompatibleServer",
E::InvalidAuth(_) => "InvalidAuth",
E::NotConnected => "NotConnected",
E::Closed => "Closed",
E::AckTimeout(_) => "AckTimeout",
E::Disconnected => "Disconnected",
E::ReservedEvent(_) => "ReservedEvent",
E::Json(_) => "Json",
E::InvalidHeader(_) => "InvalidHeader",
_ => "SocketIo",
};
ErrorPayload {
kind,
message: err.to_string(),
data,
}
}
}
fn engine_kind(err: &engineio::Error, data: &mut Option<Value>) -> &'static str {
use engineio::Error as E;
match err {
E::Protocol(_) => "Protocol",
E::InvalidUrl(_) => "InvalidUrl",
E::InvalidUrlScheme(_) => "InvalidUrlScheme",
E::Http(_) => "Http",
E::HttpStatus {
status, message, ..
} => {
*data = Some(json!({ "status": status, "message": message }));
"HttpStatus"
}
E::WebsocketClosed { code, reason, .. } => {
*data = Some(json!({ "code": code, "reason": reason }));
"WebsocketClosed"
}
E::ProxyFailed(_) => "ProxyFailed",
E::Websocket(_) => "Websocket",
E::InvalidHandshake(_) => "InvalidHandshake",
E::NotConnected => "NotConnected",
E::UpgradeUnavailable => "UpgradeUnavailable",
E::UpgradeFailed(_) => "UpgradeFailed",
E::PingTimeout => "PingTimeout",
E::Timeout(_) => "Timeout",
E::TlsNotEnabled(_) => "TlsNotEnabled",
E::TlsProviderMissing => "TlsProviderMissing",
E::InvalidTlsConfig(_) => "InvalidTlsConfig",
_ => "Engine",
}
}
impl From<&Error> for ErrorPayload {
fn from(err: &Error) -> Self {
let kind = match err {
Error::SocketIo(e) => return ErrorPayload::from_core(e),
Error::UnknownClient(_) => "UnknownClient",
Error::AlreadyExists(_) => "AlreadyExists",
Error::AccessDenied(_) => "AccessDenied",
Error::UnknownAck(_) => "UnknownAck",
Error::Reserved(_) => "Reserved",
Error::UrlNotAllowed => "UrlNotAllowed",
Error::TooManySubscriptions(_) => "TooManySubscriptions",
Error::TooManyClients(_) => "TooManyClients",
Error::InvalidOptions(_) => "InvalidOptions",
Error::NotConfigurable(_) => "NotConfigurable",
};
ErrorPayload {
kind,
message: err.to_string(),
data: None,
}
}
}
impl Serialize for Error {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
ErrorPayload::from(self).serialize(serializer)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kinds_and_data() {
let denied = serde_json::to_value(Error::AccessDenied("core".into())).unwrap();
assert_eq!(denied["kind"], "AccessDenied");
assert!(denied.get("data").is_none());
let not =
serde_json::to_value(Error::SocketIo(socketio_next::Error::NotConnected)).unwrap();
assert_eq!(not["kind"], "NotConnected");
}
}