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