1pub mod container;
4
5use std::time::Duration;
6
7use anyhow::{Context, Result, bail, ensure};
8use base64::{Engine, engine::general_purpose::STANDARD};
9use futures::StreamExt;
10use serde_json::{Value, json};
11use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
12use tokio_util::{
13 codec::{FramedRead, LinesCodec},
14 sync::CancellationToken,
15};
16
17use crate::{Action, Driver, MAX_SCREENSHOT_BYTES, MouseButton, Observation, Point, Screenshot, ScrollDirection};
18
19const MAX_ACTION_BYTES: usize = 1024 * 1024;
20const MAX_REPLY_BYTES: usize = MAX_SCREENSHOT_BYTES.div_ceil(3) * 4 + 256;
21const STARTUP_TIMEOUT: Duration = Duration::from_secs(20);
22
23pub struct BrowserDriver<R, W> {
27 replies: FramedRead<R, LinesCodec>,
28 commands: W,
29 usable: bool,
30}
31
32impl<R, W> BrowserDriver<R, W>
33where
34 R: AsyncRead + Unpin + Send,
35 W: AsyncWrite + Unpin + Send,
36{
37 pub async fn connect(replies: R, commands: W) -> Result<Self> {
43 let mut driver = Self {
44 replies: FramedRead::new(replies, LinesCodec::new_with_max_length(MAX_REPLY_BYTES)),
45 commands,
46 usable: true,
47 };
48 let reply = tokio::time::timeout(STARTUP_TIMEOUT, driver.read_reply())
49 .await
50 .context("browser runner startup timed out")??;
51 ensure!(reply.get("kind").and_then(Value::as_str) == Some("ready"), "browser runner did not open the target");
52 Ok(driver)
53 }
54
55 async fn read_reply(&mut self) -> Result<Value> {
56 let line = self
57 .replies
58 .next()
59 .await
60 .context("browser runner closed its reply stream")?
61 .map_err(|_private_error| anyhow::anyhow!("invalid browser runner reply frame"))?;
62 serde_json::from_str(&line).map_err(|_private_error| anyhow::anyhow!("invalid browser runner reply"))
63 }
64}
65
66impl<R, W> Driver for BrowserDriver<R, W>
67where
68 R: AsyncRead + Unpin + Send,
69 W: AsyncWrite + Unpin + Send,
70{
71 async fn execute(&mut self, action: &Action, revoked: &CancellationToken) -> Result<Observation> {
72 ensure!(self.usable, "browser runner exchange has ended");
73 ensure!(!revoked.is_cancelled(), "browser control was revoked");
74 let mut frame = serde_json::to_vec(&encode_action(action)?)?;
75 ensure!(frame.len() <= MAX_ACTION_BYTES, "browser action exceeded its request budget");
76 frame.push(b'\n');
77
78 self.usable = false;
81 let observation = tokio::select! {
82 biased;
83 _ = revoked.cancelled() => bail!("browser control was revoked"),
84 result = async {
85 self.commands.write_all(&frame).await.context("could not write browser action")?;
86 self.commands.flush().await.context("could not flush browser action")?;
87 decode_observation(action, &self.read_reply().await?)
88 } => result?,
89 };
90 ensure!(!revoked.is_cancelled(), "browser control was revoked");
91 self.usable = true;
92 Ok(observation)
93 }
94}
95
96fn decode_observation(action: &Action, reply: &Value) -> Result<Observation> {
97 match (action, reply.get("kind").and_then(Value::as_str)) {
98 (Action::Screenshot | Action::Zoom { .. }, Some("screenshot")) => {
99 let data = reply
100 .get("data")
101 .and_then(Value::as_str)
102 .context("browser runner omitted screenshot data")?;
103 let bytes = STANDARD.decode(data).context("invalid browser screenshot encoding")?;
104 Ok(Observation::Screenshot(Screenshot::png(bytes)?))
105 }
106 (Action::CursorPosition, Some("cursor_position")) => {
107 let coordinate = |field| {
108 reply
109 .get(field)
110 .and_then(Value::as_u64)
111 .and_then(|value| u32::try_from(value).ok())
112 };
113 let x = coordinate("x").context("invalid browser cursor x")?;
114 let y = coordinate("y").context("invalid browser cursor y")?;
115 Ok(Observation::CursorPosition(Point { x, y }))
116 }
117 (_, Some("failed")) => bail!("browser runner refused the action"),
118 (Action::Screenshot | Action::Zoom { .. } | Action::CursorPosition, _) => {
119 bail!("browser runner returned an unexpected observation")
120 }
121 (_, Some("done")) => Ok(Observation::Done),
122 _ => bail!("browser runner returned an unexpected observation"),
123 }
124}
125
126fn point(Point { x, y }: Point) -> Value {
127 json!({ "x": x, "y": y })
128}
129
130fn encode_action(action: &Action) -> Result<Value> {
131 Ok(match action {
132 Action::Screenshot => json!({"kind":"screenshot"}),
133 Action::Zoom { top_left, bottom_right } => {
134 json!({"kind":"zoom", "top_left":point(*top_left), "bottom_right":point(*bottom_right)})
135 }
136 Action::Click { at, button, count, modifiers } => {
137 let button = match button {
138 MouseButton::Left => "left",
139 MouseButton::Middle => "middle",
140 MouseButton::Right => "right",
141 MouseButton::Back | MouseButton::Forward => bail!("browser does not deliver navigation mouse buttons"),
142 };
143 json!({"kind":"click", "at": at.map(point), "button":button, "count":count, "modifiers":modifiers})
144 }
145 Action::Drag { path, modifiers } => {
146 json!({"kind":"drag", "path":path.iter().copied().map(point).collect::<Vec<_>>(), "modifiers":modifiers})
147 }
148 Action::Move { at, modifiers } => json!({"kind":"move", "at":point(*at), "modifiers":modifiers}),
149 Action::ScrollPixels { at, x, y, modifiers } => {
150 json!({"kind":"scroll_pixels", "at":point(*at), "x":x, "y":y, "modifiers":modifiers})
151 }
152 Action::ScrollTicks { at, direction, amount, modifiers } => {
153 let direction = match direction {
154 ScrollDirection::Up => "up",
155 ScrollDirection::Down => "down",
156 ScrollDirection::Left => "left",
157 ScrollDirection::Right => "right",
158 };
159 json!({"kind":"scroll_ticks", "at":at.map(point), "direction":direction, "amount":amount, "modifiers":modifiers})
160 }
161 Action::Key { keys, repeat } => json!({"kind":"key", "keys":keys, "repeat":repeat}),
162 Action::HoldKey { keys, duration } => {
163 json!({"kind":"hold_key", "keys":keys, "milliseconds":bounded_milliseconds(*duration)?})
164 }
165 Action::LeftMouseDown => json!({"kind":"left_mouse_down"}),
166 Action::LeftMouseUp => json!({"kind":"left_mouse_up"}),
167 Action::CursorPosition => json!({"kind":"cursor_position"}),
168 Action::Type(text) => json!({"kind":"type", "text":text}),
169 Action::Wait(duration) => json!({"kind":"wait", "milliseconds":bounded_milliseconds(*duration)?}),
170 })
171}
172
173fn bounded_milliseconds(duration: Duration) -> Result<u64> {
174 ensure!(duration <= Duration::from_secs(300), "browser action duration exceeded its limit");
175 u64::try_from(duration.as_millis()).context("invalid browser action duration")
176}
177
178#[cfg(test)]
179mod tests;