Skip to main content

eoka_protocol/
sidecar.rs

1use schemars::{JsonSchema, Schema, SchemaGenerator};
2use serde::{Deserialize, Serialize};
3use serde_json::{json, Value};
4use std::collections::{BTreeMap, HashMap};
5
6pub use crate::{OperationIdArgs, OperationListArgs, OperationWaitArgs};
7
8pub const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
9pub const MAX_MESSAGE_BYTES: usize = 32 * 1024 * 1024;
10pub const MAX_IN_FLIGHT: usize = 128;
11pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion { major: 4, minor: 0 };
12pub const MAX_SCREENSHOT_BYTES: usize = 16 * 1024 * 1024;
13pub const MAX_RECORDING_FPS: u32 = 120;
14pub const CAPABILITIES: &[&str] = &[
15    "durableActions",
16    "operationCancellation",
17    "gracefulShutdown",
18    "explicitExecutablePath",
19    "browserAttachment",
20    "runtimeIsolation",
21    "sandboxControl",
22    "viewportEmulation",
23    "boundedFetch",
24    "screenshotOptions",
25    "screenshotFile",
26    "nativeRecording",
27    "cloudflareAutoSolve",
28    "operationCatalog",
29    "pageBlockers",
30];
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
33pub struct ProtocolVersion {
34    pub major: u32,
35    pub minor: u32,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
39pub struct HelloParams {
40    pub protocol: ProtocolVersion,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
44#[serde(rename_all = "camelCase")]
45pub struct TransportLimits {
46    pub max_message_bytes: usize,
47    pub max_in_flight: usize,
48}
49
50impl Default for TransportLimits {
51    fn default() -> Self {
52        Self {
53            max_message_bytes: MAX_MESSAGE_BYTES,
54            max_in_flight: MAX_IN_FLIGHT,
55        }
56    }
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
60#[serde(rename_all = "camelCase")]
61pub struct HelloResult {
62    pub protocol: ProtocolVersion,
63    pub server_version: String,
64    pub core_version: String,
65    pub methods: Vec<String>,
66    pub capabilities: Vec<String>,
67    pub limits: TransportLimits,
68}
69
70pub fn valid_request_id(id: &Value) -> bool {
71    id.as_u64()
72        .is_some_and(|id| id > 0 && id <= MAX_SAFE_INTEGER)
73}
74
75fn deserialize_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Value, D::Error> {
76    let id = Value::deserialize(deserializer)?;
77    if valid_request_id(&id) {
78        Ok(id)
79    } else {
80        Err(serde::de::Error::custom(
81            "id must be a positive integer no greater than 9007199254740991",
82        ))
83    }
84}
85
86fn request_id_schema(_: &mut SchemaGenerator) -> Schema {
87    json!({"type":"integer", "minimum":1, "maximum":MAX_SAFE_INTEGER})
88        .try_into()
89        .unwrap()
90}
91
92fn response_id_schema(_: &mut SchemaGenerator) -> Schema {
93    json!({"anyOf":[{"type":"integer","minimum":1,"maximum":MAX_SAFE_INTEGER},{"type":"null"}]})
94        .try_into()
95        .unwrap()
96}
97
98fn deserialize_response_id<'de, D: serde::Deserializer<'de>>(
99    deserializer: D,
100) -> Result<Value, D::Error> {
101    let id = Value::deserialize(deserializer)?;
102    if id.is_null() || valid_request_id(&id) {
103        Ok(id)
104    } else {
105        Err(serde::de::Error::custom(
106            "response id must be null or a safe positive integer",
107        ))
108    }
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
112pub struct Request {
113    #[serde(deserialize_with = "deserialize_id")]
114    #[schemars(schema_with = "request_id_schema")]
115    pub id: Value,
116    pub method: String,
117    #[serde(default = "empty_params")]
118    pub params: Value,
119}
120
121fn empty_params() -> Value {
122    json!({})
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
126#[serde(untagged, deny_unknown_fields)]
127pub enum Response {
128    Success {
129        #[schemars(schema_with = "response_id_schema")]
130        #[serde(deserialize_with = "deserialize_response_id")]
131        id: Value,
132        result: Value,
133    },
134    Failure {
135        #[schemars(schema_with = "response_id_schema")]
136        #[serde(deserialize_with = "deserialize_response_id")]
137        id: Value,
138        error: ServerError,
139    },
140}
141
142impl Response {
143    pub fn ok(id: impl Into<Value>, result: Value) -> Self {
144        Self::Success {
145            id: response_id(id.into()),
146            result,
147        }
148    }
149
150    pub fn err(id: impl Into<Value>, error: ServerError) -> Self {
151        Self::Failure {
152            id: response_id(id.into()),
153            error,
154        }
155    }
156}
157
158fn response_id(id: Value) -> Value {
159    if valid_request_id(&id) {
160        id
161    } else {
162        Value::Null
163    }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
167pub enum ErrorCode {
168    ElementNotFound,
169    ElementNotVisible,
170    Timeout,
171    RetryExhausted,
172    Cdp,
173    InvalidPage,
174    InvalidParams,
175    UnknownMethod,
176    Internal,
177    ProtocolMismatch,
178    MessageTooLarge,
179    ServerBusy,
180    ShuttingDown,
181    Cancelled,
182    Action,
183    Operation,
184    ScreenshotTooLarge,
185    FileOutput,
186    RecordingUnsupported,
187    RecordingNotFound,
188    RecordingConflict,
189    RecordingAlreadyActive,
190    RecordingInvalidState,
191    RecordingFailed,
192    DialogOpen,
193    NavigationPending,
194    PageUnresponsive,
195}
196
197impl ErrorCode {
198    pub fn blocker_detail_code(self) -> Option<&'static str> {
199        BLOCKER_ERROR_DETAIL_CODES
200            .iter()
201            .find(|(code, _)| *code == self)
202            .map(|(_, detail)| *detail)
203    }
204
205    pub fn for_blocker_detail(detail_code: &str) -> Option<Self> {
206        BLOCKER_ERROR_DETAIL_CODES
207            .iter()
208            .find(|(_, detail)| *detail == detail_code)
209            .map(|(code, _)| *code)
210    }
211}
212
213const BLOCKER_ERROR_DETAIL_CODES: &[(ErrorCode, &str)] = &[
214    (ErrorCode::DialogOpen, "dialog_open"),
215    (ErrorCode::NavigationPending, "navigation_pending"),
216    (ErrorCode::PageUnresponsive, "page_unresponsive"),
217];
218
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
220#[serde(tag = "kind", rename_all = "snake_case")]
221pub enum PageBlocker {
222    #[serde(rename_all = "camelCase")]
223    Dialog {
224        dialog_type: String,
225        message: String,
226        url: String,
227        elapsed_ms: u64,
228    },
229    #[serde(rename_all = "camelCase")]
230    Navigation {
231        #[serde(skip_serializing_if = "Option::is_none")]
232        url: Option<String>,
233        elapsed_ms: u64,
234    },
235}
236
237#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
238pub struct CdpErrorDetail {
239    pub method: Option<String>,
240    pub code: Option<i64>,
241    pub message: String,
242}
243
244#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
245pub struct ErrorData {
246    #[serde(skip_serializing_if = "Option::is_none")]
247    pub operation_id: Option<String>,
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub receipt: Option<crate::ActionReceipt>,
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub detail: Option<crate::ErrorDetail>,
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub cdp: Option<CdpErrorDetail>,
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub source: Option<Box<ServerError>>,
256    #[serde(rename = "recordingId", skip_serializing_if = "Option::is_none")]
257    pub recording_id: Option<String>,
258    #[serde(skip_serializing_if = "Option::is_none")]
259    pub recording: Option<RecordingRecord>,
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub path: Option<String>,
262    #[serde(rename = "partialPath", skip_serializing_if = "Option::is_none")]
263    pub partial_path: Option<String>,
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub blocker: Option<PageBlocker>,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub result: Option<Value>,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
271pub struct ServerError {
272    pub code: ErrorCode,
273    pub message: String,
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub data: Option<Box<ErrorData>>,
276}
277
278impl ServerError {
279    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
280        Self {
281            code,
282            message: message.into(),
283            data: None,
284        }
285    }
286    pub fn with_data(mut self, data: ErrorData) -> Self {
287        self.data = Some(Box::new(data));
288        self
289    }
290    pub fn from_detail(detail: crate::ErrorDetail) -> Self {
291        Self::new(ErrorCode::Operation, detail.message.clone()).with_data(ErrorData {
292            detail: Some(detail),
293            ..Default::default()
294        })
295    }
296    pub fn invalid_params(message: impl Into<String>) -> Self {
297        Self::new(ErrorCode::InvalidParams, message)
298    }
299    pub fn invalid_page(page_id: &str) -> Self {
300        Self::new(
301            ErrorCode::InvalidPage,
302            format!("unknown pageId \"{page_id}\""),
303        )
304    }
305    pub fn unknown_method(method: &str) -> Self {
306        Self::new(
307            ErrorCode::UnknownMethod,
308            format!("unknown method \"{method}\""),
309        )
310    }
311    pub fn internal(message: impl Into<String>) -> Self {
312        Self::new(ErrorCode::Internal, message)
313    }
314
315    pub fn blocked(detail: crate::ErrorDetail, blocker: Option<PageBlocker>) -> Self {
316        let code = ErrorCode::for_blocker_detail(&detail.code).unwrap_or(ErrorCode::Operation);
317        Self::new(code, detail.message.clone()).with_data(ErrorData {
318            detail: Some(detail),
319            blocker,
320            ..Default::default()
321        })
322    }
323}
324
325impl std::fmt::Display for ServerError {
326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327        f.write_str(&self.message)
328    }
329}
330impl std::error::Error for ServerError {}
331
332const CORE_ERROR_DETAIL_CODES: &[(ErrorCode, &str)] = &[
333    (ErrorCode::ElementNotFound, "element_not_found"),
334    (ErrorCode::ElementNotVisible, "element_not_visible"),
335    (ErrorCode::Timeout, "timeout"),
336    (ErrorCode::RetryExhausted, "retry_exhausted"),
337    (ErrorCode::Cdp, "cdp_error"),
338    (ErrorCode::MessageTooLarge, "message_too_large"),
339];
340
341pub fn core_error_detail_code(code: ErrorCode) -> Option<&'static str> {
342    CORE_ERROR_DETAIL_CODES
343        .iter()
344        .find(|(candidate, _)| *candidate == code)
345        .map(|(_, detail)| *detail)
346}
347
348pub fn core_error_code(detail_code: &str) -> Option<ErrorCode> {
349    CORE_ERROR_DETAIL_CODES
350        .iter()
351        .find(|(_, candidate)| *candidate == detail_code)
352        .map(|(code, _)| *code)
353}
354
355impl From<eoka::Error> for ServerError {
356    fn from(error: eoka::Error) -> Self {
357        let message = error.to_string();
358        if let eoka::Detail::Action { receipt, cause } = error.detail() {
359            return Self::new(ErrorCode::Action, message).with_data(ErrorData {
360                detail: Some(crate::ErrorDetail::new(error.code(), cause.to_string())),
361                receipt: Some(eoka::ActionReceipt::clone(receipt)),
362                source: Some(Box::new(Self::from(eoka::Error::clone(cause)))),
363                ..Default::default()
364            });
365        }
366        if let Some((method, code)) = error.cdp_context() {
367            return Self::new(ErrorCode::Cdp, message).with_data(ErrorData {
368                cdp: Some(CdpErrorDetail {
369                    method: method.map(str::to_owned),
370                    code,
371                    message: error.message().to_owned(),
372                }),
373                ..Default::default()
374            });
375        }
376        match error.code() {
377            eoka::ErrorCode::ElementNotFound => Self::new(ErrorCode::ElementNotFound, message),
378            eoka::ErrorCode::ElementNotVisible => Self::new(ErrorCode::ElementNotVisible, message),
379            eoka::ErrorCode::ResultTooLarge
380                if matches!(error.detail(), eoka::Detail::TooLarge { .. }) =>
381            {
382                Self::new(ErrorCode::MessageTooLarge, message)
383            }
384            eoka::ErrorCode::RetryExhausted => Self::new(ErrorCode::RetryExhausted, message),
385            eoka::ErrorCode::Timeout => Self::new(ErrorCode::Timeout, message),
386            eoka::ErrorCode::InvalidArgument => Self::new(ErrorCode::InvalidParams, message),
387            eoka::ErrorCode::LaunchFailed
388            | eoka::ErrorCode::NavigationFailed
389            | eoka::ErrorCode::InputState
390            | eoka::ErrorCode::DecodeFailed
391            | eoka::ErrorCode::Transport
392            | eoka::ErrorCode::Io
393            | eoka::ErrorCode::Serialization
394            | eoka::ErrorCode::Patching
395            | eoka::ErrorCode::InvalidUrl
396            | eoka::ErrorCode::ChromeNotFound
397            | eoka::ErrorCode::ValueMismatch => Self::internal(message),
398            _ => Self::new(ErrorCode::Cdp, message.clone()).with_data(ErrorData {
399                cdp: Some(CdpErrorDetail {
400                    method: None,
401                    code: None,
402                    message,
403                }),
404                ..Default::default()
405            }),
406        }
407    }
408}
409
410macro_rules! dto {
411    ($name:ident { $($(#[$attr:meta])* $field:ident: $ty:ty),* $(,)? }) => {
412        #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
413        #[serde(rename_all = "camelCase")]
414        pub struct $name { $($(#[$attr])* pub $field: $ty),* }
415    };
416}
417
418mod capture;
419mod methods;
420mod params;
421
422pub use capture::*;
423pub use methods::*;
424pub use params::*;
425
426#[cfg(test)]
427mod tests;