viewpoint_core/page/evaluate/wait/
mod.rs1use std::time::Duration;
6
7use serde::Serialize;
8use tracing::{debug, instrument};
9use viewpoint_cdp::protocol::runtime::{EvaluateParams, EvaluateResult, ReleaseObjectParams};
10
11use crate::error::PageError;
12use crate::page::Page;
13
14use super::{wrap_expression, JsHandle, DEFAULT_TIMEOUT};
15
16#[derive(Debug, Clone, Copy, Default)]
18pub enum Polling {
19 #[default]
21 Raf,
22 Interval(Duration),
24}
25
26#[derive(Debug)]
28pub struct WaitForFunctionBuilder<'a> {
29 page: &'a Page,
30 expression: String,
31 arg: Option<serde_json::Value>,
32 timeout: Duration,
33 polling: Polling,
34}
35
36impl<'a> WaitForFunctionBuilder<'a> {
37 pub(crate) fn new(page: &'a Page, expression: String) -> Self {
39 Self {
40 page,
41 expression,
42 arg: None,
43 timeout: DEFAULT_TIMEOUT,
44 polling: Polling::default(),
45 }
46 }
47
48 #[must_use]
50 pub fn arg<A: Serialize>(mut self, arg: A) -> Self {
51 self.arg = serde_json::to_value(arg).ok();
52 self
53 }
54
55 #[must_use]
57 pub fn timeout(mut self, timeout: Duration) -> Self {
58 self.timeout = timeout;
59 self
60 }
61
62 #[must_use]
64 pub fn polling(mut self, polling: Polling) -> Self {
65 self.polling = polling;
66 self
67 }
68
69 #[instrument(level = "debug", skip(self), fields(expression = %self.expression, timeout_ms = self.timeout.as_millis()))]
73 pub async fn wait(self) -> Result<JsHandle, PageError> {
74 if self.page.closed {
75 return Err(PageError::Closed);
76 }
77
78 let start = std::time::Instant::now();
79
80 debug!("Starting wait_for_function polling with {:?}", self.polling);
81
82 loop {
83 if start.elapsed() >= self.timeout {
84 return Err(PageError::EvaluationFailed(format!(
85 "Timeout {}ms exceeded waiting for function",
86 self.timeout.as_millis()
87 )));
88 }
89
90 let result = self.try_evaluate().await?;
92
93 if result.is_truthy {
94 debug!("Function returned truthy value");
95 return Ok(result.handle.expect("truthy result has handle"));
96 }
97
98 match self.polling {
100 Polling::Raf => {
101 tokio::time::sleep(Duration::from_millis(16)).await;
103 }
104 Polling::Interval(duration) => {
105 tokio::time::sleep(duration).await;
106 }
107 }
108 }
109 }
110
111 async fn try_evaluate(&self) -> Result<TryResult, PageError> {
113 let expression = if let Some(ref arg) = self.arg {
114 let arg_json = serde_json::to_string(arg)
115 .map_err(|e| PageError::EvaluationFailed(e.to_string()))?;
116 format!("({})({})", self.expression, arg_json)
117 } else {
118 wrap_expression(&self.expression)
119 };
120
121 let params = EvaluateParams {
122 expression,
123 object_group: Some("viewpoint-wait".to_string()),
124 include_command_line_api: None,
125 silent: Some(false),
126 context_id: None,
127 return_by_value: Some(false),
128 await_promise: Some(true),
129 };
130
131 let result: EvaluateResult = self
132 .page
133 .connection
134 .send_command(
135 "Runtime.evaluate",
136 Some(params),
137 Some(&self.page.session_id),
138 )
139 .await?;
140
141 if let Some(exception) = result.exception_details {
142 return Err(PageError::EvaluationFailed(exception.text));
143 }
144
145 let is_truthy = is_truthy_result(&result.result);
147
148 let handle = if is_truthy {
149 result.result.object_id.map(|id| {
150 JsHandle::new(id, self.page.session_id.clone(), self.page.connection.clone())
151 })
152 } else {
153 if let Some(object_id) = result.result.object_id {
155 let _ = self
156 .page
157 .connection
158 .send_command::<_, serde_json::Value>(
159 "Runtime.releaseObject",
160 Some(ReleaseObjectParams { object_id }),
161 Some(&self.page.session_id),
162 )
163 .await;
164 }
165 None
166 };
167
168 Ok(TryResult { is_truthy, handle })
169 }
170}
171
172struct TryResult {
173 is_truthy: bool,
174 handle: Option<JsHandle>,
175}
176
177fn is_truthy_result(result: &viewpoint_cdp::protocol::runtime::RemoteObject) -> bool {
179 match result.object_type.as_str() {
181 "undefined" => false,
182 "object" => {
183 result.subtype.as_deref() != Some("null")
185 }
186 "boolean" => result
187 .value
188 .as_ref()
189 .and_then(serde_json::Value::as_bool)
190 .unwrap_or(false),
191 "number" => result
192 .value
193 .as_ref()
194 .and_then(serde_json::Value::as_f64)
195 .is_some_and(|n| n != 0.0 && !n.is_nan()),
196 "string" => result
197 .value
198 .as_ref()
199 .and_then(|v| v.as_str())
200 .is_some_and(|s| !s.is_empty()),
201 _ => {
202 true
204 }
205 }
206}
207
208impl Page {
209 pub fn wait_for_function(&self, expression: impl Into<String>) -> WaitForFunctionBuilder<'_> {
240 WaitForFunctionBuilder::new(self, expression.into())
241 }
242
243 pub fn wait_for_function_with_arg<A: Serialize>(
245 &self,
246 expression: impl Into<String>,
247 arg: A,
248 ) -> WaitForFunctionBuilder<'_> {
249 WaitForFunctionBuilder::new(self, expression.into()).arg(arg)
250 }
251}