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