BlueGit

ict rusty-teams

Files

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

events.rs

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