nexo_plugin_browser/
plugin.rs1use std::sync::Arc;
27use std::time::Duration;
28
29use base64::Engine;
30use tokio::sync::Mutex;
31
32use nexo_cdp::{CdpClient, CdpSession};
33use nexo_config::BrowserConfig;
34
35use crate::chrome::{ChromeLauncher, RunningChrome};
36use crate::command::{BrowserCmd, BrowserResult};
37
38pub struct BrowserPlugin {
42 inner: Arc<BrowserInner>,
43}
44
45struct BrowserInner {
46 config: BrowserConfig,
47 session: Mutex<Option<CdpSession>>,
48 chrome: Mutex<Option<RunningChrome>>,
49}
50
51impl BrowserPlugin {
52 pub fn new(config: BrowserConfig) -> Self {
53 Self {
54 inner: Arc::new(BrowserInner {
55 config,
56 session: Mutex::new(None),
57 chrome: Mutex::new(None),
58 }),
59 }
60 }
61
62 pub async fn execute(&self, cmd: BrowserCmd) -> BrowserResult {
67 if let Err(e) = self.inner.ensure_session().await {
68 return BrowserResult::err(format!("session init failed: {e}"));
69 }
70 let mut lock = self.inner.session.lock().await;
71 let Some(session) = lock.as_mut() else {
72 return BrowserResult::err("no active session");
73 };
74 let timeout = Duration::from_millis(self.inner.config.command_timeout_ms);
75 match cmd {
76 BrowserCmd::Navigate { url } => {
77 match tokio::time::timeout(timeout, session.navigate(&url)).await {
78 Ok(Ok(())) => BrowserResult::ok(),
79 Ok(Err(e)) => BrowserResult::err(e.to_string()),
80 Err(_) => BrowserResult::err("navigate timed out"),
81 }
82 }
83 BrowserCmd::Click { target } => {
84 match tokio::time::timeout(timeout, session.click(&target)).await {
85 Ok(Ok(())) => BrowserResult::ok(),
86 Ok(Err(e)) => BrowserResult::err(e.to_string()),
87 Err(_) => BrowserResult::err("click timed out"),
88 }
89 }
90 BrowserCmd::Fill { target, value } => {
91 match tokio::time::timeout(timeout, session.fill(&target, &value)).await {
92 Ok(Ok(())) => BrowserResult::ok(),
93 Ok(Err(e)) => BrowserResult::err(e.to_string()),
94 Err(_) => BrowserResult::err("fill timed out"),
95 }
96 }
97 BrowserCmd::Screenshot => {
98 match tokio::time::timeout(timeout, session.screenshot()).await {
99 Ok(Ok(bytes)) => {
100 let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
101 BrowserResult::ok_screenshot(b64)
102 }
103 Ok(Err(e)) => BrowserResult::err(e.to_string()),
104 Err(_) => BrowserResult::err("screenshot timed out"),
105 }
106 }
107 BrowserCmd::Evaluate { script } => {
108 match tokio::time::timeout(timeout, session.evaluate(&script)).await {
109 Ok(Ok(v)) => BrowserResult::ok_value(v),
110 Ok(Err(e)) => BrowserResult::err(e.to_string()),
111 Err(_) => BrowserResult::err("evaluate timed out"),
112 }
113 }
114 BrowserCmd::Snapshot => {
115 match tokio::time::timeout(timeout, session.snapshot()).await {
116 Ok(Ok(text)) => BrowserResult::ok_snapshot(text),
117 Ok(Err(e)) => BrowserResult::err(e.to_string()),
118 Err(_) => BrowserResult::err("snapshot timed out"),
119 }
120 }
121 BrowserCmd::ScrollTo { target } => {
122 match tokio::time::timeout(timeout, session.scroll_to(&target)).await {
123 Ok(Ok(())) => BrowserResult::ok(),
124 Ok(Err(e)) => BrowserResult::err(e.to_string()),
125 Err(_) => BrowserResult::err("scroll_to timed out"),
126 }
127 }
128 }
129 }
130}
131
132impl BrowserPlugin {
133 pub async fn shutdown_chrome(&self) {
146 let mut session = self.inner.session.lock().await;
147 *session = None;
148 drop(session);
149 let mut chrome = self.inner.chrome.lock().await;
150 *chrome = None;
151 }
152}
153
154impl BrowserInner {
155 async fn ensure_session(self: &Arc<Self>) -> anyhow::Result<()> {
156 let mut session_lock = self.session.lock().await;
157 if session_lock.is_some() {
158 return Ok(());
159 }
160
161 let ws_url = if self.config.cdp_url.is_empty() {
162 let chrome = ChromeLauncher::launch(&self.config).await?;
163 let ws = chrome.ws_url.clone();
164 *self.chrome.lock().await = Some(chrome);
165 ws
166 } else {
167 ChromeLauncher::connect_existing(&self.config.cdp_url, self.config.connect_timeout_ms)
168 .await?
169 };
170
171 let client = Arc::new(CdpClient::connect(&ws_url).await?);
172
173 if let Err(e) = client.send("Page.enable", serde_json::json!({})).await {
174 tracing::warn!(error = %e, "Page.enable failed — navigation events may be missing");
175 }
176
177 let target_id = get_first_target_id(&ws_url, self.config.connect_timeout_ms).await?;
178 let session = CdpSession::new(
179 Arc::clone(&client),
180 &target_id,
181 self.config.command_timeout_ms,
182 )
183 .await?;
184 *session_lock = Some(session);
185 Ok(())
186 }
187}
188
189async fn get_first_target_id(ws_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
190 let http_url = ws_url
191 .replace("ws://", "http://")
192 .replace("wss://", "https://");
193 let base = if let Some(idx) = http_url.find("/devtools/") {
194 http_url[..idx].to_string()
195 } else {
196 http_url
197 };
198
199 let client = reqwest::Client::builder()
200 .timeout(std::time::Duration::from_millis(timeout_ms))
201 .build()?;
202 let targets: Vec<serde_json::Value> = client
203 .get(format!("{base}/json/list"))
204 .header(reqwest::header::HOST, "localhost")
205 .send()
206 .await?
207 .json()
208 .await?;
209
210 targets
211 .iter()
212 .find(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"))
213 .and_then(|t| t.get("id").and_then(|v| v.as_str()))
214 .map(|s| s.to_string())
215 .ok_or_else(|| anyhow::anyhow!("no page target found in Chrome"))
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 fn test_config() -> BrowserConfig {
223 BrowserConfig {
224 headless: true,
225 executable: String::new(),
226 cdp_url: String::new(),
227 user_data_dir: "./.test-profile".into(),
228 window_width: 1280,
229 window_height: 800,
230 connect_timeout_ms: 8_000,
231 command_timeout_ms: 30_000,
232 args: Vec::new(),
233 }
234 }
235
236 #[tokio::test]
237 async fn shutdown_chrome_is_idempotent_on_fresh_plugin() {
238 let plugin = BrowserPlugin::new(test_config());
242 plugin.shutdown_chrome().await;
243 plugin.shutdown_chrome().await; }
245}
246