use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
use crate::constants::{DAEMON_PROTOCOL_VERSION, MAX_ACTION_LENGTH, MAX_ID_LENGTH};
use crate::error::ValidationError;
use crate::runtime::RuntimeViewData;
use crate::session::{SessionPatch, SessionSnapshotData};
pub fn js_length(value: &str) -> usize {
value.chars().map(char::len_utf16).sum()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DaemonRequest {
pub version: u32,
pub id: String,
pub action: String,
#[serde(flatten)]
pub payload: Map<String, Value>,
}
impl DaemonRequest {
pub fn new(id: impl Into<String>, action: impl Into<String>) -> Self {
Self {
version: DAEMON_PROTOCOL_VERSION,
id: id.into(),
action: action.into(),
payload: Map::new(),
}
}
pub fn with(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.payload.insert(key.into(), value.into());
self
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.payload.get(key)
}
}
pub fn validate_request(request: &DaemonRequest) -> Result<(), ValidationError> {
if request.version != DAEMON_PROTOCOL_VERSION {
return Err(ValidationError::WrongVersion {
expected: DAEMON_PROTOCOL_VERSION,
actual: request.version,
});
}
let id = js_length(&request.id);
if !(1..=MAX_ID_LENGTH).contains(&id) {
return Err(ValidationError::InvalidIdLength { actual: id });
}
let action = js_length(&request.action);
if !(1..=MAX_ACTION_LENGTH).contains(&action) {
return Err(ValidationError::InvalidActionLength { actual: action });
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum DaemonResponse {
Success {
version: u32,
id: String,
ok: bool,
result: Value,
},
Failure {
version: u32,
id: String,
ok: bool,
error: String,
},
}
impl<'de> Deserialize<'de> for DaemonResponse {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
let object = value
.as_object()
.ok_or_else(|| D::Error::custom("response must be an object"))?;
let version = object
.get("version")
.and_then(Value::as_u64)
.and_then(|version| u32::try_from(version).ok())
.ok_or_else(|| D::Error::custom("response version must be an integer"))?;
let id = object
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| D::Error::custom("response id must be a string"))?
.to_owned();
let ok = object
.get("ok")
.and_then(Value::as_bool)
.ok_or_else(|| D::Error::custom("response ok must be a boolean"))?;
let has_result = object.contains_key("result");
let has_error = object.contains_key("error");
match (has_result, has_error, ok) {
(true, false, true) => Ok(DaemonResponse::Success {
version,
id,
ok,
result: object.get("result").cloned().unwrap_or(Value::Null),
}),
(false, true, false) => {
let error = object
.get("error")
.and_then(Value::as_str)
.ok_or_else(|| D::Error::custom("response error must be a string"))?
.to_owned();
Ok(DaemonResponse::Failure {
version,
id,
ok,
error,
})
}
_ => Err(D::Error::custom(
ValidationError::MalformedResponse.to_string(),
)),
}
}
}
impl DaemonResponse {
pub fn id(&self) -> &str {
match self {
DaemonResponse::Success { id, .. } | DaemonResponse::Failure { id, .. } => id,
}
}
pub fn version(&self) -> u32 {
match self {
DaemonResponse::Success { version, .. } | DaemonResponse::Failure { version, .. } => {
*version
}
}
}
}
pub fn validate_response(
response: &DaemonResponse,
expected_version: u32,
) -> Result<(), ValidationError> {
if response.version() != expected_version {
return Err(ValidationError::ResponseVersionMismatch {
expected: expected_version,
actual: response.version(),
});
}
match response {
DaemonResponse::Success { ok, .. } if !*ok => Err(ValidationError::MalformedResponse),
DaemonResponse::Failure { ok, .. } if *ok => Err(ValidationError::MalformedResponse),
_ => Ok(()),
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "lowercase")]
pub enum DaemonEvent {
Snapshot {
version: u32,
snapshot: SessionSnapshotData,
runtime: RuntimeViewData,
},
Patch { version: u32, patch: SessionPatch },
Notification {
version: u32,
title: String,
message: String,
},
}
impl DaemonEvent {
pub fn version(&self) -> u32 {
match self {
Self::Snapshot { version, .. }
| Self::Patch { version, .. }
| Self::Notification { version, .. } => *version,
}
}
}
pub fn validate_event(event: &DaemonEvent, expected_version: u32) -> Result<(), ValidationError> {
if event.version() != expected_version {
return Err(ValidationError::ResponseVersionMismatch {
expected: expected_version,
actual: event.version(),
});
}
Ok(())
}
pub type DaemonNotification = DaemonEvent;