BlueGit

ict rusty-teams

Files

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

mod.rs

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