BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / realtime / mod.rs

mod.rs

fix(presence): review findings
metis Daniel Däschle · pushed by metis · 7 weeks ago
a755adcc History
mod.rs 5.4 KiB Download Raw
1mod callback;
2mod event;
3mod host;
4mod runner;
5
6use std::pin::Pin;
7use std::sync::Arc;
8use std::task::{Context, Poll};
9use std::time::Duration;
10
11use futures_util::Stream;
12use session::Session;
13use tokio::sync::{Notify, mpsc, oneshot, watch};
14use tokio::task::JoinHandle;
15
16pub use event::{
17 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 TrouterEndpoint, TypingEvent, decode_payload,
19};
20pub use callback::{CallbackReplier, TrouterCallback};
21pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22
23use crate::error::Result;
24use runner::{Runner, attach};
25
26const STOP_TIMEOUT: Duration = Duration::from_secs(15);
27
28#[derive(Debug, Clone)]
29pub struct RealtimeConfig {
30 pub host: Option<String>,
31 pub default_host: String,
32 pub discover_host: bool,
33 pub ensure_interval: Duration,
34 pub navigation_settle: Duration,
35 pub max_reattach_backoff: Duration,
36 pub instance: InstanceNames,
37 pub forward_callbacks: bool,
38 pub ringable: bool,
39 pub initially_active: bool,
40}
41
42/// Page globals of one Trouter client; a second client in the same tab needs its own names.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct InstanceNames {
45 pub global: String,
46 pub binding: String,
47 pub endpoint_storage_key: String,
48}
49
50impl Default for InstanceNames {
51 fn default() -> Self {
52 InstanceNames {
53 global: runner::DEFAULT_GLOBAL_NAME.to_owned(),
54 binding: runner::DEFAULT_BINDING_NAME.to_owned(),
55 endpoint_storage_key: runner::DEFAULT_EPID_KEY.to_owned(),
56 }
57 }
58}
59
60impl Default for RealtimeConfig {
61 fn default() -> Self {
62 RealtimeConfig {
63 host: None,
64 default_host: DEFAULT_TROUTER_HOST.to_owned(),
65 discover_host: true,
66 ensure_interval: Duration::from_secs(30),
67 navigation_settle: Duration::from_millis(1500),
68 max_reattach_backoff: Duration::from_secs(30),
69 instance: InstanceNames::default(),
70 forward_callbacks: false,
71 ringable: false,
72 initially_active: false,
73 }
74 }
75}
76
77pub struct Realtime {
78 host: String,
79 events: mpsc::UnboundedReceiver<RealtimeEvent>,
80 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
81 replier: CallbackReplier,
82 activity: watch::Sender<bool>,
83 resend: Arc<Notify>,
84 stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
85 task: JoinHandle<()>,
86}
87
88impl Realtime {
89 /// Works on a parked tab (same origin, localStorage readable); the CDP attachment keeps it from being parked.
90 pub async fn start(session: &Session) -> Result<Realtime> {
91 Self::start_with(session, RealtimeConfig::default()).await
92 }
93
94 pub async fn start_with(session: &Session, config: RealtimeConfig) -> Result<Realtime> {
95 let session = session.clone();
96 let host = host::resolve(&session, &config).await;
97 let script = runner::PageScript::new(&config);
98 let attached = attach(&session, &script).await?;
99 let (output, events) = mpsc::unbounded_channel();
100 let (callback_output, callbacks) = mpsc::unbounded_channel();
101 let (reply_sender, replies) = mpsc::unbounded_channel();
102 let (activity, activity_receiver) = watch::channel(config.initially_active);
103 let resend = Arc::new(Notify::new());
104 let (stop, stop_receiver) = oneshot::channel();
105 let mut runner = Runner::new(
106 session,
107 config,
108 script,
109 host.clone(),
110 output,
111 runner::CallbackPipes {
112 output: callback_output,
113 replies,
114 },
115 activity_receiver,
116 resend.clone(),
117 );
118 if let Err(error) = runner.ensure().await {
119 attached.shutdown().await;
120 return Err(error.into());
121 }
122 let task = tokio::spawn(runner.run(attached, stop_receiver));
123 Ok(Realtime {
124 host,
125 events,
126 callbacks: Some(callbacks),
127 replier: CallbackReplier {
128 sender: reply_sender,
129 },
130 activity,
131 resend,
132 stop: Some(stop),
133 task,
134 })
135 }
136
137 pub fn host(&self) -> &str {
138 &self.host
139 }
140
141 pub async fn recv(&mut self) -> Option<RealtimeEvent> {
142 self.events.recv().await
143 }
144
145 /// Callbacks only flow when `forward_callbacks` is set; the receiver can be taken once.
146 pub fn take_callbacks(&mut self) -> Option<mpsc::UnboundedReceiver<TrouterCallback>> {
147 self.callbacks.take()
148 }
149
150 pub fn callback_replier(&self) -> CallbackReplier {
151 self.replier.clone()
152 }
153
154 pub fn set_activity(&self, active: bool) {
155 self.activity.send_replace(active);
156 }
157
158 pub fn resend_activity(&self) {
159 self.resend.notify_one();
160 }
161
162 /// Deletes the registration and closes the page-side socket.
163 pub async fn stop(mut self) {
164 if let Some(stop) = self.stop.take() {
165 let (done, finished) = oneshot::channel();
166 if stop.send(done).is_ok() {
167 let _ = tokio::time::timeout(STOP_TIMEOUT, finished).await;
168 }
169 }
170 let _ = self.task.await;
171 }
172}
173
174impl Stream for Realtime {
175 type Item = RealtimeEvent;
176
177 fn poll_next(
178 mut self: Pin<&mut Self>,
179 context: &mut Context<'_>,
180 ) -> Poll<Option<RealtimeEvent>> {
181 self.events.poll_recv(context)
182 }
183}