eoka 0.12.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use std::{
    sync::{atomic::Ordering, Arc},
    time::Duration,
};

use serde_json::Value;
use tokio::sync::{broadcast, OwnedMutexGuard};

use super::{
    dispatch::Dispatch,
    locator::resolve,
    perform::{self, Verification},
    *,
};
use crate::{
    cdp::transport::CdpMessage,
    error::classify::{cdp_failure, CdpFailure},
    page::ActionInput,
    Error, ErrorCode, Page, Result,
};

/// How long a filled value must stay unchanged and wrong before fill reports
/// [`Error::ValueMismatch`].
const VALUE_SETTLE: Duration = Duration::from_millis(750);

struct Cleanup {
    gate: Option<OwnedMutexGuard<()>>,
    input: Option<ActionInput>,
    state: Arc<ActionState>,
    dispatch: Arc<Dispatch>,
}

impl Drop for Cleanup {
    fn drop(&mut self) {
        let Some(mut input) = self.input.take() else {
            return;
        };
        if self.dispatch.state() == DispatchState::NotSent {
            input.discard_unsent_reservations();
        }
        if !input.has_held_input() {
            return;
        }
        let gate = self.gate.take();
        let state = self.state.clone();
        state.cleanup_failed.store(true, Ordering::Release);
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            runtime.spawn(async move {
                let succeeded = matches!(
                    tokio::time::timeout(Duration::from_secs(5), input.cleanup()).await,
                    Ok(Ok(()))
                );
                state.cleanup_failed.store(!succeeded, Ordering::Release);
                drop(input);
                drop(gate);
            });
        }
    }
}

impl Page {
    /// Resolve, prepare and execute an action once, then verify its result.
    /// The returned error retains a receipt when completion is uncertain.
    pub async fn act(&self, action: Action, options: ActionOptions) -> Result<ActionReceipt> {
        self.run_action(action, options, false).await
    }

    /// Execute one exploratory action with the same actionability and deadline checks.
    /// Without intrinsic or caller-supplied completion evidence, successful dispatch
    /// returns `Ok` with `ActionOutcome::OutcomeUnknown`, never verified completion.
    pub async fn explore(&self, action: Action, options: ActionOptions) -> Result<ActionReceipt> {
        self.run_action(action, options, true).await
    }

    async fn run_action(
        &self,
        action: Action,
        options: ActionOptions,
        exploratory: bool,
    ) -> Result<ActionReceipt> {
        let started = tokio::time::Instant::now();
        let dispatch = Arc::new(Dispatch::new(options.observer.clone()));
        let mut receipt = ActionReceipt {
            destination_target_id: None,
            started_at_ms: timestamp(),
            finished_at_ms: 0,
            download_guid: None,
            action: action.kind().into(),
            target_id: self.target_id().into(),
            outcome: ActionOutcome::NotDispatched,
            dispatch: DispatchState::NotSent,
            preparation_may_have_executed: false,
            verification: None,
            elapsed_ms: 0,
            already_satisfied: false,
            cleanup_pending: false,
        };
        let state = self.session().action_state();
        let mut cleanup = Cleanup {
            gate: None,
            input: None,
            state: state.clone(),
            dispatch: dispatch.clone(),
        };
        let execution = async {
            if options.timeout_ms == 0 || options.timeout_ms > MAX_ACTION_TIMEOUT_MS {
                return Err(Error::coded(
                    ErrorCode::InvalidTimeout,
                    format!("action timeout must be between 1 and {MAX_ACTION_TIMEOUT_MS}ms"),
                ));
            }
            if action.requires_expectation() && options.expect.is_none() && !exploratory {
                return Err(Error::coded(
                    ErrorCode::ExpectationRequired,
                    "action requires an expected result",
                ));
            }
            cleanup.gate = Some(state.gate.clone().lock_owned().await);
            if state.cleanup_failed.load(Ordering::Acquire) {
                return Err(Error::input_state(
                    "Previous action input cleanup failed; release_all_inputs is required",
                ));
            }
            if let Some(expect) = &options.expect {
                validate_expectation(expect, 0)?;
                if options.destination != Destination::NewTab
                    && self.check_expectation(expect).await?
                {
                    return Err(Error::coded(
                        ErrorCode::ExpectationAlreadySatisfied,
                        "choose a condition that proves a new result",
                    ));
                }
            }
            let mut destination_watch = if options.destination != Destination::Current
                && options
                    .expect
                    .as_ref()
                    .is_some_and(|e| !matches!(e, Expectation::DownloadStarted))
            {
                Some(super::destination::DestinationWatch::begin(self, options.destination).await?)
            } else {
                None
            };
            dispatch.note("preparation");
            cleanup.input = Some(ActionInput::acquire(self.session()).await?);
            let download_frames = if matches!(options.expect, Some(Expectation::DownloadStarted)) {
                self.frames()
                    .await?
                    .into_iter()
                    .map(|f| f.id)
                    .collect::<Vec<_>>()
            } else {
                Vec::new()
            };
            let main = self.session().get_frame_tree().await?.frame;
            let (main_frame, previous_loader) = (main.id, main.loader_id);
            let mut events = self.session().transport().subscribe();
            let (node, verification) = loop {
                let attempt = async {
                    let mut node =
                        perform::prepare(self, &action, &dispatch, options.wait_for_target).await?;
                    if matches!(action, Action::Hover { .. }) {
                        if let Some(node) = node.as_mut() {
                            node.arm_hover().await?;
                        }
                    }
                    let verification = perform::perform(
                        self,
                        &action,
                        node.as_ref(),
                        cleanup
                            .input
                            .as_mut()
                            .ok_or_else(|| Error::cdp_msg("Action input missing"))?,
                        &dispatch,
                    )
                    .await?;

                    Ok((node, verification))
                }
                .await;
                match attempt {
                    Ok(result) => break result,
                    Err(error)
                        if options.wait_for_target
                            && dispatch.state() == DispatchState::NotSent
                            && perform::retryable_preparation(&action, &error) =>
                    {
                        perform::pause().await;
                    }
                    Err(error) => return Err(error),
                }
            };

            receipt.already_satisfied = matches!(verification, Verification::Noop);
            dispatch.note("verification");
            match verification {
                Verification::Properties { field, expected } => {
                    // A control that settles on another value (input masks,
                    // maxlength, trimming) will never match; report that
                    // once the value has been stable for a while instead of
                    // waiting out the deadline.
                    let mut settled: Option<(Value, tokio::time::Instant)> = None;
                    loop {
                        if let Some(node) = node.as_ref() {
                            let properties = node.properties().await?;
                            if properties["connected"] != true {
                                return Err(Error::coded(
                                    ErrorCode::TargetStale,
                                    "target detached after dispatch",
                                ));
                            }
                            let actual = super::locator::Node::property(&properties, field);
                            if actual == expected {
                                break;
                            }
                            if field == "value" {
                                match &settled {
                                    Some((value, since)) if *value == actual => {
                                        if since.elapsed() >= VALUE_SETTLE {
                                            return Err(value_mismatch(
                                                &action, &expected, &actual,
                                            ));
                                        }
                                    }
                                    _ => settled = Some((actual, tokio::time::Instant::now())),
                                }
                            }
                        }
                        perform::pause().await;
                    }
                    receipt.verification = Some(field.into());
                }
                Verification::Navigation { .. } | Verification::NavigationAborted { .. }
                    if matches!(options.expect, Some(Expectation::DownloadStarted)) => {}
                Verification::NavigationAborted { download } => {
                    return Err(Error::coded(
                        ErrorCode::NavigationAborted,
                        if download {
                            "the navigation became a download; expect DownloadStarted to wait for it"
                        } else {
                            "Chrome aborted the navigation before it committed"
                        },
                    ));
                }
                Verification::Navigation { loader } => {
                    loop {
                        let event = match events.recv().await {
                            Ok(event) => event,
                            // Busy pages can outrun the shared event buffer.
                            // The commit may be among the dropped events, so
                            // check the main frame's loader instead of failing.
                            Err(broadcast::error::RecvError::Lagged(skipped)) => {
                                tracing::debug!(skipped, "navigation events lagged");
                                let current = self.session().get_frame_tree().await?.frame;
                                match committed_after_lag(
                                    loader.as_deref(),
                                    previous_loader.as_deref(),
                                    current.loader_id.as_deref(),
                                ) {
                                    Some(true) => break,
                                    Some(false) => continue,
                                    None => {
                                        return Err(Error::transport(format!(
                                            "Navigation events lagged by {skipped}; commit unknown"
                                        )))
                                    }
                                }
                            }
                            Err(error @ broadcast::error::RecvError::Closed) => {
                                return Err(Error::transport_io(
                                    "Navigation event stream lost",
                                    std::io::Error::other(error),
                                ));
                            }
                        };
                        if let CdpMessage::Event {
                            method,
                            params,
                            session_id,
                        } = &*event
                        {
                            if session_id.as_deref() != Some(self.session().session_id()) {
                                continue;
                            }
                            if (method == "Page.frameNavigated"
                                && params["frame"]["parentId"].is_null()
                                && loader
                                    .as_ref()
                                    .is_none_or(|id| params["frame"]["loaderId"] == *id))
                                || (method == "Page.navigatedWithinDocument"
                                    && loader.is_none()
                                    && params["frameId"] == main_frame)
                            {
                                break;
                            }
                        }
                    }
                    self.invalidate_document();
                    while !self.check_settling(&Expectation::DocumentReady).await? {
                        perform::pause().await;
                    }
                    receipt.verification = Some("document_ready".into());
                }
                Verification::Noop => {
                    receipt.verification = Some("already_satisfied".into());
                }
                Verification::Explicit => {}
            }
            if let Some(Expectation::DownloadStarted) = &options.expect {
                loop {
                    match &*events.recv().await.map_err(|error| {
                        Error::transport_io(
                            "Download event stream lost",
                            std::io::Error::other(error),
                        )
                    })? {
                        CdpMessage::Event { method, params, .. }
                            if method == "Browser.downloadWillBegin"
                                && params["frameId"]
                                    .as_str()
                                    .is_some_and(|id| download_frames.iter().any(|f| f == id)) =>
                        {
                            receipt.download_guid = params["guid"].as_str().map(str::to_owned);
                            receipt.verification = Some("download_started".into());
                            break;
                        }
                        _ => {}
                    }
                }
            } else if let Some(expect) = &options.expect {
                loop {
                    let target = if let Some(watch) = destination_watch.as_mut() {
                        watch.check(expect).await?
                    } else if self.check_settling(expect).await? {
                        Some(self.target_id().into())
                    } else {
                        None
                    };
                    if let Some(target) = target {
                        receipt.destination_target_id = Some(target);
                        break;
                    }
                    perform::pause().await;
                }
                receipt.verification = Some(expect.kind().into());
            }
            cleanup
                .input
                .as_mut()
                .ok_or_else(|| Error::cdp_msg("Action input missing"))?
                .cleanup()
                .await?;
            cleanup.input.take();
            receipt.outcome = if receipt.verification.is_some() {
                ActionOutcome::VerifiedComplete
            } else {
                ActionOutcome::OutcomeUnknown
            };
            Ok(())
        };
        let result = tokio::time::timeout(
            Duration::from_millis(options.timeout_ms.min(MAX_ACTION_TIMEOUT_MS)),
            execution,
        )
        .await
        .unwrap_or_else(|_| {
            Err(Error::timeout(format!(
                "Action deadline exceeded during {}",
                dispatch.context()
            )))
        });
        receipt.finished_at_ms = timestamp();
        receipt.elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
        receipt.dispatch = dispatch.state();
        receipt.preparation_may_have_executed = dispatch.prepared();
        match result {
            Ok(()) => Ok(receipt),
            Err(source) => {
                receipt.outcome = if receipt.dispatch == DispatchState::NotSent {
                    ActionOutcome::NotDispatched
                } else {
                    ActionOutcome::OutcomeUnknown
                };
                receipt.cleanup_pending = dispatch.state() != DispatchState::NotSent
                    && cleanup
                        .input
                        .as_ref()
                        .is_some_and(ActionInput::has_held_input);
                let code = action_code(&source);
                Err(Error::Action {
                    code,
                    receipt: Box::new(receipt),
                    source: Box::new(source),
                })
            }
        }
    }

    pub(super) async fn check_expectation(&self, expect: &Expectation) -> Result<bool> {
        let (target, field, expected, contains) = match expect {
            Expectation::DocumentReady => return self
                .evaluate_sync(
                    "document.readyState === 'interactive' || document.readyState === 'complete'",
                )
                .await,
            Expectation::All { conditions } => {
                if conditions.is_empty() {
                    return Err(Error::coded(
                        ErrorCode::InvalidExpectation,
                        "all requires at least one condition",
                    ));
                }
                for condition in conditions {
                    if !Box::pin(self.check_expectation(condition)).await? {
                        return Ok(false);
                    }
                }
                return Ok(true);
            }
            Expectation::Enabled { target, enabled } => {
                (target, "disabled", Value::Bool(!enabled), false)
            }
            Expectation::DownloadStarted => return Ok(false),
            Expectation::Focused { target } => (target, "focused", Value::Bool(true), false),
            Expectation::Url { value, contains } => {
                let url = self.url().await?;
                return Ok(if *contains {
                    url.contains(value)
                } else {
                    url == *value
                });
            }
            Expectation::Visible { target } => (target, "visible", Value::Bool(true), false),
            Expectation::Hidden { target } => (target, "visible", Value::Bool(false), false),
            Expectation::Text {
                target,
                value,
                contains,
            } => (target, "text", Value::String(value.clone()), *contains),
            Expectation::Value { target, value } => {
                (target, "value", Value::String(value.clone()), false)
            }
            Expectation::Checked { target, checked } => {
                (target, "checked", Value::Bool(*checked), false)
            }
            Expectation::Selected { target, values } => {
                let mut values = values.clone();
                values.sort();
                values.dedup();
                (target, "selected", serde_json::json!(values), false)
            }
        };
        let Some(node) = resolve(self, target).await? else {
            return Ok(matches!(expect, Expectation::Hidden { .. }));
        };
        let properties = node.properties().await?;
        if matches!(expect, Expectation::Enabled { .. }) && properties["visible"] != true {
            return Ok(false);
        }
        let actual = super::locator::Node::property(&properties, field);
        Ok(if contains {
            actual
                .as_str()
                .is_some_and(|text| text.contains(expected.as_str().unwrap_or_default()))
        } else {
            actual == expected
        })
    }

    /// Checks an expectation after dispatch. Input often starts a navigation,
    /// which destroys the context the check runs in; that means "not yet",
    /// not failure, because the next document may satisfy it.
    async fn check_settling(&self, expect: &Expectation) -> Result<bool> {
        match self.check_expectation(expect).await {
            Err(error)
                if matches!(
                    cdp_failure(&error),
                    Some(CdpFailure::ContextLost | CdpFailure::NodeGone)
                ) =>
            {
                tracing::debug!("expectation check raced a document change: {error}");
                Ok(false)
            }
            result => result,
        }
    }

    /// Wait for observable page state without dispatching input or replaying an action.
    ///
    /// The timeout must be between 1ms and 24h; a sub-millisecond remainder
    /// rounds up to a whole millisecond.
    pub async fn wait_for_expectation(
        &self,
        expectation: &Expectation,
        timeout: Duration,
    ) -> Result<()> {
        let timeout_ms = super::types::duration_to_ms(timeout);
        validate_expectation(expectation, 0)?;
        if timeout_ms == 0 || timeout_ms > MAX_ACTION_TIMEOUT_MS {
            return Err(Error::coded(
                ErrorCode::InvalidTimeout,
                format!("observation timeout must be between 1 and {MAX_ACTION_TIMEOUT_MS}ms"),
            ));
        }
        if matches!(expectation, Expectation::DownloadStarted) {
            return Err(Error::coded(
                ErrorCode::InvalidExpectation,
                "download_started cannot be observed without an action",
            ));
        }
        tokio::time::timeout(Duration::from_millis(timeout_ms), async {
            while !self.check_expectation(expectation).await? {
                perform::pause().await;
            }
            Ok(())
        })
        .await
        .map_err(|_| Error::timeout("Page expectation was not satisfied"))?
    }
}

fn value_mismatch(action: &Action, expected: &Value, actual: &Value) -> Error {
    let chars = |v: &Value| v.as_str().map_or(0, |s| s.chars().count());
    Error::ValueMismatch {
        selector: action.target().map_or_else(
            || "the focused control".into(),
            |t| format!("{:?}", t.query),
        ),
        expected_chars: chars(expected),
        actual_chars: chars(actual),
    }
}

/// The stable code an action failure reports for its underlying cause.
fn action_code(source: &Error) -> ErrorCode {
    match source {
        Error::ElementNotFound(_) | Error::ElementNotVisible { .. } => ErrorCode::TargetUnavailable,
        _ => match source.code() {
            Some(ErrorCode::Timeout) => ErrorCode::ActionTimeout,
            // Not action-specific: keep reporting them as a generic failure.
            Some(
                ErrorCode::LaunchFailed
                | ErrorCode::DecodeFailed
                | ErrorCode::ChromeNotFound
                | ErrorCode::InvalidUrl
                | ErrorCode::ResultTooLarge,
            )
            | None => ErrorCode::ActionFailed,
            Some(code) => code,
        },
    }
}

fn validate_expectation(expectation: &Expectation, depth: usize) -> Result<()> {
    if depth > 8 {
        return Err(Error::coded(
            ErrorCode::InvalidExpectation,
            "nesting exceeds 8",
        ));
    }
    match expectation {
        Expectation::All { conditions } => {
            if conditions.is_empty() || conditions.len() > 16 {
                return Err(Error::coded(
                    ErrorCode::InvalidExpectation,
                    "all requires 1 through 16 conditions",
                ));
            }
            for condition in conditions {
                validate_expectation(condition, depth + 1)?;
            }
        }
        Expectation::DownloadStarted if depth > 0 => {
            return Err(Error::coded(
                ErrorCode::InvalidExpectation,
                "download_started must be a standalone event expectation",
            ))
        }
        _ => {}
    }
    Ok(())
}

fn timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|t| u64::try_from(t.as_millis()).unwrap_or(u64::MAX))
        .unwrap_or_default()
}

/// Decide from the main frame's loader whether a navigation committed after
/// its events were dropped. `None` means the commit cannot be determined.
fn committed_after_lag(
    expected: Option<&str>,
    previous: Option<&str>,
    current: Option<&str>,
) -> Option<bool> {
    match (expected, current) {
        // Page.navigate reported its loader; wait until it is current.
        (Some(expected), current) => Some(current == Some(expected)),
        // History and reload report no loader, but a new document replaces it.
        (None, Some(current)) if previous != Some(current) => Some(true),
        // A same-document entry keeps the loader: its commit is not visible.
        (None, _) => None,
    }
}

#[cfg(test)]
mod code_tests {
    use super::action_code;
    use crate::{Error, ErrorCode};

    #[test]
    fn action_codes_keep_their_pre_coded_mapping() {
        let cases = [
            (Error::timeout("x"), ErrorCode::ActionTimeout),
            (Error::input_state("x"), ErrorCode::InputState),
            (
                Error::coded(ErrorCode::NavigationFailed, "x"),
                ErrorCode::NavigationFailed,
            ),
            (
                Error::ElementNotFound("x".into()),
                ErrorCode::TargetUnavailable,
            ),
            (Error::launch("x"), ErrorCode::ActionFailed),
            (Error::decode("x"), ErrorCode::ActionFailed),
            (Error::InvalidUrl("x".into()), ErrorCode::ActionFailed),
            (Error::ChromeNotFound, ErrorCode::ActionFailed),
            (
                Error::EvaluationTooLarge { maximum_bytes: 1 },
                ErrorCode::ActionFailed,
            ),
            (Error::cdp_msg("x"), ErrorCode::ActionFailed),
        ];
        for (error, expected) in cases {
            assert_eq!(action_code(&error), expected, "{error}");
        }
    }
}

#[cfg(test)]
mod lag_tests {
    use super::committed_after_lag;

    #[test]
    fn lagged_navigation_commit_follows_the_main_frame_loader() {
        // Page.navigate: done only once its own loader is current.
        assert_eq!(
            committed_after_lag(Some("new"), Some("old"), Some("new")),
            Some(true)
        );
        assert_eq!(
            committed_after_lag(Some("new"), Some("old"), Some("old")),
            Some(false)
        );
        assert_eq!(
            committed_after_lag(Some("new"), Some("old"), None),
            Some(false)
        );
        // History/reload: a replaced document proves the commit.
        assert_eq!(
            committed_after_lag(None, Some("old"), Some("new")),
            Some(true)
        );
        // Same loader: same-document entry or not yet committed; unknown.
        assert_eq!(committed_after_lag(None, Some("old"), Some("old")), None);
        assert_eq!(committed_after_lag(None, Some("old"), None), None);
    }
}