Skip to main content

rightkit_browser/
act.rs

1//! Acting on observed refs: one action, then the diff it caused; and the action-loop watchdog.
2//!
3//! The ref check itself (epoch, replaced frame, tag, role and name must still match) lives in
4//! `page.rs` beside `observe`. This module holds the types of [`BrowserPage::act`](crate::BrowserPage::act)
5//! and the repeat counter that stops a run which keeps doing the same thing to the same element with no
6//! visible effect.
7
8use crate::error::{BrowserError, Result};
9use crate::page::ObservedNode;
10use crate::policy::ActionKind;
11use serde::Serialize;
12use std::collections::hash_map::DefaultHasher;
13use std::hash::{Hash, Hasher};
14
15/// How many times the same action may run on the same ref with no diff before the next one is refused.
16pub const DEFAULT_ACTION_LOOP_LIMIT: u32 = 5;
17
18/// The one action [`BrowserPage::act`](crate::BrowserPage::act) runs on a ref.
19#[derive(Clone, Debug, PartialEq)]
20pub enum RefAction {
21    Click,
22    DoubleClick,
23    Hover,
24    /// Click to focus, optionally select-all and delete, then type.
25    Fill {
26        text: String,
27        clear: bool,
28    },
29    /// Choose a `<select>` option by value or label.
30    SelectOption {
31        value: String,
32    },
33}
34
35impl RefAction {
36    /// The admission kind and detail for this action. A fill reports its length, never its text.
37    pub(crate) fn admission(&self) -> (ActionKind, Option<String>) {
38        match self {
39            RefAction::Click => (ActionKind::Click, None),
40            RefAction::DoubleClick => (ActionKind::DoubleClick, None),
41            RefAction::Hover => (ActionKind::Hover, None),
42            RefAction::Fill { text, clear } => (
43                ActionKind::Fill,
44                Some(format!("chars={} clear={clear}", text.chars().count())),
45            ),
46            RefAction::SelectOption { value } => {
47                (ActionKind::Select, Some(format!("value={value}")))
48            }
49        }
50    }
51
52    /// What the watchdog compares: the action, its ref and a hash of any text (the text itself is not kept).
53    pub(crate) fn watch_key(&self, node_ref: &str) -> String {
54        let what = match self {
55            RefAction::Click => "click".to_string(),
56            RefAction::DoubleClick => "double_click".to_string(),
57            RefAction::Hover => "hover".to_string(),
58            RefAction::Fill { text, clear } => format!("fill:{clear}:{}", hash_of(text)),
59            RefAction::SelectOption { value } => format!("select:{}", hash_of(value)),
60        };
61        format!("{node_ref}|{what}")
62    }
63}
64
65fn hash_of(text: &str) -> u64 {
66    let mut h = DefaultHasher::new();
67    text.hash(&mut h);
68    h.finish()
69}
70
71/// What an observed element looked like. Names of password-like fields are already masked.
72#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
73pub struct NodeState {
74    pub role: String,
75    pub name: String,
76    pub visible: bool,
77    pub disabled: bool,
78}
79
80impl NodeState {
81    pub(crate) fn of(node: &ObservedNode) -> NodeState {
82        NodeState {
83            role: node.role.clone(),
84            name: node.name.clone(),
85            visible: node.visible,
86            disabled: node.disabled,
87        }
88    }
89}
90
91/// An element that was there before the action and is still there, but looks different.
92#[derive(Clone, Debug, Serialize)]
93pub struct NodeChange {
94    /// The element's ref in the new epoch.
95    pub node_ref: String,
96    pub selector: String,
97    pub before: NodeState,
98    pub after: NodeState,
99}
100
101/// What one action changed. Elements are matched by selector; an element with no selector (it cannot be
102/// targeted by ref) is not part of the diff.
103#[derive(Clone, Debug, Serialize)]
104pub struct ObservationDiff {
105    pub epoch_before: u64,
106    pub epoch_after: u64,
107    pub url_before: String,
108    pub url_after: String,
109    /// The main document was replaced (a navigation or reload). Every earlier ref is refused.
110    pub document_replaced: bool,
111    /// Elements that were not there before, with their refs in `epoch_after`.
112    pub added: Vec<ObservedNode>,
113    /// Selectors of elements that are gone.
114    pub removed: Vec<String>,
115    pub changed: Vec<NodeChange>,
116}
117
118impl ObservationDiff {
119    /// Nothing observable happened. This is what the watchdog counts.
120    pub fn is_empty(&self) -> bool {
121        !self.document_replaced
122            && self.url_before == self.url_after
123            && self.added.is_empty()
124            && self.removed.is_empty()
125            && self.changed.is_empty()
126    }
127}
128
129/// The result of one [`BrowserPage::act`](crate::BrowserPage::act).
130#[derive(Clone, Debug, Serialize)]
131pub struct ActResult {
132    pub page_id: String,
133    /// The ref the action ran on.
134    pub node_ref: String,
135    /// The page's epoch after the action. When it differs from `diff.epoch_before`, every earlier ref is
136    /// refused: use the refs in `diff`, or call `observe` for the whole tree.
137    pub epoch: u64,
138    pub diff: ObservationDiff,
139    /// How many times in a row this same action has now run on this same ref with no diff (0 after a diff).
140    pub repeats: u32,
141}
142
143/// Repeat counter behind the action-loop watchdog. Pure state: no page access, no clock.
144#[derive(Debug)]
145pub(crate) struct ActionWatch {
146    limit: u32,
147    last: Option<String>,
148    repeats: u32,
149    stopped: bool,
150}
151
152impl Default for ActionWatch {
153    fn default() -> Self {
154        ActionWatch {
155            limit: DEFAULT_ACTION_LOOP_LIMIT,
156            last: None,
157            repeats: 0,
158            stopped: false,
159        }
160    }
161}
162
163impl ActionWatch {
164    /// `limit` must be at least 1.
165    pub(crate) fn set_limit(&mut self, limit: u32) -> Result<()> {
166        if limit == 0 {
167            return Err(BrowserError::Invalid(
168                "the action-loop limit must be at least 1".into(),
169            ));
170        }
171        self.limit = limit;
172        Ok(())
173    }
174
175    /// Clear the count and the stop latch (a person or the host decided the run may go on).
176    pub(crate) fn reset(&mut self) {
177        self.last = None;
178        self.repeats = 0;
179        self.stopped = false;
180    }
181
182    /// Called before an action runs. Refuses it when the run is stopped, or when it would be the
183    /// `limit + 1`th identical no-diff action; the second case stops the run until `reset`.
184    pub(crate) fn before(&mut self, key: &str) -> Result<()> {
185        if self.stopped {
186            return Err(BrowserError::ActionLoop(format!(
187                "the run was stopped after {} identical actions with no effect",
188                self.limit
189            )));
190        }
191        if self.last.as_deref() == Some(key) && self.repeats >= self.limit {
192            self.stopped = true;
193            return Err(BrowserError::ActionLoop(format!(
194                "the same action on the same element ran {} times with no effect",
195                self.repeats
196            )));
197        }
198        Ok(())
199    }
200
201    /// Called after an action ran. `no_effect` is true for an empty diff or a failed action. Returns the
202    /// consecutive repeat count.
203    pub(crate) fn after(&mut self, key: String, no_effect: bool) -> u32 {
204        if !no_effect {
205            self.last = None;
206            self.repeats = 0;
207        } else if self.last.as_deref() == Some(key.as_str()) {
208            self.repeats = self.repeats.saturating_add(1);
209        } else {
210            self.last = Some(key);
211            self.repeats = 1;
212        }
213        self.repeats
214    }
215}