BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / events.rs

events.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
events.rs 9.0 KiB Download Raw
1use std::collections::HashMap;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use std::time::Duration;
5
6use futures_util::{SinkExt, Stream, StreamExt};
7use serde_json::{Value, json};
8use tokio::sync::{mpsc, oneshot};
9use tokio_tungstenite::connect_async;
10use tokio_tungstenite::tungstenite::Message;
11
12use crate::error::{Error, Result};
13
14const EVALUATE_TIMEOUT: Duration = Duration::from_secs(30);
15
16#[derive(Debug, Clone, PartialEq)]
17pub struct TabEvent {
18 pub method: String,
19 pub params: Value,
20}
21
22impl TabEvent {
23 pub fn binding_payload(&self, binding_name: &str) -> Option<&str> {
24 if self.method != "Runtime.bindingCalled"
25 || self.params.get("name")?.as_str()? != binding_name
26 {
27 return None;
28 }
29 self.params.get("payload")?.as_str()
30 }
31}
32
33pub struct TabCommand {
34 pub method: String,
35 pub params: Value,
36 reply: oneshot::Sender<Result<Value>>,
37}
38
39impl TabCommand {
40 pub fn respond(self, outcome: Result<Value>) {
41 let _ = self.reply.send(outcome);
42 }
43}
44
45/// Both ends of a tab connection, for a transport that serves the commands itself.
46pub struct TabChannel {
47 pub control: TabControl,
48 pub events: Option<TabEvents>,
49 pub commands: mpsc::UnboundedReceiver<TabCommand>,
50 pub event_sink: Option<mpsc::UnboundedSender<TabEvent>>,
51}
52
53impl TabChannel {
54 pub fn new(with_events: bool) -> Self {
55 let (commands_sender, commands) = mpsc::unbounded_channel();
56 let (event_sink, events) = if with_events {
57 let (sender, receiver) = mpsc::unbounded_channel();
58 (Some(sender), Some(TabEvents { receiver }))
59 } else {
60 (None, None)
61 };
62 TabChannel {
63 control: TabControl {
64 commands: commands_sender,
65 },
66 events,
67 commands,
68 event_sink,
69 }
70 }
71}
72
73#[derive(Clone)]
74pub struct TabControl {
75 commands: mpsc::UnboundedSender<TabCommand>,
76}
77
78pub struct TabEvents {
79 receiver: mpsc::UnboundedReceiver<TabEvent>,
80}
81
82impl TabEvents {
83 pub async fn recv(&mut self) -> Option<TabEvent> {
84 self.receiver.recv().await
85 }
86}
87
88impl Stream for TabEvents {
89 type Item = TabEvent;
90
91 fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<TabEvent>> {
92 self.receiver.poll_recv(context)
93 }
94}
95
96impl TabControl {
97 pub async fn call(&self, method: &str, params: Value) -> Result<Value> {
98 let (reply, answer) = oneshot::channel();
99 let command = TabCommand {
100 method: method.to_owned(),
101 params,
102 reply,
103 };
104 self.commands
105 .send(command)
106 .map_err(|_| Error::Cdp("tab connection closed".into()))?;
107 answer
108 .await
109 .map_err(|_| Error::Cdp("tab connection closed".into()))?
110 }
111
112 pub async fn enable_events(&self) -> Result<()> {
113 self.call("Runtime.enable", json!({})).await?;
114 self.call("Page.enable", json!({})).await?;
115 Ok(())
116 }
117
118 pub async fn add_binding(&self, name: &str) -> Result<()> {
119 self.call("Runtime.addBinding", json!({"name": name}))
120 .await
121 .map(drop)
122 }
123
124 pub async fn evaluate(&self, expression: &str) -> Result<Value> {
125 self.evaluate_within(expression, EVALUATE_TIMEOUT).await
126 }
127
128 pub async fn evaluate_within(&self, expression: &str, timeout: Duration) -> Result<Value> {
129 let params = json!({"expression": expression, "awaitPromise": true, "returnByValue": true});
130 let result = tokio::time::timeout(timeout, self.call("Runtime.evaluate", params))
131 .await
132 .map_err(|_| Error::Cdp("Runtime.evaluate timed out".into()))??;
133 if let Some(details) = result.get("exceptionDetails") {
134 let text = details
135 .pointer("/exception/description")
136 .or_else(|| details.get("text"))
137 .and_then(Value::as_str)
138 .unwrap_or("unknown");
139 return Err(Error::Cdp(format!("page script failed: {text}")));
140 }
141 Ok(result
142 .pointer("/result/value")
143 .cloned()
144 .unwrap_or(Value::Null))
145 }
146
147 /// Runs `source` in every future document of the tab and once in the current one.
148 pub async fn inject_script(&self, source: &str) -> Result<String> {
149 let added = self
150 .call(
151 "Page.addScriptToEvaluateOnNewDocument",
152 json!({"source": source}),
153 )
154 .await?;
155 let identifier = added
156 .get("identifier")
157 .and_then(Value::as_str)
158 .unwrap_or_default()
159 .to_owned();
160 self.evaluate(source).await?;
161 Ok(identifier)
162 }
163
164 pub async fn remove_injected_script(&self, identifier: &str) -> Result<()> {
165 self.call(
166 "Page.removeScriptToEvaluateOnNewDocument",
167 json!({"identifier": identifier}),
168 )
169 .await
170 .map(drop)
171 }
172}
173
174pub(crate) async fn open(
175 websocket_url: &str,
176 with_events: bool,
177) -> Result<(TabControl, Option<TabEvents>)> {
178 let (stream, _) = connect_async(websocket_url)
179 .await
180 .map_err(|error| Error::Cdp(format!("websocket connect failed: {error}")))?;
181 let channel = TabChannel::new(with_events);
182 tokio::spawn(pump(stream, channel.commands, channel.event_sink));
183 Ok((channel.control, channel.events))
184}
185
186async fn events_closed(events: &Option<mpsc::UnboundedSender<TabEvent>>) {
187 match events {
188 Some(sender) => sender.closed().await,
189 None => std::future::pending().await,
190 }
191}
192
193async fn pump<S>(
194 mut stream: S,
195 mut commands: mpsc::UnboundedReceiver<TabCommand>,
196 events: Option<mpsc::UnboundedSender<TabEvent>>,
197) where
198 S: Stream<Item = std::result::Result<Message, tokio_tungstenite::tungstenite::Error>>
199 + futures_util::Sink<Message>
200 + Unpin,
201{
202 let mut pending: HashMap<u64, oneshot::Sender<Result<Value>>> = HashMap::new();
203 let mut next_id: u64 = 1;
204 let mut commands_open = true;
205 loop {
206 tokio::select! {
207 command = commands.recv(), if commands_open => {
208 let Some(command) = command else {
209 if events.is_none() {
210 break;
211 }
212 commands_open = false;
213 continue;
214 };
215 let call_id = next_id;
216 next_id += 1;
217 let frame = json!({"id": call_id, "method": command.method, "params": command.params});
218 if stream.send(Message::text(frame.to_string())).await.is_err() {
219 let _ = command.reply.send(Err(Error::Cdp("websocket send failed".into())));
220 break;
221 }
222 pending.insert(call_id, command.reply);
223 }
224 message = stream.next() => {
225 let Some(Ok(message)) = message else { break };
226 let Message::Text(text) = message else {
227 if matches!(message, Message::Close(_)) {
228 break;
229 }
230 continue;
231 };
232 let Ok(frame) = serde_json::from_str::<Value>(text.as_str()) else { continue };
233 if let Some(call_id) = frame.get("id").and_then(Value::as_u64) {
234 if let Some(reply) = pending.remove(&call_id) {
235 let _ = reply.send(answer_of(&frame));
236 }
237 } else if let Some(events) = &events
238 && let Some(method) = frame.get("method").and_then(Value::as_str)
239 {
240 let event = TabEvent {
241 method: method.to_owned(),
242 params: frame.get("params").cloned().unwrap_or(Value::Null),
243 };
244 if events.send(event).is_err() {
245 break;
246 }
247 }
248 }
249 _ = events_closed(&events) => break,
250 }
251 }
252 for (_, reply) in pending {
253 let _ = reply.send(Err(Error::Cdp("websocket closed".into())));
254 }
255}
256
257fn answer_of(frame: &Value) -> Result<Value> {
258 if let Some(failure) = frame.get("error") {
259 let reason = failure
260 .get("message")
261 .and_then(Value::as_str)
262 .unwrap_or("unknown");
263 return Err(Error::Cdp(reason.to_owned()));
264 }
265 Ok(frame.get("result").cloned().unwrap_or(Value::Null))
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn binding_payload_matches_name_only() {
274 let event = TabEvent {
275 method: "Runtime.bindingCalled".into(),
276 params: json!({"name": "sink", "payload": "{}"}),
277 };
278 assert_eq!(event.binding_payload("sink"), Some("{}"));
279 assert_eq!(event.binding_payload("other"), None);
280 let navigation = TabEvent {
281 method: "Page.frameNavigated".into(),
282 params: json!({}),
283 };
284 assert_eq!(navigation.binding_payload("sink"), None);
285 }
286}