BlueGit

ict rusty-teams

Files

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

mod.rs

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