Skip to main content

eoka_protocol/sidecar/
capture.rs

1use super::*;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
4#[serde(rename_all = "lowercase")]
5pub enum ScreenshotFormat {
6    Png,
7    Jpeg,
8    Webp,
9}
10
11dto!(ScreenshotClip {
12    #[schemars(range(min = 0))]
13    x: f64,
14    #[schemars(range(min = 0))]
15    y: f64,
16    #[schemars(schema_with = "positive_scale_schema")]
17    width: f64,
18    #[schemars(schema_with = "positive_scale_schema")]
19    height: f64,
20});
21pub fn screenshot_options(
22    format: Option<ScreenshotFormat>,
23    quality: Option<u8>,
24    clip: Option<&ScreenshotClip>,
25    full_page: Option<bool>,
26) -> eoka::ScreenshotOptions {
27    eoka::ScreenshotOptions {
28        format: match format.unwrap_or(ScreenshotFormat::Png) {
29            ScreenshotFormat::Png => eoka::ScreenshotFormat::Png,
30            ScreenshotFormat::Jpeg => eoka::ScreenshotFormat::Jpeg,
31            ScreenshotFormat::Webp => eoka::ScreenshotFormat::Webp,
32        },
33        quality,
34        clip: clip.map(|clip| eoka::ScreenshotClip {
35            x: clip.x,
36            y: clip.y,
37            width: clip.width,
38            height: clip.height,
39        }),
40        full_page: full_page.unwrap_or(false),
41    }
42}
43
44pub fn validate_screenshot(
45    format: Option<ScreenshotFormat>,
46    quality: Option<u8>,
47    clip: Option<&ScreenshotClip>,
48    full_page: Option<bool>,
49) -> Result<(), ServerError> {
50    if quality.is_some_and(|quality| quality > 100)
51        || (quality.is_some() && format.unwrap_or(ScreenshotFormat::Png) == ScreenshotFormat::Png)
52    {
53        return Err(ServerError::invalid_params(
54            "quality must be between 0 and 100 and is only supported for JPEG or WebP",
55        ));
56    }
57    if let Some(clip) = clip {
58        if full_page.unwrap_or(false) {
59            return Err(ServerError::invalid_params(
60                "clip and fullPage cannot be combined",
61            ));
62        }
63        if !clip.x.is_finite()
64            || !clip.y.is_finite()
65            || clip.x < 0.0
66            || clip.y < 0.0
67            || !clip.width.is_finite()
68            || !clip.height.is_finite()
69            || clip.width <= 0.0
70            || clip.height <= 0.0
71        {
72            return Err(ServerError::invalid_params(
73                "clip requires finite nonnegative x/y and finite positive width/height",
74            ));
75        }
76    }
77    Ok(())
78}
79
80pub fn validate_output_path(path: &str) -> Result<(), ServerError> {
81    if !std::path::Path::new(path).is_absolute() || path.as_bytes().contains(&0) {
82        return Err(ServerError::invalid_params(
83            "path must be an absolute file path without NUL bytes",
84        ));
85    }
86    Ok(())
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
90#[serde(rename_all = "lowercase")]
91pub enum ArtifactContainer {
92    Mp4,
93}
94
95dto!(Artifact {
96    path: String,
97    bytes: u64,
98    mime_type: String,
99    #[serde(skip_serializing_if = "Option::is_none")] container: Option<ArtifactContainer>,
100});
101
102impl Artifact {
103    pub fn validate(&self) -> Result<(), ServerError> {
104        validate_output_path(&self.path)?;
105        if self.bytes > MAX_SAFE_INTEGER {
106            return Err(ServerError::invalid_params(
107                "artifact bytes exceed the JavaScript-safe integer limit",
108            ));
109        }
110        Ok(())
111    }
112}
113
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
115#[serde(rename_all = "camelCase", deny_unknown_fields)]
116pub struct RecordingStartParams {
117    pub page_id: String,
118    #[schemars(regex(
119        pattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
120    ))]
121    pub recording_id: String,
122    pub path: String,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    #[schemars(range(min = 1, max = 2147483647))]
125    pub max_width: Option<u32>,
126    #[serde(skip_serializing_if = "Option::is_none")]
127    #[schemars(range(min = 1, max = 2147483647))]
128    pub max_height: Option<u32>,
129    #[serde(skip_serializing_if = "Option::is_none")]
130    #[schemars(range(min = 1, max = 120))]
131    pub fps: Option<u32>,
132}
133
134dto!(RecordingIdParams {
135    #[schemars(regex(
136        pattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
137    ))]
138    recording_id: String,
139});
140
141fn validate_recording_id(id: &str) -> Result<(), ServerError> {
142    if id.len() != 36
143        || !id.bytes().enumerate().all(|(index, byte)| {
144            if matches!(index, 8 | 13 | 18 | 23) {
145                byte == b'-'
146            } else {
147                byte.is_ascii_hexdigit()
148            }
149        })
150    {
151        return Err(ServerError::invalid_params("recordingId must be a UUID"));
152    }
153    Ok(())
154}
155
156impl RecordingStartParams {
157    pub fn validate(&self) -> Result<(), ServerError> {
158        validate_recording_id(&self.recording_id)?;
159        validate_output_path(&self.path)?;
160        if self
161            .max_width
162            .into_iter()
163            .chain(self.max_height)
164            .any(|dimension| dimension == 0 || dimension > i32::MAX as u32)
165        {
166            return Err(ServerError::invalid_params(
167                "maxWidth/maxHeight must be positive and no greater than 2147483647",
168            ));
169        }
170        if self
171            .fps
172            .is_some_and(|fps| fps == 0 || fps > MAX_RECORDING_FPS)
173        {
174            return Err(ServerError::invalid_params(
175                "fps must be an integer between 1 and 120",
176            ));
177        }
178        Ok(())
179    }
180}
181
182impl RecordingIdParams {
183    pub fn validate(&self) -> Result<(), ServerError> {
184        validate_recording_id(&self.recording_id)
185    }
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
189#[serde(rename_all = "lowercase")]
190pub enum RecordingState {
191    Running,
192    Finalizing,
193    Completed,
194    Cancelled,
195    Failed,
196}
197
198impl RecordingState {
199    pub fn is_terminal(self) -> bool {
200        matches!(self, Self::Completed | Self::Cancelled | Self::Failed)
201    }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
205#[serde(rename_all = "lowercase")]
206pub enum RecordingFailureStage {
207    Start,
208    Stop,
209    Read,
210    Write,
211    Flush,
212    Close,
213    Publish,
214    Cancel,
215    Disconnect,
216}
217
218dto!(RecordingFailure {
219    stage: RecordingFailureStage,
220    code: ErrorCode,
221    message: String,
222    #[serde(skip_serializing_if = "Option::is_none")] partial_path: Option<String>,
223    #[serde(skip_serializing_if = "Option::is_none")] cleanup_uncertain: Option<bool>,
224});
225dto!(RecordingRecord {
226    recording_id: String,
227    page_id: String,
228    state: RecordingState,
229    path: String,
230    #[serde(skip_serializing_if = "Option::is_none")] artifact: Option<Artifact>,
231    #[serde(skip_serializing_if = "Option::is_none")] failure: Option<RecordingFailure>,
232    #[serde(default, skip_serializing_if = "Option::is_none")] frames: Option<u64>,
233    #[serde(default, skip_serializing_if = "Option::is_none")] duration_ms: Option<u64>,
234});
235
236impl RecordingRecord {
237    pub fn validate(&self) -> Result<(), ServerError> {
238        validate_recording_id(&self.recording_id)?;
239        validate_output_path(&self.path)?;
240        if self.state == RecordingState::Completed {
241            let artifact = self.artifact.as_ref().ok_or_else(|| {
242                ServerError::invalid_params("completed recording requires a published artifact")
243            })?;
244            artifact.validate()?;
245            if artifact.path != self.path
246                || artifact.container != Some(ArtifactContainer::Mp4)
247                || artifact.mime_type != "video/mp4"
248                || self.failure.is_some()
249            {
250                return Err(ServerError::invalid_params(
251                    "completed recording requires its destination MP4 artifact and no failure",
252                ));
253            }
254        } else if self.artifact.is_some() || self.frames.is_some() || self.duration_ms.is_some() {
255            return Err(ServerError::invalid_params(
256                "only completed recordings may contain an artifact, frames or duration",
257            ));
258        }
259        if self.state == RecordingState::Failed && self.failure.is_none() {
260            return Err(ServerError::invalid_params(
261                "failed recording requires failure evidence",
262            ));
263        }
264        if self.failure.is_some() && !self.state.is_terminal() {
265            return Err(ServerError::invalid_params(
266                "nonterminal recording cannot contain failure evidence",
267            ));
268        }
269        if let Some(partial) = self
270            .failure
271            .as_ref()
272            .and_then(|failure| failure.partial_path.as_ref())
273        {
274            validate_output_path(partial)?;
275            if partial == &self.path {
276                return Err(ServerError::invalid_params(
277                    "partial artifact cannot use the destination success path",
278                ));
279            }
280        }
281        Ok(())
282    }
283}