1use serde::de::Error as _;
10use serde::{Deserialize, Deserializer, Serialize};
11use serde_json::{Map, Value};
12
13use crate::constants::{DAEMON_PROTOCOL_VERSION, MAX_ACTION_LENGTH, MAX_ID_LENGTH};
14use crate::error::ValidationError;
15use crate::runtime::RuntimeViewData;
16use crate::session::{SessionPatch, SessionSnapshotData};
17
18pub fn js_length(value: &str) -> usize {
22 value.chars().map(char::len_utf16).sum()
23}
24
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub struct DaemonRequest {
32 pub version: u32,
33 pub id: String,
34 pub action: String,
35 #[serde(flatten)]
36 pub payload: Map<String, Value>,
37}
38
39impl DaemonRequest {
40 pub fn new(id: impl Into<String>, action: impl Into<String>) -> Self {
42 Self {
43 version: DAEMON_PROTOCOL_VERSION,
44 id: id.into(),
45 action: action.into(),
46 payload: Map::new(),
47 }
48 }
49
50 pub fn with(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
52 self.payload.insert(key.into(), value.into());
53 self
54 }
55
56 pub fn get(&self, key: &str) -> Option<&Value> {
58 self.payload.get(key)
59 }
60}
61
62pub fn validate_request(request: &DaemonRequest) -> Result<(), ValidationError> {
65 if request.version != DAEMON_PROTOCOL_VERSION {
66 return Err(ValidationError::WrongVersion {
67 expected: DAEMON_PROTOCOL_VERSION,
68 actual: request.version,
69 });
70 }
71 let id = js_length(&request.id);
72 if !(1..=MAX_ID_LENGTH).contains(&id) {
73 return Err(ValidationError::InvalidIdLength { actual: id });
74 }
75 let action = js_length(&request.action);
76 if !(1..=MAX_ACTION_LENGTH).contains(&action) {
77 return Err(ValidationError::InvalidActionLength { actual: action });
78 }
79 Ok(())
80}
81
82#[derive(Debug, Clone, PartialEq, Serialize)]
88#[serde(untagged)]
89pub enum DaemonResponse {
90 Success {
91 version: u32,
92 id: String,
93 ok: bool,
94 result: Value,
95 },
96 Failure {
97 version: u32,
98 id: String,
99 ok: bool,
100 error: String,
101 },
102}
103
104impl<'de> Deserialize<'de> for DaemonResponse {
105 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106 where
107 D: Deserializer<'de>,
108 {
109 let value = Value::deserialize(deserializer)?;
110 let object = value
111 .as_object()
112 .ok_or_else(|| D::Error::custom("response must be an object"))?;
113 let version = object
114 .get("version")
115 .and_then(Value::as_u64)
116 .and_then(|version| u32::try_from(version).ok())
117 .ok_or_else(|| D::Error::custom("response version must be an integer"))?;
118 let id = object
119 .get("id")
120 .and_then(Value::as_str)
121 .ok_or_else(|| D::Error::custom("response id must be a string"))?
122 .to_owned();
123 let ok = object
124 .get("ok")
125 .and_then(Value::as_bool)
126 .ok_or_else(|| D::Error::custom("response ok must be a boolean"))?;
127 let has_result = object.contains_key("result");
128 let has_error = object.contains_key("error");
129 match (has_result, has_error, ok) {
130 (true, false, true) => Ok(DaemonResponse::Success {
131 version,
132 id,
133 ok,
134 result: object.get("result").cloned().unwrap_or(Value::Null),
135 }),
136 (false, true, false) => {
137 let error = object
138 .get("error")
139 .and_then(Value::as_str)
140 .ok_or_else(|| D::Error::custom("response error must be a string"))?
141 .to_owned();
142 Ok(DaemonResponse::Failure {
143 version,
144 id,
145 ok,
146 error,
147 })
148 }
149 _ => Err(D::Error::custom(
150 ValidationError::MalformedResponse.to_string(),
151 )),
152 }
153 }
154}
155
156impl DaemonResponse {
157 pub fn id(&self) -> &str {
159 match self {
160 DaemonResponse::Success { id, .. } | DaemonResponse::Failure { id, .. } => id,
161 }
162 }
163
164 pub fn version(&self) -> u32 {
166 match self {
167 DaemonResponse::Success { version, .. } | DaemonResponse::Failure { version, .. } => {
168 *version
169 }
170 }
171 }
172}
173
174pub fn validate_response(
178 response: &DaemonResponse,
179 expected_version: u32,
180) -> Result<(), ValidationError> {
181 if response.version() != expected_version {
182 return Err(ValidationError::ResponseVersionMismatch {
183 expected: expected_version,
184 actual: response.version(),
185 });
186 }
187 match response {
188 DaemonResponse::Success { ok, .. } if !*ok => Err(ValidationError::MalformedResponse),
189 DaemonResponse::Failure { ok, .. } if *ok => Err(ValidationError::MalformedResponse),
190 _ => Ok(()),
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
197#[serde(tag = "event", rename_all = "lowercase")]
198pub enum DaemonEvent {
199 Snapshot {
202 version: u32,
203 snapshot: SessionSnapshotData,
204 runtime: RuntimeViewData,
205 },
206 Patch { version: u32, patch: SessionPatch },
208 Notification {
211 version: u32,
212 title: String,
213 message: String,
214 },
215}
216
217impl DaemonEvent {
218 pub fn version(&self) -> u32 {
219 match self {
220 Self::Snapshot { version, .. }
221 | Self::Patch { version, .. }
222 | Self::Notification { version, .. } => *version,
223 }
224 }
225}
226
227pub fn validate_event(event: &DaemonEvent, expected_version: u32) -> Result<(), ValidationError> {
229 if event.version() != expected_version {
230 return Err(ValidationError::ResponseVersionMismatch {
231 expected: expected_version,
232 actual: event.version(),
233 });
234 }
235 Ok(())
236}
237
238pub type DaemonNotification = DaemonEvent;