fix(presence): review findings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -8,7 +8,7 @@ use graph::Graph;
8
8
use session::{Session, SessionConfig, Transport};
9
9
use store::Store;
10
10
use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
11
use tokio::sync::{mpsc, watch};
11
use tokio::sync::{Notify, mpsc, watch};
12
12
13
13
use crate::call::{CallLauncher, fetch_window};
14
14
use crate::presence_link::{self, LinkSignal};
@@ -100,10 +100,11 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
100
100
}
101
101
}
102
102
103
fn link_signal_for(kind: StatusKind) -> LinkSignal {
103
fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {
104
104
match kind {
105
StatusKind::Connected | StatusKind::MessageLoss => LinkSignal::Connected,
106
StatusKind::Disconnected | StatusKind::Error => LinkSignal::Disconnected,
105
StatusKind::Connected => Some(LinkSignal::Connected),
106
StatusKind::Disconnected => Some(LinkSignal::Disconnected),
107
StatusKind::MessageLoss | StatusKind::Error => None,
107
108
}
108
109
}
109
110
@@ -155,13 +156,15 @@ async fn supervise(
155
156
let _ = events.send(BackendEvent::Calls(launcher));
156
157
tokio::spawn(forward_core_events(engine.clone(), events.clone()));
157
158
let (nudge, nudges) = mpsc::unbounded_channel();
158
let link = presence_link::start(&session, activity.clone());
159
let resend = Arc::new(Notify::new());
160
let link = presence_link::start(&session, activity.clone(), resend.clone());
159
161
tokio::spawn(realtime_loop(
160
162
session.clone(),
161
163
engine.clone(),
162
164
events.clone(),
163
165
nudge,
164
166
activity,
167
resend,
165
168
link,
166
169
));
167
170
tokio::spawn(calendar_loop(session.clone(), events.clone()));
@@ -225,6 +228,7 @@ async fn realtime_loop(
225
228
events: EventSender,
226
229
nudge: mpsc::UnboundedSender<()>,
227
230
mut activity: watch::Receiver<bool>,
231
resend: Arc<Notify>,
228
232
link: mpsc::UnboundedSender<LinkSignal>,
229
233
) {
230
234
loop {
@@ -242,6 +246,10 @@ async fn realtime_loop(
242
246
realtime.set_activity(*activity.borrow_and_update());
243
247
continue;
244
248
}
249
_ = resend.notified() => {
250
realtime.resend_activity();
251
continue;
252
}
245
253
};
246
254
let Some(event) = event else { break };
247
255
match event {
@@ -267,7 +275,9 @@ async fn realtime_loop(
267
275
}
268
276
RealtimeEvent::Status(status) => {
269
277
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
270
let _ = link.send(link_signal_for(status.kind));
278
if let Some(signal) = link_signal_for(status.kind) {
279
let _ = link.send(signal);
280
}
271
281
let receipt_engine = engine.clone();
272
282
let receipt_status = status.clone();
273
283
tokio::spawn(async move {
@@ -506,10 +516,10 @@ mod tests {
506
516
}
507
517
508
518
#[test]
509
fn only_a_closed_or_failed_trouter_counts_as_down() {
510
assert_eq!(link_signal_for(StatusKind::Connected), LinkSignal::Connected);
511
assert_eq!(link_signal_for(StatusKind::MessageLoss), LinkSignal::Connected);
512
assert_eq!(link_signal_for(StatusKind::Disconnected), LinkSignal::Disconnected);
513
assert_eq!(link_signal_for(StatusKind::Error), LinkSignal::Disconnected);
519
fn only_connect_and_disconnect_move_the_link() {
520
assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected));
521
assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected));
522
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
523
assert_eq!(link_signal_for(StatusKind::Error), None);
514
524
}
515
525
}
@@ -8,7 +8,7 @@ use graph::Graph;8
use session::{Session, SessionConfig, Transport};8
use session::{Session, SessionConfig, Transport};9
use store::Store;9
use store::Store;10
use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};10
use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};11
use tokio::sync::{mpsc, watch};11
use tokio::sync::{Notify, mpsc, watch};12
12
13
use crate::call::{CallLauncher, fetch_window};13
use crate::call::{CallLauncher, fetch_window};14
use crate::presence_link::{self, LinkSignal};14
use crate::presence_link::{self, LinkSignal};@@ -100,10 +100,11 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {100
}100
}101
}101
}102
102
103
fn link_signal_for(kind: StatusKind) -> LinkSignal {103
fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {104
match kind {104
match kind {105
StatusKind::Connected | StatusKind::MessageLoss => LinkSignal::Connected,105
StatusKind::Connected => Some(LinkSignal::Connected),106
StatusKind::Disconnected | StatusKind::Error => LinkSignal::Disconnected,106
StatusKind::Disconnected => Some(LinkSignal::Disconnected),107
StatusKind::MessageLoss | StatusKind::Error => None,107
}108
}108
}109
}109
110
@@ -155,13 +156,15 @@ async fn supervise(155
let _ = events.send(BackendEvent::Calls(launcher));156
let _ = events.send(BackendEvent::Calls(launcher));156
tokio::spawn(forward_core_events(engine.clone(), events.clone()));157
tokio::spawn(forward_core_events(engine.clone(), events.clone()));157
let (nudge, nudges) = mpsc::unbounded_channel();158
let (nudge, nudges) = mpsc::unbounded_channel();158
let link = presence_link::start(&session, activity.clone());159
let resend = Arc::new(Notify::new());160
let link = presence_link::start(&session, activity.clone(), resend.clone());159
tokio::spawn(realtime_loop(161
tokio::spawn(realtime_loop(160
session.clone(),162
session.clone(),161
engine.clone(),163
engine.clone(),162
events.clone(),164
events.clone(),163
nudge,165
nudge,164
activity,166
activity,167
resend,165
link,168
link,166
));169
));167
tokio::spawn(calendar_loop(session.clone(), events.clone()));170
tokio::spawn(calendar_loop(session.clone(), events.clone()));@@ -225,6 +228,7 @@ async fn realtime_loop(225
events: EventSender,228
events: EventSender,226
nudge: mpsc::UnboundedSender<()>,229
nudge: mpsc::UnboundedSender<()>,227
mut activity: watch::Receiver<bool>,230
mut activity: watch::Receiver<bool>,231
resend: Arc<Notify>,228
link: mpsc::UnboundedSender<LinkSignal>,232
link: mpsc::UnboundedSender<LinkSignal>,229
) {233
) {230
loop {234
loop {@@ -242,6 +246,10 @@ async fn realtime_loop(242
realtime.set_activity(*activity.borrow_and_update());246
realtime.set_activity(*activity.borrow_and_update());243
continue;247
continue;244
}248
}249
_ = resend.notified() => {250
realtime.resend_activity();251
continue;252
}245
};253
};246
let Some(event) = event else { break };254
let Some(event) = event else { break };247
match event {255
match event {@@ -267,7 +275,9 @@ async fn realtime_loop(267
}275
}268
RealtimeEvent::Status(status) => {276
RealtimeEvent::Status(status) => {269
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));277
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));270
let _ = link.send(link_signal_for(status.kind));278
if let Some(signal) = link_signal_for(status.kind) {279
let _ = link.send(signal);280
}271
let receipt_engine = engine.clone();281
let receipt_engine = engine.clone();272
let receipt_status = status.clone();282
let receipt_status = status.clone();273
tokio::spawn(async move {283
tokio::spawn(async move {@@ -506,10 +516,10 @@ mod tests {506
}516
}507
517
508
#[test]518
#[test]509
fn only_a_closed_or_failed_trouter_counts_as_down() {519
fn only_connect_and_disconnect_move_the_link() {510
assert_eq!(link_signal_for(StatusKind::Connected), LinkSignal::Connected);520
assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected));511
assert_eq!(link_signal_for(StatusKind::MessageLoss), LinkSignal::Connected);521
assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected));512
assert_eq!(link_signal_for(StatusKind::Disconnected), LinkSignal::Disconnected);522
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);513
assert_eq!(link_signal_for(StatusKind::Error), LinkSignal::Disconnected);523
assert_eq!(link_signal_for(StatusKind::Error), None);514
}524
}515
}525
}@@ -1,15 +1,17 @@
1
use std::sync::OnceLock;
1
use std::sync::{Arc, OnceLock};
2
2
use std::time::Duration;
3
3
4
4
use chatsvc::cards::CardTransport;
5
use chatsvc::{PresenceService, is_endpoint_missing};
5
use chatsvc::{ActivityReporting, PresenceService, error_status, is_endpoint_missing};
6
6
use session::Session;
7
use tokio::sync::{mpsc, oneshot, watch};
7
use tokio::sync::{Notify, mpsc, oneshot, watch};
8
8
use tokio::time::{Instant, MissedTickBehavior, interval};
9
9
10
10
const FALLBACK_AFTER: Duration = Duration::from_secs(120);
11
11
const FALLBACK_INTERVAL: Duration = Duration::from_secs(120);
12
12
const CHECK_INTERVAL: Duration = Duration::from_secs(30);
13
const RETRY_BASE: Duration = Duration::from_secs(30);
14
const RETRY_MAX: Duration = Duration::from_secs(240);
13
15
14
16
static UNREGISTER: OnceLock<mpsc::UnboundedSender<oneshot::Sender<()>>> = OnceLock::new();
15
17
@@ -25,12 +27,25 @@ pub fn report_due(down_for: Option<Duration>, since_last_report: Option<Duration
25
27
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))
26
28
}
27
29
28
pub fn start(session: &Session, activity: watch::Receiver<bool>) -> mpsc::UnboundedSender<LinkSignal> {
30
pub fn retry_delay(failures: u32) -> Duration {
31
let doublings = failures.saturating_sub(1).min(8);
32
(RETRY_BASE * 2u32.pow(doublings)).min(RETRY_MAX)
33
}
34
35
pub fn is_permanent_failure(status: Option<u16>) -> bool {
36
matches!(status, Some(400..=499)) && !matches!(status, Some(401 | 404 | 408 | 429))
37
}
38
39
pub fn start(
40
session: &Session,
41
activity: watch::Receiver<bool>,
42
resend: Arc<Notify>,
43
) -> mpsc::UnboundedSender<LinkSignal> {
29
44
let (signals, receiver) = mpsc::unbounded_channel();
30
45
let (unregister, unregisters) = mpsc::unbounded_channel();
31
46
let _ = UNREGISTER.set(unregister);
32
let service = PresenceService::new(session);
33
tokio::spawn(run(service, activity, receiver, unregisters));
47
let link = Link::new(PresenceService::new(session), activity, resend);
48
tokio::spawn(link.run(receiver, unregisters));
34
49
signals
35
50
}
36
51
@@ -47,127 +62,204 @@ pub fn unregister_on_exit(timeout: Duration) {
47
62
}
48
63
49
64
#[derive(Default)]
50
struct LinkState {
65
struct RetryState {
66
failures: u32,
67
next_attempt: Option<Instant>,
68
blocked: bool,
69
last_error: Option<String>,
70
}
71
72
impl RetryState {
73
fn may_attempt(&self, now: Instant) -> bool {
74
!self.blocked && self.next_attempt.is_none_or(|next| now >= next)
75
}
76
77
fn succeeded(&mut self) {
78
*self = RetryState::default();
79
}
80
81
fn failed(&mut self, now: Instant, error: &chatsvc::Error) -> Option<String> {
82
self.failures += 1;
83
self.next_attempt = Some(now + retry_delay(self.failures));
84
self.blocked = is_permanent_failure(error_status(error));
85
let message = error.to_string();
86
let is_new = self.last_error.as_deref() != Some(message.as_str());
87
self.last_error = Some(message.clone());
88
is_new.then_some(message)
89
}
90
}
91
92
struct Link<T: CardTransport> {
93
service: PresenceService<T>,
94
activity: watch::Receiver<bool>,
95
resend: Arc<Notify>,
51
96
endpoint_id: Option<String>,
52
97
registered: bool,
98
applied: ActivityReporting,
53
99
down_since: Option<Instant>,
54
100
last_report: Option<Instant>,
101
retry: RetryState,
55
102
}
56
103
57
async fn run<T: CardTransport>(
58
service: PresenceService<T>,
59
mut activity: watch::Receiver<bool>,
60
mut signals: mpsc::UnboundedReceiver<LinkSignal>,
61
mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>,
62
) {
63
let mut state = LinkState::default();
64
let mut check = interval(CHECK_INTERVAL);
65
check.set_missed_tick_behavior(MissedTickBehavior::Delay);
66
loop {
67
tokio::select! {
68
signal = signals.recv() => {
69
let Some(signal) = signal else { return };
70
apply_signal(&service, &mut state, signal).await;
71
}
72
Ok(()) = activity.changed() => {
73
let active = *activity.borrow_and_update();
74
report_if_due(&service, &mut state, active, true).await;
104
impl<T: CardTransport> Link<T> {
105
fn new(service: PresenceService<T>, activity: watch::Receiver<bool>, resend: Arc<Notify>) -> Self {
106
Link {
107
service,
108
activity,
109
resend,
110
endpoint_id: None,
111
registered: false,
112
applied: ActivityReporting::Transport,
113
down_since: None,
114
last_report: None,
115
retry: RetryState::default(),
116
}
117
}
118
119
async fn run(
120
mut self,
121
mut signals: mpsc::UnboundedReceiver<LinkSignal>,
122
mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>,
123
) {
124
let mut check = interval(CHECK_INTERVAL);
125
check.set_missed_tick_behavior(MissedTickBehavior::Delay);
126
loop {
127
tokio::select! {
128
signal = signals.recv() => {
129
let Some(signal) = signal else { return };
130
self.apply(signal).await;
131
}
132
Ok(()) = self.activity.changed() => {
133
self.activity.borrow_and_update();
134
self.reconcile(true).await;
135
}
136
_ = check.tick() => self.reconcile(false).await,
137
Some(done) = unregisters.recv() => {
138
if let Some(endpoint_id) = &self.endpoint_id {
139
let _ = self.service.unregister_endpoint(endpoint_id).await;
140
}
141
let _ = done.send(());
142
}
75
143
}
76
_ = check.tick() => {
77
if let Some(endpoint_id) = state.endpoint_id.clone().filter(|_| !state.registered) {
78
state.registered = register(&service, &endpoint_id).await;
144
}
145
}
146
147
async fn apply(&mut self, signal: LinkSignal) {
148
match signal {
149
LinkSignal::Endpoint(endpoint_id) => {
150
if self.endpoint_id.as_deref() == Some(endpoint_id.as_str()) {
151
return;
152
}
153
if let Some(previous) = self.endpoint_id.replace(endpoint_id) {
154
let _ = self.service.unregister_endpoint(&previous).await;
79
155
}
80
let active = *activity.borrow();
81
report_if_due(&service, &mut state, active, false).await;
156
self.registered = false;
157
self.applied = ActivityReporting::Transport;
158
self.down_since = None;
159
self.last_report = None;
160
self.retry.succeeded();
82
161
}
83
Some(done) = unregisters.recv() => {
84
if let Some(endpoint_id) = &state.endpoint_id {
85
let _ = service.unregister_endpoint(endpoint_id).await;
162
LinkSignal::Connected => {
163
if self.down_since.take().is_some() {
164
self.last_report = None;
165
self.retry.succeeded();
86
166
}
87
let _ = done.send(());
167
}
168
LinkSignal::Disconnected => {
169
self.down_since.get_or_insert_with(Instant::now);
88
170
}
89
171
}
172
self.reconcile(false).await;
90
173
}
91
}
92
174
93
async fn apply_signal<T: CardTransport>(service: &PresenceService<T>, state: &mut LinkState, signal: LinkSignal) {
94
match signal {
95
LinkSignal::Endpoint(endpoint_id) => {
96
state.registered = register(service, &endpoint_id).await;
97
state.endpoint_id = Some(endpoint_id);
98
state.down_since = None;
99
state.last_report = None;
175
async fn reconcile(&mut self, activity_changed: bool) {
176
let Some(endpoint_id) = self.endpoint_id.clone() else {
177
return;
178
};
179
let now = Instant::now();
180
let down_for = self.down_since.map(|since| now.duration_since(since));
181
let wanted = match down_for {
182
Some(down_for) if down_for >= FALLBACK_AFTER => ActivityReporting::Direct,
183
_ => ActivityReporting::Transport,
184
};
185
if (!self.registered || self.applied != wanted) && self.retry.may_attempt(now) {
186
self.register(&endpoint_id, wanted, now).await;
100
187
}
101
LinkSignal::Connected => {
102
state.down_since = None;
103
state.last_report = None;
188
if wanted != ActivityReporting::Direct || !self.registered || self.applied != wanted {
189
return;
104
190
}
105
LinkSignal::Disconnected => {
106
state.down_since.get_or_insert_with(Instant::now);
191
let since_last_report = self.last_report.map(|last| now.duration_since(last));
192
if report_due(down_for, since_last_report, activity_changed) {
193
self.last_report = Some(now);
194
let active = *self.activity.borrow();
195
self.report_with_recovery(&endpoint_id, active).await;
107
196
}
108
197
}
109
}
110
198
111
async fn register<T: CardTransport>(service: &PresenceService<T>, endpoint_id: &str) -> bool {
112
match service.register_endpoint(endpoint_id).await {
113
Ok(()) => true,
114
Err(error) => {
115
crate::diagnostics::record(format!("presence: endpoint not registered: {error}"));
116
false
199
async fn register(&mut self, endpoint_id: &str, reporting: ActivityReporting, now: Instant) {
200
match self.service.register_endpoint(endpoint_id, reporting).await {
201
Ok(()) => {
202
self.registered = true;
203
self.applied = reporting;
204
self.retry.succeeded();
205
if reporting == ActivityReporting::Transport {
206
self.resend.notify_one();
207
}
208
}
209
Err(error) => {
210
if let Some(message) = self.retry.failed(now, &error) {
211
crate::diagnostics::record(format!("presence: endpoint not registered: {message}"));
212
}
213
}
117
214
}
118
215
}
119
}
120
121
async fn report_if_due<T: CardTransport>(
122
service: &PresenceService<T>,
123
state: &mut LinkState,
124
active: bool,
125
activity_changed: bool,
126
) {
127
let Some(endpoint_id) = state.endpoint_id.clone() else {
128
return;
129
};
130
let now = Instant::now();
131
let down_for = state.down_since.map(|since| now.duration_since(since));
132
let since_last_report = state.last_report.map(|last| now.duration_since(last));
133
if !report_due(down_for, since_last_report, activity_changed) {
134
return;
135
}
136
state.last_report = Some(now);
137
report_with_recovery(service, &endpoint_id, active).await;
138
}
139
216
140
async fn report_with_recovery<T: CardTransport>(service: &PresenceService<T>, endpoint_id: &str, active: bool) {
141
let Err(error) = service.report_activity(endpoint_id, active).await else {
142
return;
143
};
144
if is_endpoint_missing(&error)
145
&& service.register_endpoint(endpoint_id).await.is_ok()
146
&& service.report_activity(endpoint_id, active).await.is_ok()
147
{
148
return;
217
async fn report_with_recovery(&self, endpoint_id: &str, active: bool) {
218
let Err(error) = self.service.report_activity(endpoint_id, active).await else {
219
return;
220
};
221
if is_endpoint_missing(&error)
222
&& self
223
.service
224
.register_endpoint(endpoint_id, ActivityReporting::Direct)
225
.await
226
.is_ok()
227
&& self.service.report_activity(endpoint_id, active).await.is_ok()
228
{
229
return;
230
}
231
crate::diagnostics::record(format!("presence: activity not reported: {error}"));
149
232
}
150
crate::diagnostics::record(format!("presence: activity not reported: {error}"));
151
233
}
152
234
153
235
#[cfg(test)]
154
236
mod tests {
155
use std::sync::{Arc, Mutex};
237
use std::sync::Mutex;
156
238
157
239
use chatsvc::Result;
158
240
use session::{ApiResponse, Method, Request, Scope};
159
241
160
242
use super::*;
161
243
244
const PRESENCE: &str = "https://presence.teams.microsoft.com/v1/me";
245
246
type Sent = Arc<Mutex<Vec<(Method, String, Option<String>)>>>;
247
162
248
struct Scripted {
163
249
statuses: Mutex<Vec<u16>>,
164
sent: Arc<Mutex<Vec<(Method, String)>>>,
250
sent: Sent,
165
251
}
166
252
167
253
impl CardTransport for Scripted {
168
254
async fn send(&self, request: Request, _scope: Scope) -> Result<ApiResponse> {
169
self.sent.lock().unwrap().push((request.method, request.url));
170
let status = self.statuses.lock().unwrap().remove(0);
255
let reporting = request
256
.body
257
.as_ref()
258
.and_then(|body| body["activityReporting"].as_str())
259
.map(str::to_owned);
260
self.sent.lock().unwrap().push((request.method, request.url, reporting));
261
let mut statuses = self.statuses.lock().unwrap();
262
let status = if statuses.is_empty() { 200 } else { statuses.remove(0) };
171
263
Ok(ApiResponse {
172
264
status,
173
265
body: serde_json::Value::Null,
@@ -176,6 +268,28 @@ mod tests {
176
268
}
177
269
}
178
270
271
fn link(statuses: Vec<u16>) -> (Link<Scripted>, Sent, Arc<Notify>) {
272
let sent: Sent = Arc::default();
273
let resend = Arc::new(Notify::new());
274
let (_, activity) = watch::channel(true);
275
let service = PresenceService::with_transport(Scripted {
276
statuses: Mutex::new(statuses),
277
sent: sent.clone(),
278
});
279
(Link::new(service, activity, resend.clone()), sent, resend)
280
}
281
282
fn calls(sent: &Sent) -> Vec<String> {
283
sent.lock()
284
.unwrap()
285
.iter()
286
.map(|(method, url, reporting)| {
287
let path = url.strip_prefix(PRESENCE).unwrap();
288
format!("{} {path} {}", method.as_str(), reporting.as_deref().unwrap_or("-"))
289
})
290
.collect()
291
}
292
179
293
fn seconds(count: u64) -> Duration {
180
294
Duration::from_secs(count)
181
295
}
@@ -190,22 +304,98 @@ mod tests {
190
304
assert!(report_due(Some(seconds(150)), Some(seconds(30)), true));
191
305
}
192
306
307
#[test]
308
fn retry_delay_doubles_up_to_four_minutes() {
309
let delays: Vec<u64> = (1..=6).map(|failures| retry_delay(failures).as_secs()).collect();
310
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);
311
}
312
313
#[test]
314
fn only_client_errors_other_than_auth_and_missing_are_permanent() {
315
assert!(is_permanent_failure(Some(400)));
316
assert!(is_permanent_failure(Some(403)));
317
assert!(!is_permanent_failure(Some(401)));
318
assert!(!is_permanent_failure(Some(404)));
319
assert!(!is_permanent_failure(Some(429)));
320
assert!(!is_permanent_failure(Some(500)));
321
assert!(!is_permanent_failure(None));
322
}
323
324
#[tokio::test]
325
async fn a_repeated_identical_failure_is_logged_once_and_backs_off() {
326
let error = chatsvc::Error::UnexpectedAnswer("x".into());
327
let mut retry = RetryState::default();
328
let now = Instant::now();
329
assert!(retry.failed(now, &error).is_some());
330
assert!(retry.failed(now, &error).is_none());
331
assert!(!retry.may_attempt(now + seconds(59)));
332
assert!(retry.may_attempt(now + seconds(60)));
333
retry.succeeded();
334
assert!(retry.may_attempt(now));
335
}
336
337
#[tokio::test]
338
async fn a_permanent_failure_stops_retrying_until_a_new_endpoint() {
339
let (mut link, sent, _) = link(vec![403]);
340
link.apply(LinkSignal::Endpoint("a".into())).await;
341
link.reconcile(false).await;
342
assert_eq!(calls(&sent).len(), 1);
343
assert!(!link.retry.may_attempt(Instant::now() + seconds(10_000)));
344
link.apply(LinkSignal::Endpoint("b".into())).await;
345
assert_eq!(calls(&sent).len(), 3);
346
}
347
348
#[tokio::test]
349
async fn the_same_endpoint_announced_again_is_not_registered_again() {
350
let (mut link, sent, resend) = link(vec![]);
351
link.apply(LinkSignal::Endpoint("a".into())).await;
352
link.apply(LinkSignal::Endpoint("a".into())).await;
353
link.apply(LinkSignal::Connected).await;
354
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);
355
resend.notified().await;
356
}
357
358
#[tokio::test]
359
async fn a_new_endpoint_removes_the_old_one_first() {
360
let (mut link, sent, _) = link(vec![]);
361
link.apply(LinkSignal::Endpoint("a".into())).await;
362
link.apply(LinkSignal::Endpoint("b".into())).await;
363
assert_eq!(
364
calls(&sent),
365
["PUT /endpoints/ Transport", "DELETE /endpoints/a -", "PUT /endpoints/ Transport"]
366
);
367
}
368
369
#[tokio::test]
370
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {
371
let (mut link, sent, resend) = link(vec![]);
372
link.apply(LinkSignal::Endpoint("a".into())).await;
373
resend.notified().await;
374
link.down_since = Some(Instant::now() - seconds(130));
375
link.reconcile(false).await;
376
link.apply(LinkSignal::Connected).await;
377
assert_eq!(
378
calls(&sent),
379
[
380
"PUT /endpoints/ Transport",
381
"PUT /endpoints/ Direct",
382
"POST /reportmyactivity/ -",
383
"PUT /endpoints/ Transport",
384
]
385
);
386
resend.notified().await;
387
}
388
193
389
#[tokio::test]
194
390
async fn a_missing_endpoint_is_registered_again_before_the_report_is_repeated() {
195
let sent = Arc::new(Mutex::new(Vec::new()));
196
let service = PresenceService::with_transport(Scripted {
197
statuses: Mutex::new(vec![404, 200, 200]),
198
sent: sent.clone(),
199
});
200
report_with_recovery(&service, "epid-1", true).await;
201
let sent = sent.lock().unwrap();
202
let calls: Vec<(Method, &str)> = sent.iter().map(|(method, url)| (*method, url.as_str())).collect();
391
let (link, sent, _) = link(vec![404, 200, 200]);
392
link.report_with_recovery("epid-1", true).await;
203
393
assert_eq!(
204
calls,
394
calls(&sent),
205
395
[
206
(Method::Post, "https://presence.teams.microsoft.com/v1/me/reportmyactivity/"),
207
(Method::Put, "https://presence.teams.microsoft.com/v1/me/endpoints/"),
208
(Method::Post, "https://presence.teams.microsoft.com/v1/me/reportmyactivity/"),
396
"POST /reportmyactivity/ -",
397
"PUT /endpoints/ Direct",
398
"POST /reportmyactivity/ -",
209
399
]
210
400
);
211
401
}
@@ -1,15 +1,17 @@1
use std::sync::OnceLock;1
use std::sync::{Arc, OnceLock};2
use std::time::Duration;2
use std::time::Duration;3
3
4
use chatsvc::cards::CardTransport;4
use chatsvc::cards::CardTransport;5
use chatsvc::{PresenceService, is_endpoint_missing};5
use chatsvc::{ActivityReporting, PresenceService, error_status, is_endpoint_missing};6
use session::Session;6
use session::Session;7
use tokio::sync::{mpsc, oneshot, watch};7
use tokio::sync::{Notify, mpsc, oneshot, watch};8
use tokio::time::{Instant, MissedTickBehavior, interval};8
use tokio::time::{Instant, MissedTickBehavior, interval};9
9
10
const FALLBACK_AFTER: Duration = Duration::from_secs(120);10
const FALLBACK_AFTER: Duration = Duration::from_secs(120);11
const FALLBACK_INTERVAL: Duration = Duration::from_secs(120);11
const FALLBACK_INTERVAL: Duration = Duration::from_secs(120);12
const CHECK_INTERVAL: Duration = Duration::from_secs(30);12
const CHECK_INTERVAL: Duration = Duration::from_secs(30);13
const RETRY_BASE: Duration = Duration::from_secs(30);14
const RETRY_MAX: Duration = Duration::from_secs(240);13
15
14
static UNREGISTER: OnceLock<mpsc::UnboundedSender<oneshot::Sender<()>>> = OnceLock::new();16
static UNREGISTER: OnceLock<mpsc::UnboundedSender<oneshot::Sender<()>>> = OnceLock::new();15
17
@@ -25,12 +27,25 @@ pub fn report_due(down_for: Option<Duration>, since_last_report: Option<Duration25
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))27
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))26
}28
}27
29
28
pub fn start(session: &Session, activity: watch::Receiver<bool>) -> mpsc::UnboundedSender<LinkSignal> {30
pub fn retry_delay(failures: u32) -> Duration {31
let doublings = failures.saturating_sub(1).min(8);32
(RETRY_BASE * 2u32.pow(doublings)).min(RETRY_MAX)33
}34
35
pub fn is_permanent_failure(status: Option<u16>) -> bool {36
matches!(status, Some(400..=499)) && !matches!(status, Some(401 | 404 | 408 | 429))37
}38
39
pub fn start(40
session: &Session,41
activity: watch::Receiver<bool>,42
resend: Arc<Notify>,43
) -> mpsc::UnboundedSender<LinkSignal> {29
let (signals, receiver) = mpsc::unbounded_channel();44
let (signals, receiver) = mpsc::unbounded_channel();30
let (unregister, unregisters) = mpsc::unbounded_channel();45
let (unregister, unregisters) = mpsc::unbounded_channel();31
let _ = UNREGISTER.set(unregister);46
let _ = UNREGISTER.set(unregister);32
let service = PresenceService::new(session);47
let link = Link::new(PresenceService::new(session), activity, resend);33
tokio::spawn(run(service, activity, receiver, unregisters));48
tokio::spawn(link.run(receiver, unregisters));34
signals49
signals35
}50
}36
51
@@ -47,127 +62,204 @@ pub fn unregister_on_exit(timeout: Duration) {47
}62
}48
63
49
#[derive(Default)]64
#[derive(Default)]50
struct LinkState {65
struct RetryState {66
failures: u32,67
next_attempt: Option<Instant>,68
blocked: bool,69
last_error: Option<String>,70
}71
72
impl RetryState {73
fn may_attempt(&self, now: Instant) -> bool {74
!self.blocked && self.next_attempt.is_none_or(|next| now >= next)75
}76
77
fn succeeded(&mut self) {78
*self = RetryState::default();79
}80
81
fn failed(&mut self, now: Instant, error: &chatsvc::Error) -> Option<String> {82
self.failures += 1;83
self.next_attempt = Some(now + retry_delay(self.failures));84
self.blocked = is_permanent_failure(error_status(error));85
let message = error.to_string();86
let is_new = self.last_error.as_deref() != Some(message.as_str());87
self.last_error = Some(message.clone());88
is_new.then_some(message)89
}90
}91
92
struct Link<T: CardTransport> {93
service: PresenceService<T>,94
activity: watch::Receiver<bool>,95
resend: Arc<Notify>,51
endpoint_id: Option<String>,96
endpoint_id: Option<String>,52
registered: bool,97
registered: bool,98
applied: ActivityReporting,53
down_since: Option<Instant>,99
down_since: Option<Instant>,54
last_report: Option<Instant>,100
last_report: Option<Instant>,101
retry: RetryState,55
}102
}56
103
57
async fn run<T: CardTransport>(104
impl<T: CardTransport> Link<T> {58
service: PresenceService<T>,105
fn new(service: PresenceService<T>, activity: watch::Receiver<bool>, resend: Arc<Notify>) -> Self {59
mut activity: watch::Receiver<bool>,106
Link {60
mut signals: mpsc::UnboundedReceiver<LinkSignal>,107
service,61
mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>,108
activity,62
) {109
resend,63
let mut state = LinkState::default();110
endpoint_id: None,64
let mut check = interval(CHECK_INTERVAL);111
registered: false,65
check.set_missed_tick_behavior(MissedTickBehavior::Delay);112
applied: ActivityReporting::Transport,66
loop {113
down_since: None,67
tokio::select! {114
last_report: None,68
signal = signals.recv() => {115
retry: RetryState::default(),69
let Some(signal) = signal else { return };116
}70
apply_signal(&service, &mut state, signal).await;117
}71
}118
72
Ok(()) = activity.changed() => {119
async fn run(73
let active = *activity.borrow_and_update();120
mut self,74
report_if_due(&service, &mut state, active, true).await;121
mut signals: mpsc::UnboundedReceiver<LinkSignal>,122
mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>,123
) {124
let mut check = interval(CHECK_INTERVAL);125
check.set_missed_tick_behavior(MissedTickBehavior::Delay);126
loop {127
tokio::select! {128
signal = signals.recv() => {129
let Some(signal) = signal else { return };130
self.apply(signal).await;131
}132
Ok(()) = self.activity.changed() => {133
self.activity.borrow_and_update();134
self.reconcile(true).await;135
}136
_ = check.tick() => self.reconcile(false).await,137
Some(done) = unregisters.recv() => {138
if let Some(endpoint_id) = &self.endpoint_id {139
let _ = self.service.unregister_endpoint(endpoint_id).await;140
}141
let _ = done.send(());142
}75
}143
}76
_ = check.tick() => {144
}77
if let Some(endpoint_id) = state.endpoint_id.clone().filter(|_| !state.registered) {145
}78
state.registered = register(&service, &endpoint_id).await;146
147
async fn apply(&mut self, signal: LinkSignal) {148
match signal {149
LinkSignal::Endpoint(endpoint_id) => {150
if self.endpoint_id.as_deref() == Some(endpoint_id.as_str()) {151
return;152
}153
if let Some(previous) = self.endpoint_id.replace(endpoint_id) {154
let _ = self.service.unregister_endpoint(&previous).await;79
}155
}80
let active = *activity.borrow();156
self.registered = false;81
report_if_due(&service, &mut state, active, false).await;157
self.applied = ActivityReporting::Transport;158
self.down_since = None;159
self.last_report = None;160
self.retry.succeeded();82
}161
}83
Some(done) = unregisters.recv() => {162
LinkSignal::Connected => {84
if let Some(endpoint_id) = &state.endpoint_id {163
if self.down_since.take().is_some() {85
let _ = service.unregister_endpoint(endpoint_id).await;164
self.last_report = None;165
self.retry.succeeded();86
}166
}87
let _ = done.send(());167
}168
LinkSignal::Disconnected => {169
self.down_since.get_or_insert_with(Instant::now);88
}170
}89
}171
}172
self.reconcile(false).await;90
}173
}91
}92
174
93
async fn apply_signal<T: CardTransport>(service: &PresenceService<T>, state: &mut LinkState, signal: LinkSignal) {175
async fn reconcile(&mut self, activity_changed: bool) {94
match signal {176
let Some(endpoint_id) = self.endpoint_id.clone() else {95
LinkSignal::Endpoint(endpoint_id) => {177
return;96
state.registered = register(service, &endpoint_id).await;178
};97
state.endpoint_id = Some(endpoint_id);179
let now = Instant::now();98
state.down_since = None;180
let down_for = self.down_since.map(|since| now.duration_since(since));99
state.last_report = None;181
let wanted = match down_for {182
Some(down_for) if down_for >= FALLBACK_AFTER => ActivityReporting::Direct,183
_ => ActivityReporting::Transport,184
};185
if (!self.registered || self.applied != wanted) && self.retry.may_attempt(now) {186
self.register(&endpoint_id, wanted, now).await;100
}187
}101
LinkSignal::Connected => {188
if wanted != ActivityReporting::Direct || !self.registered || self.applied != wanted {102
state.down_since = None;189
return;103
state.last_report = None;104
}190
}105
LinkSignal::Disconnected => {191
let since_last_report = self.last_report.map(|last| now.duration_since(last));106
state.down_since.get_or_insert_with(Instant::now);192
if report_due(down_for, since_last_report, activity_changed) {193
self.last_report = Some(now);194
let active = *self.activity.borrow();195
self.report_with_recovery(&endpoint_id, active).await;107
}196
}108
}197
}109
}110
198
111
async fn register<T: CardTransport>(service: &PresenceService<T>, endpoint_id: &str) -> bool {199
async fn register(&mut self, endpoint_id: &str, reporting: ActivityReporting, now: Instant) {112
match service.register_endpoint(endpoint_id).await {200
match self.service.register_endpoint(endpoint_id, reporting).await {113
Ok(()) => true,201
Ok(()) => {114
Err(error) => {202
self.registered = true;115
crate::diagnostics::record(format!("presence: endpoint not registered: {error}"));203
self.applied = reporting;116
false204
self.retry.succeeded();205
if reporting == ActivityReporting::Transport {206
self.resend.notify_one();207
}208
}209
Err(error) => {210
if let Some(message) = self.retry.failed(now, &error) {211
crate::diagnostics::record(format!("presence: endpoint not registered: {message}"));212
}213
}117
}214
}118
}215
}119
}120
121
async fn report_if_due<T: CardTransport>(122
service: &PresenceService<T>,123
state: &mut LinkState,124
active: bool,125
activity_changed: bool,126
) {127
let Some(endpoint_id) = state.endpoint_id.clone() else {128
return;129
};130
let now = Instant::now();131
let down_for = state.down_since.map(|since| now.duration_since(since));132
let since_last_report = state.last_report.map(|last| now.duration_since(last));133
if !report_due(down_for, since_last_report, activity_changed) {134
return;135
}136
state.last_report = Some(now);137
report_with_recovery(service, &endpoint_id, active).await;138
}139
216
140
async fn report_with_recovery<T: CardTransport>(service: &PresenceService<T>, endpoint_id: &str, active: bool) {217
async fn report_with_recovery(&self, endpoint_id: &str, active: bool) {141
let Err(error) = service.report_activity(endpoint_id, active).await else {218
let Err(error) = self.service.report_activity(endpoint_id, active).await else {142
return;219
return;143
};220
};144
if is_endpoint_missing(&error)221
if is_endpoint_missing(&error)145
&& service.register_endpoint(endpoint_id).await.is_ok()222
&& self146
&& service.report_activity(endpoint_id, active).await.is_ok()223
.service147
{224
.register_endpoint(endpoint_id, ActivityReporting::Direct)148
return;225
.await226
.is_ok()227
&& self.service.report_activity(endpoint_id, active).await.is_ok()228
{229
return;230
}231
crate::diagnostics::record(format!("presence: activity not reported: {error}"));149
}232
}150
crate::diagnostics::record(format!("presence: activity not reported: {error}"));151
}233
}152
234
153
#[cfg(test)]235
#[cfg(test)]154
mod tests {236
mod tests {155
use std::sync::{Arc, Mutex};237
use std::sync::Mutex;156
238
157
use chatsvc::Result;239
use chatsvc::Result;158
use session::{ApiResponse, Method, Request, Scope};240
use session::{ApiResponse, Method, Request, Scope};159
241
160
use super::*;242
use super::*;161
243
244
const PRESENCE: &str = "https://presence.teams.microsoft.com/v1/me";245
246
type Sent = Arc<Mutex<Vec<(Method, String, Option<String>)>>>;247
162
struct Scripted {248
struct Scripted {163
statuses: Mutex<Vec<u16>>,249
statuses: Mutex<Vec<u16>>,164
sent: Arc<Mutex<Vec<(Method, String)>>>,250
sent: Sent,165
}251
}166
252
167
impl CardTransport for Scripted {253
impl CardTransport for Scripted {168
async fn send(&self, request: Request, _scope: Scope) -> Result<ApiResponse> {254
async fn send(&self, request: Request, _scope: Scope) -> Result<ApiResponse> {169
self.sent.lock().unwrap().push((request.method, request.url));255
let reporting = request170
let status = self.statuses.lock().unwrap().remove(0);256
.body257
.as_ref()258
.and_then(|body| body["activityReporting"].as_str())259
.map(str::to_owned);260
self.sent.lock().unwrap().push((request.method, request.url, reporting));261
let mut statuses = self.statuses.lock().unwrap();262
let status = if statuses.is_empty() { 200 } else { statuses.remove(0) };171
Ok(ApiResponse {263
Ok(ApiResponse {172
status,264
status,173
body: serde_json::Value::Null,265
body: serde_json::Value::Null,@@ -176,6 +268,28 @@ mod tests {176
}268
}177
}269
}178
270
271
fn link(statuses: Vec<u16>) -> (Link<Scripted>, Sent, Arc<Notify>) {272
let sent: Sent = Arc::default();273
let resend = Arc::new(Notify::new());274
let (_, activity) = watch::channel(true);275
let service = PresenceService::with_transport(Scripted {276
statuses: Mutex::new(statuses),277
sent: sent.clone(),278
});279
(Link::new(service, activity, resend.clone()), sent, resend)280
}281
282
fn calls(sent: &Sent) -> Vec<String> {283
sent.lock()284
.unwrap()285
.iter()286
.map(|(method, url, reporting)| {287
let path = url.strip_prefix(PRESENCE).unwrap();288
format!("{} {path} {}", method.as_str(), reporting.as_deref().unwrap_or("-"))289
})290
.collect()291
}292
179
fn seconds(count: u64) -> Duration {293
fn seconds(count: u64) -> Duration {180
Duration::from_secs(count)294
Duration::from_secs(count)181
}295
}@@ -190,22 +304,98 @@ mod tests {190
assert!(report_due(Some(seconds(150)), Some(seconds(30)), true));304
assert!(report_due(Some(seconds(150)), Some(seconds(30)), true));191
}305
}192
306
307
#[test]308
fn retry_delay_doubles_up_to_four_minutes() {309
let delays: Vec<u64> = (1..=6).map(|failures| retry_delay(failures).as_secs()).collect();310
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);311
}312
313
#[test]314
fn only_client_errors_other_than_auth_and_missing_are_permanent() {315
assert!(is_permanent_failure(Some(400)));316
assert!(is_permanent_failure(Some(403)));317
assert!(!is_permanent_failure(Some(401)));318
assert!(!is_permanent_failure(Some(404)));319
assert!(!is_permanent_failure(Some(429)));320
assert!(!is_permanent_failure(Some(500)));321
assert!(!is_permanent_failure(None));322
}323
324
#[tokio::test]325
async fn a_repeated_identical_failure_is_logged_once_and_backs_off() {326
let error = chatsvc::Error::UnexpectedAnswer("x".into());327
let mut retry = RetryState::default();328
let now = Instant::now();329
assert!(retry.failed(now, &error).is_some());330
assert!(retry.failed(now, &error).is_none());331
assert!(!retry.may_attempt(now + seconds(59)));332
assert!(retry.may_attempt(now + seconds(60)));333
retry.succeeded();334
assert!(retry.may_attempt(now));335
}336
337
#[tokio::test]338
async fn a_permanent_failure_stops_retrying_until_a_new_endpoint() {339
let (mut link, sent, _) = link(vec![403]);340
link.apply(LinkSignal::Endpoint("a".into())).await;341
link.reconcile(false).await;342
assert_eq!(calls(&sent).len(), 1);343
assert!(!link.retry.may_attempt(Instant::now() + seconds(10_000)));344
link.apply(LinkSignal::Endpoint("b".into())).await;345
assert_eq!(calls(&sent).len(), 3);346
}347
348
#[tokio::test]349
async fn the_same_endpoint_announced_again_is_not_registered_again() {350
let (mut link, sent, resend) = link(vec![]);351
link.apply(LinkSignal::Endpoint("a".into())).await;352
link.apply(LinkSignal::Endpoint("a".into())).await;353
link.apply(LinkSignal::Connected).await;354
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);355
resend.notified().await;356
}357
358
#[tokio::test]359
async fn a_new_endpoint_removes_the_old_one_first() {360
let (mut link, sent, _) = link(vec![]);361
link.apply(LinkSignal::Endpoint("a".into())).await;362
link.apply(LinkSignal::Endpoint("b".into())).await;363
assert_eq!(364
calls(&sent),365
["PUT /endpoints/ Transport", "DELETE /endpoints/a -", "PUT /endpoints/ Transport"]366
);367
}368
369
#[tokio::test]370
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {371
let (mut link, sent, resend) = link(vec![]);372
link.apply(LinkSignal::Endpoint("a".into())).await;373
resend.notified().await;374
link.down_since = Some(Instant::now() - seconds(130));375
link.reconcile(false).await;376
link.apply(LinkSignal::Connected).await;377
assert_eq!(378
calls(&sent),379
[380
"PUT /endpoints/ Transport",381
"PUT /endpoints/ Direct",382
"POST /reportmyactivity/ -",383
"PUT /endpoints/ Transport",384
]385
);386
resend.notified().await;387
}388
193
#[tokio::test]389
#[tokio::test]194
async fn a_missing_endpoint_is_registered_again_before_the_report_is_repeated() {390
async fn a_missing_endpoint_is_registered_again_before_the_report_is_repeated() {195
let sent = Arc::new(Mutex::new(Vec::new()));391
let (link, sent, _) = link(vec![404, 200, 200]);196
let service = PresenceService::with_transport(Scripted {392
link.report_with_recovery("epid-1", true).await;197
statuses: Mutex::new(vec![404, 200, 200]),198
sent: sent.clone(),199
});200
report_with_recovery(&service, "epid-1", true).await;201
let sent = sent.lock().unwrap();202
let calls: Vec<(Method, &str)> = sent.iter().map(|(method, url)| (*method, url.as_str())).collect();203
assert_eq!(393
assert_eq!(204
calls,394
calls(&sent),205
[395
[206
(Method::Post, "https://presence.teams.microsoft.com/v1/me/reportmyactivity/"),396
"POST /reportmyactivity/ -",207
(Method::Put, "https://presence.teams.microsoft.com/v1/me/endpoints/"),397
"PUT /endpoints/ Direct",208
(Method::Post, "https://presence.teams.microsoft.com/v1/me/reportmyactivity/"),398
"POST /reportmyactivity/ -",209
]399
]210
);400
);211
}401
}@@ -2,6 +2,7 @@ use std::sync::Arc;
2
2
use std::sync::atomic::{AtomicU64, Ordering};
3
3
use std::time::{Duration, Instant};
4
4
5
use gpui_kit::{DispatchPhase, IntoElement, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};
5
6
use tokio::sync::watch;
6
7
7
8
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
@@ -12,11 +13,13 @@ pub struct UserInput {
12
13
last_input_millis: AtomicU64,
13
14
}
14
15
16
const NO_INPUT: u64 = u64::MAX;
17
15
18
impl UserInput {
16
19
pub fn new() -> Arc<Self> {
17
20
Arc::new(UserInput {
18
21
origin: Instant::now(),
19
last_input_millis: AtomicU64::new(0),
22
last_input_millis: AtomicU64::new(NO_INPUT),
20
23
})
21
24
}
22
25
@@ -25,29 +28,56 @@ impl UserInput {
25
28
self.last_input_millis.store(elapsed, Ordering::Relaxed);
26
29
}
27
30
28
fn last_input(&self) -> Instant {
29
self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))
31
fn last_input(&self) -> Option<Instant> {
32
match self.last_input_millis.load(Ordering::Relaxed) {
33
NO_INPUT => None,
34
millis => Some(self.origin + Duration::from_millis(millis)),
35
}
30
36
}
31
37
}
32
38
33
pub fn latest_input(app_input: Instant, system_idle: Option<Duration>, now: Instant) -> Instant {
34
match system_idle.and_then(|idle| now.checked_sub(idle)) {
35
Some(system_input) => app_input.max(system_input),
36
None => app_input,
37
}
39
pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {
40
canvas(
41
|_, _, _| {},
42
move |_, _, window, _| {
43
let moved = input.clone();
44
window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {
45
if phase == DispatchPhase::Capture {
46
moved.touch();
47
}
48
});
49
let pressed = input.clone();
50
window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {
51
if phase == DispatchPhase::Capture {
52
pressed.touch();
53
}
54
});
55
let scrolled = input.clone();
56
window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {
57
if phase == DispatchPhase::Capture {
58
scrolled.touch();
59
}
60
});
61
},
62
)
63
}
64
65
pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {
66
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));
67
app_input.max(system_input)
38
68
}
39
69
40
pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {
41
now.saturating_duration_since(last_input) < idle_after
70
pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {
71
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)
42
72
}
43
73
44
pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {
74
pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {
45
75
let current = is_active(last_input, now, idle_after);
46
76
(current != previous).then_some(current)
47
77
}
48
78
49
79
pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
50
let (sender, receiver) = watch::channel(true);
80
let (sender, receiver) = watch::channel(false);
51
81
crate::runtime::handle().spawn(async move {
52
82
let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
53
83
loop {
@@ -94,35 +124,47 @@ mod tests {
94
124
#[test]
95
125
fn active_until_the_idle_threshold() {
96
126
let last_input = Instant::now();
97
assert!(is_active(last_input, last_input + seconds(299), IDLE_AFTER));
98
assert!(!is_active(last_input, last_input + seconds(300), IDLE_AFTER));
99
assert!(is_active(last_input + seconds(10), last_input, IDLE_AFTER));
127
assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));
128
assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));
129
assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));
130
}
131
132
#[test]
133
fn without_any_input_the_user_is_inactive() {
134
assert!(!is_active(None, Instant::now(), IDLE_AFTER));
135
assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);
100
136
}
101
137
102
138
#[test]
103
139
fn only_a_change_of_state_is_reported() {
104
let last_input = Instant::now();
105
assert_eq!(activity_change(true, last_input, last_input + seconds(10), IDLE_AFTER), None);
106
assert_eq!(activity_change(true, last_input, last_input + seconds(301), IDLE_AFTER), Some(false));
107
assert_eq!(activity_change(false, last_input, last_input + seconds(301), IDLE_AFTER), None);
108
assert_eq!(activity_change(false, last_input + seconds(400), last_input + seconds(401), IDLE_AFTER), Some(true));
140
let last_input = Some(Instant::now());
141
let at = |offset: u64| last_input.unwrap() + seconds(offset);
142
assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);
143
assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));
144
assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);
145
assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));
146
assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));
109
147
}
110
148
111
149
#[test]
112
150
fn system_input_counts_when_newer_than_app_input() {
113
151
let now = Instant::now() + seconds(1000);
114
let app_input = now - seconds(900);
115
assert_eq!(latest_input(app_input, Some(seconds(20)), now), now - seconds(20));
152
let app_input = Some(now - seconds(900));
153
assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));
116
154
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
117
155
assert_eq!(latest_input(app_input, None, now), app_input);
156
assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));
157
assert_eq!(latest_input(None, None, now), None);
118
158
}
119
159
120
160
#[test]
121
fn touch_moves_the_last_input_forward() {
161
fn touch_sets_and_moves_the_last_input_forward() {
122
162
let input = UserInput::new();
123
let before = input.last_input();
163
assert_eq!(input.last_input(), None);
164
input.touch();
165
let first = input.last_input().unwrap();
124
166
std::thread::sleep(Duration::from_millis(5));
125
167
input.touch();
126
assert!(input.last_input() > before);
168
assert!(input.last_input().unwrap() > first);
127
169
}
128
170
}
@@ -2,6 +2,7 @@ use std::sync::Arc;2
use std::sync::atomic::{AtomicU64, Ordering};2
use std::sync::atomic::{AtomicU64, Ordering};3
use std::time::{Duration, Instant};3
use std::time::{Duration, Instant};4
4
5
use gpui_kit::{DispatchPhase, IntoElement, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};5
use tokio::sync::watch;6
use tokio::sync::watch;6
7
7
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);8
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);@@ -12,11 +13,13 @@ pub struct UserInput {12
last_input_millis: AtomicU64,13
last_input_millis: AtomicU64,13
}14
}14
15
16
const NO_INPUT: u64 = u64::MAX;17
15
impl UserInput {18
impl UserInput {16
pub fn new() -> Arc<Self> {19
pub fn new() -> Arc<Self> {17
Arc::new(UserInput {20
Arc::new(UserInput {18
origin: Instant::now(),21
origin: Instant::now(),19
last_input_millis: AtomicU64::new(0),22
last_input_millis: AtomicU64::new(NO_INPUT),20
})23
})21
}24
}22
25
@@ -25,29 +28,56 @@ impl UserInput {25
self.last_input_millis.store(elapsed, Ordering::Relaxed);28
self.last_input_millis.store(elapsed, Ordering::Relaxed);26
}29
}27
30
28
fn last_input(&self) -> Instant {31
fn last_input(&self) -> Option<Instant> {29
self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))32
match self.last_input_millis.load(Ordering::Relaxed) {33
NO_INPUT => None,34
millis => Some(self.origin + Duration::from_millis(millis)),35
}30
}36
}31
}37
}32
38
33
pub fn latest_input(app_input: Instant, system_idle: Option<Duration>, now: Instant) -> Instant {39
pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {34
match system_idle.and_then(|idle| now.checked_sub(idle)) {40
canvas(35
Some(system_input) => app_input.max(system_input),41
|_, _, _| {},36
None => app_input,42
move |_, _, window, _| {37
}43
let moved = input.clone();44
window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {45
if phase == DispatchPhase::Capture {46
moved.touch();47
}48
});49
let pressed = input.clone();50
window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {51
if phase == DispatchPhase::Capture {52
pressed.touch();53
}54
});55
let scrolled = input.clone();56
window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {57
if phase == DispatchPhase::Capture {58
scrolled.touch();59
}60
});61
},62
)63
}64
65
pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {66
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));67
app_input.max(system_input)38
}68
}39
69
40
pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {70
pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {41
now.saturating_duration_since(last_input) < idle_after71
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)42
}72
}43
73
44
pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {74
pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {45
let current = is_active(last_input, now, idle_after);75
let current = is_active(last_input, now, idle_after);46
(current != previous).then_some(current)76
(current != previous).then_some(current)47
}77
}48
78
49
pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {79
pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {50
let (sender, receiver) = watch::channel(true);80
let (sender, receiver) = watch::channel(false);51
crate::runtime::handle().spawn(async move {81
crate::runtime::handle().spawn(async move {52
let mut interval = tokio::time::interval(SAMPLE_INTERVAL);82
let mut interval = tokio::time::interval(SAMPLE_INTERVAL);53
loop {83
loop {@@ -94,35 +124,47 @@ mod tests {94
#[test]124
#[test]95
fn active_until_the_idle_threshold() {125
fn active_until_the_idle_threshold() {96
let last_input = Instant::now();126
let last_input = Instant::now();97
assert!(is_active(last_input, last_input + seconds(299), IDLE_AFTER));127
assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));98
assert!(!is_active(last_input, last_input + seconds(300), IDLE_AFTER));128
assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));99
assert!(is_active(last_input + seconds(10), last_input, IDLE_AFTER));129
assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));130
}131
132
#[test]133
fn without_any_input_the_user_is_inactive() {134
assert!(!is_active(None, Instant::now(), IDLE_AFTER));135
assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);100
}136
}101
137
102
#[test]138
#[test]103
fn only_a_change_of_state_is_reported() {139
fn only_a_change_of_state_is_reported() {104
let last_input = Instant::now();140
let last_input = Some(Instant::now());105
assert_eq!(activity_change(true, last_input, last_input + seconds(10), IDLE_AFTER), None);141
let at = |offset: u64| last_input.unwrap() + seconds(offset);106
assert_eq!(activity_change(true, last_input, last_input + seconds(301), IDLE_AFTER), Some(false));142
assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);107
assert_eq!(activity_change(false, last_input, last_input + seconds(301), IDLE_AFTER), None);143
assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));108
assert_eq!(activity_change(false, last_input + seconds(400), last_input + seconds(401), IDLE_AFTER), Some(true));144
assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);145
assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));146
assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));109
}147
}110
148
111
#[test]149
#[test]112
fn system_input_counts_when_newer_than_app_input() {150
fn system_input_counts_when_newer_than_app_input() {113
let now = Instant::now() + seconds(1000);151
let now = Instant::now() + seconds(1000);114
let app_input = now - seconds(900);152
let app_input = Some(now - seconds(900));115
assert_eq!(latest_input(app_input, Some(seconds(20)), now), now - seconds(20));153
assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));116
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);154
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);117
assert_eq!(latest_input(app_input, None, now), app_input);155
assert_eq!(latest_input(app_input, None, now), app_input);156
assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));157
assert_eq!(latest_input(None, None, now), None);118
}158
}119
159
120
#[test]160
#[test]121
fn touch_moves_the_last_input_forward() {161
fn touch_sets_and_moves_the_last_input_forward() {122
let input = UserInput::new();162
let input = UserInput::new();123
let before = input.last_input();163
assert_eq!(input.last_input(), None);164
input.touch();165
let first = input.last_input().unwrap();124
std::thread::sleep(Duration::from_millis(5));166
std::thread::sleep(Duration::from_millis(5));125
input.touch();167
input.touch();126
assert!(input.last_input() > before);168
assert!(input.last_input().unwrap() > first);127
}169
}128
}170
}@@ -31,7 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
31
31
use crate::call::{CallMedia, CallWindows};
32
32
use crate::embedded_web::{Overlays, RootFocus};
33
33
use crate::notice::NoticeAction;
34
use crate::user_activity::UserInput;
34
use crate::user_activity::{self, UserInput};
35
35
use crate::notify::{NotificationCenter, selection_for};
36
36
use crate::sidebar_model::Step;
37
37
use crate::theme;
@@ -626,9 +626,6 @@ impl Render for AppShell {
626
626
.id("app-shell")
627
627
.key_context("AppShell")
628
628
.track_focus(&self.focus_handle)
629
.on_mouse_move(cx.listener(|this, _, _, _| this.user_input.touch()))
630
.capture_any_mouse_down(cx.listener(|this, _, _, _| this.user_input.touch()))
631
.on_scroll_wheel(cx.listener(|this, _, _, _| this.user_input.touch()))
632
629
.on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
633
630
this.toggle_switcher("", window, cx);
634
631
}))
@@ -699,6 +696,7 @@ impl Render for AppShell {
699
696
.text_color(theme::text())
700
697
.text_size(px(14.))
701
698
.child(crate::frame_log::probe("first"))
699
.child(user_activity::input_probe(self.user_input.clone()))
702
700
.child(
703
701
v_flex()
704
702
.size_full()
@@ -31,7 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};31
use crate::call::{CallMedia, CallWindows};31
use crate::call::{CallMedia, CallWindows};32
use crate::embedded_web::{Overlays, RootFocus};32
use crate::embedded_web::{Overlays, RootFocus};33
use crate::notice::NoticeAction;33
use crate::notice::NoticeAction;34
use crate::user_activity::UserInput;34
use crate::user_activity::{self, UserInput};35
use crate::notify::{NotificationCenter, selection_for};35
use crate::notify::{NotificationCenter, selection_for};36
use crate::sidebar_model::Step;36
use crate::sidebar_model::Step;37
use crate::theme;37
use crate::theme;@@ -626,9 +626,6 @@ impl Render for AppShell {626
.id("app-shell")626
.id("app-shell")627
.key_context("AppShell")627
.key_context("AppShell")628
.track_focus(&self.focus_handle)628
.track_focus(&self.focus_handle)629
.on_mouse_move(cx.listener(|this, _, _, _| this.user_input.touch()))630
.capture_any_mouse_down(cx.listener(|this, _, _, _| this.user_input.touch()))631
.on_scroll_wheel(cx.listener(|this, _, _, _| this.user_input.touch()))632
.on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {629
.on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {633
this.toggle_switcher("", window, cx);630
this.toggle_switcher("", window, cx);634
}))631
}))@@ -699,6 +696,7 @@ impl Render for AppShell {699
.text_color(theme::text())696
.text_color(theme::text())700
.text_size(px(14.))697
.text_size(px(14.))701
.child(crate::frame_log::probe("first"))698
.child(crate::frame_log::probe("first"))699
.child(user_activity::input_probe(self.user_input.clone()))702
.child(700
.child(703
v_flex()701
v_flex()704
.size_full()702
.size_full()@@ -306,6 +306,7 @@
306
306
},
307
307
shutdown,
308
308
setActivity,
309
resendActivity: () => transmitActivity(false),
309
310
reply: (id, status, body) => answer(id, status, body),
310
311
stop: async () => {
311
312
let unregistered = null;
@@ -306,6 +306,7 @@306
},306
},307
shutdown,307
shutdown,308
setActivity,308
setActivity,309
resendActivity: () => transmitActivity(false),309
reply: (id, status, body) => answer(id, status, body),310
reply: (id, status, body) => answer(id, status, body),310
stop: async () => {311
stop: async () => {311
let unregistered = null;312
let unregistered = null;@@ -1,6 +1,6 @@
1
1
use std::time::Duration;
2
2
3
use chatsvc::{PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3
use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
4
4
use session::{DEFAULT_ENDPOINT, Session};
5
5
6
6
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -25,8 +25,8 @@ async fn main() {
25
25
let endpoint_id = wait_for_endpoint(&mut realtime).await;
26
26
println!("# trouter connected");
27
27
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id).await));
29
realtime.set_activity(true);
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
29
realtime.resend_activity();
30
30
println!("# sent active");
31
31
tokio::time::sleep(SETTLE).await;
32
32
print_own_presence(&presence, &user_id).await;
@@ -1,6 +1,6 @@1
use std::time::Duration;1
use std::time::Duration;2
2
3
use chatsvc::{PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};3
use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};4
use session::{DEFAULT_ENDPOINT, Session};4
use session::{DEFAULT_ENDPOINT, Session};5
5
6
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);6
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);@@ -25,8 +25,8 @@ async fn main() {25
let endpoint_id = wait_for_endpoint(&mut realtime).await;25
let endpoint_id = wait_for_endpoint(&mut realtime).await;26
println!("# trouter connected");26
println!("# trouter connected");27
27
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id).await));28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));29
realtime.set_activity(true);29
realtime.resend_activity();30
println!("# sent active");30
println!("# sent active");31
tokio::time::sleep(SETTLE).await;31
tokio::time::sleep(SETTLE).await;32
print_own_presence(&presence, &user_id).await;32
print_own_presence(&presence, &user_id).await;@@ -43,8 +43,8 @@ pub use pins::{
43
43
PinnedMessage, Pins, TeamLayout,
44
44
};
45
45
pub use presence::{
46
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47
WorkLocationKind, WorkLocationSource, is_endpoint_missing,
46
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
47
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
48
48
};
49
49
pub use reactions::{emotion_key, emotion_keys};
50
50
pub use realtime::{
@@ -43,8 +43,8 @@ pub use pins::{43
PinnedMessage, Pins, TeamLayout,43
PinnedMessage, Pins, TeamLayout,44
};44
};45
pub use presence::{45
pub use presence::{46
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,46
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,47
WorkLocationKind, WorkLocationSource, is_endpoint_missing,47
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,48
};48
};49
pub use reactions::{emotion_key, emotion_keys};49
pub use reactions::{emotion_key, emotion_keys};50
pub use realtime::{50
pub use realtime::{@@ -53,6 +53,21 @@ impl ForcedKind {
53
53
}
54
54
}
55
55
56
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57
pub enum ActivityReporting {
58
Transport,
59
Direct,
60
}
61
62
impl ActivityReporting {
63
fn code(self) -> &'static str {
64
match self {
65
ActivityReporting::Transport => "Transport",
66
ActivityReporting::Direct => "Direct",
67
}
68
}
69
}
70
56
71
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57
72
pub struct ForcedAvailability {
58
73
pub kind: ForcedKind,
@@ -132,9 +147,9 @@ impl<T: CardTransport> PresenceService<T> {
132
147
self.send(request, &url).await.map(drop)
133
148
}
134
149
135
pub async fn register_endpoint(&self, endpoint_id: &str) -> Result<()> {
150
pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
136
151
let url = format!("{BASE_URL}/me/endpoints/");
137
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id));
152
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
138
153
request.headers = endpoint_headers(endpoint_id);
139
154
self.send(request, &url).await.map(drop)
140
155
}
@@ -211,16 +226,23 @@ impl<T: CardTransport> PresenceService<T> {
211
226
}
212
227
}
213
228
229
pub fn error_status(error: &Error) -> Option<u16> {
230
match error {
231
Error::Session(session::Error::Api { status, .. }) => Some(*status),
232
_ => None,
233
}
234
}
235
214
236
pub fn is_endpoint_missing(error: &Error) -> bool {
215
matches!(error, Error::Session(session::Error::Api { status: 404, .. }))
237
error_status(error) == Some(404)
216
238
}
217
239
218
fn endpoint_body(endpoint_id: &str) -> Value {
240
fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value {
219
241
json!({
220
242
"id": endpoint_id,
221
243
"availability": "Available",
222
244
"activity": "Available",
223
"activityReporting": "Transport",
245
"activityReporting": reporting.code(),
224
246
"deviceType": "Desktop",
225
247
})
226
248
}
@@ -480,7 +502,7 @@ mod tests {
480
502
#[tokio::test]
481
503
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
482
504
let service = service(200, Value::Null);
483
service.register_endpoint("epid-1").await.unwrap();
505
service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
484
506
let (request, scope) = only_request(&service);
485
507
assert_eq!(request.method, Method::Put);
486
508
assert_eq!(
@@ -508,6 +530,14 @@ mod tests {
508
530
);
509
531
}
510
532
533
#[tokio::test]
534
async fn register_endpoint_can_switch_to_direct_reporting() {
535
let service = service(200, Value::Null);
536
service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
537
let (request, _) = only_request(&service);
538
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539
}
540
511
541
#[tokio::test]
512
542
async fn unregister_endpoint_deletes_by_id_without_body() {
513
543
let service = service(200, Value::Null);
@@ -53,6 +53,21 @@ impl ForcedKind {53
}53
}54
}54
}55
55
56
#[derive(Debug, Clone, Copy, PartialEq, Eq)]57
pub enum ActivityReporting {58
Transport,59
Direct,60
}61
62
impl ActivityReporting {63
fn code(self) -> &'static str {64
match self {65
ActivityReporting::Transport => "Transport",66
ActivityReporting::Direct => "Direct",67
}68
}69
}70
56
#[derive(Debug, Clone, Copy, PartialEq, Eq)]71
#[derive(Debug, Clone, Copy, PartialEq, Eq)]57
pub struct ForcedAvailability {72
pub struct ForcedAvailability {58
pub kind: ForcedKind,73
pub kind: ForcedKind,@@ -132,9 +147,9 @@ impl<T: CardTransport> PresenceService<T> {132
self.send(request, &url).await.map(drop)147
self.send(request, &url).await.map(drop)133
}148
}134
149
135
pub async fn register_endpoint(&self, endpoint_id: &str) -> Result<()> {150
pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {136
let url = format!("{BASE_URL}/me/endpoints/");151
let url = format!("{BASE_URL}/me/endpoints/");137
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id));152
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));138
request.headers = endpoint_headers(endpoint_id);153
request.headers = endpoint_headers(endpoint_id);139
self.send(request, &url).await.map(drop)154
self.send(request, &url).await.map(drop)140
}155
}@@ -211,16 +226,23 @@ impl<T: CardTransport> PresenceService<T> {211
}226
}212
}227
}213
228
229
pub fn error_status(error: &Error) -> Option<u16> {230
match error {231
Error::Session(session::Error::Api { status, .. }) => Some(*status),232
_ => None,233
}234
}235
214
pub fn is_endpoint_missing(error: &Error) -> bool {236
pub fn is_endpoint_missing(error: &Error) -> bool {215
matches!(error, Error::Session(session::Error::Api { status: 404, .. }))237
error_status(error) == Some(404)216
}238
}217
239
218
fn endpoint_body(endpoint_id: &str) -> Value {240
fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value {219
json!({241
json!({220
"id": endpoint_id,242
"id": endpoint_id,221
"availability": "Available",243
"availability": "Available",222
"activity": "Available",244
"activity": "Available",223
"activityReporting": "Transport",245
"activityReporting": reporting.code(),224
"deviceType": "Desktop",246
"deviceType": "Desktop",225
})247
})226
}248
}@@ -480,7 +502,7 @@ mod tests {480
#[tokio::test]502
#[tokio::test]481
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {503
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {482
let service = service(200, Value::Null);504
let service = service(200, Value::Null);483
service.register_endpoint("epid-1").await.unwrap();505
service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();484
let (request, scope) = only_request(&service);506
let (request, scope) = only_request(&service);485
assert_eq!(request.method, Method::Put);507
assert_eq!(request.method, Method::Put);486
assert_eq!(508
assert_eq!(@@ -508,6 +530,14 @@ mod tests {508
);530
);509
}531
}510
532
533
#[tokio::test]534
async fn register_endpoint_can_switch_to_direct_reporting() {535
let service = service(200, Value::Null);536
service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();537
let (request, _) = only_request(&service);538
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");539
}540
511
#[tokio::test]541
#[tokio::test]512
async fn unregister_endpoint_deletes_by_id_without_body() {542
async fn unregister_endpoint_deletes_by_id_without_body() {513
let service = service(200, Value::Null);543
let service = service(200, Value::Null);@@ -4,12 +4,13 @@ mod host;
4
4
mod runner;
5
5
6
6
use std::pin::Pin;
7
use std::sync::Arc;
7
8
use std::task::{Context, Poll};
8
9
use std::time::Duration;
9
10
10
11
use futures_util::Stream;
11
12
use session::Session;
12
use tokio::sync::{mpsc, oneshot, watch};
13
use tokio::sync::{Notify, mpsc, oneshot, watch};
13
14
use tokio::task::JoinHandle;
14
15
15
16
pub use event::{
@@ -79,6 +80,7 @@ pub struct Realtime {
79
80
callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
80
81
replier: CallbackReplier,
81
82
activity: watch::Sender<bool>,
83
resend: Arc<Notify>,
82
84
stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
83
85
task: JoinHandle<()>,
84
86
}
@@ -98,6 +100,7 @@ impl Realtime {
98
100
let (callback_output, callbacks) = mpsc::unbounded_channel();
99
101
let (reply_sender, replies) = mpsc::unbounded_channel();
100
102
let (activity, activity_receiver) = watch::channel(config.initially_active);
103
let resend = Arc::new(Notify::new());
101
104
let (stop, stop_receiver) = oneshot::channel();
102
105
let mut runner = Runner::new(
103
106
session,
@@ -110,6 +113,7 @@ impl Realtime {
110
113
replies,
111
114
},
112
115
activity_receiver,
116
resend.clone(),
113
117
);
114
118
if let Err(error) = runner.ensure().await {
115
119
attached.shutdown().await;
@@ -124,6 +128,7 @@ impl Realtime {
124
128
sender: reply_sender,
125
129
},
126
130
activity,
131
resend,
127
132
stop: Some(stop),
128
133
task,
129
134
})
@@ -150,6 +155,10 @@ impl Realtime {
150
155
self.activity.send_replace(active);
151
156
}
152
157
158
pub fn resend_activity(&self) {
159
self.resend.notify_one();
160
}
161
153
162
/// Deletes the registration and closes the page-side socket.
154
163
pub async fn stop(mut self) {
155
164
if let Some(stop) = self.stop.take() {
@@ -4,12 +4,13 @@ mod host;4
mod runner;4
mod runner;5
5
6
use std::pin::Pin;6
use std::pin::Pin;7
use std::sync::Arc;7
use std::task::{Context, Poll};8
use std::task::{Context, Poll};8
use std::time::Duration;9
use std::time::Duration;9
10
10
use futures_util::Stream;11
use futures_util::Stream;11
use session::Session;12
use session::Session;12
use tokio::sync::{mpsc, oneshot, watch};13
use tokio::sync::{Notify, mpsc, oneshot, watch};13
use tokio::task::JoinHandle;14
use tokio::task::JoinHandle;14
15
15
pub use event::{16
pub use event::{@@ -79,6 +80,7 @@ pub struct Realtime {79
callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,80
callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,80
replier: CallbackReplier,81
replier: CallbackReplier,81
activity: watch::Sender<bool>,82
activity: watch::Sender<bool>,83
resend: Arc<Notify>,82
stop: Option<oneshot::Sender<oneshot::Sender<()>>>,84
stop: Option<oneshot::Sender<oneshot::Sender<()>>>,83
task: JoinHandle<()>,85
task: JoinHandle<()>,84
}86
}@@ -98,6 +100,7 @@ impl Realtime {98
let (callback_output, callbacks) = mpsc::unbounded_channel();100
let (callback_output, callbacks) = mpsc::unbounded_channel();99
let (reply_sender, replies) = mpsc::unbounded_channel();101
let (reply_sender, replies) = mpsc::unbounded_channel();100
let (activity, activity_receiver) = watch::channel(config.initially_active);102
let (activity, activity_receiver) = watch::channel(config.initially_active);103
let resend = Arc::new(Notify::new());101
let (stop, stop_receiver) = oneshot::channel();104
let (stop, stop_receiver) = oneshot::channel();102
let mut runner = Runner::new(105
let mut runner = Runner::new(103
session,106
session,@@ -110,6 +113,7 @@ impl Realtime {110
replies,113
replies,111
},114
},112
activity_receiver,115
activity_receiver,116
resend.clone(),113
);117
);114
if let Err(error) = runner.ensure().await {118
if let Err(error) = runner.ensure().await {115
attached.shutdown().await;119
attached.shutdown().await;@@ -124,6 +128,7 @@ impl Realtime {124
sender: reply_sender,128
sender: reply_sender,125
},129
},126
activity,130
activity,131
resend,127
stop: Some(stop),132
stop: Some(stop),128
task,133
task,129
})134
})@@ -150,6 +155,10 @@ impl Realtime {150
self.activity.send_replace(active);155
self.activity.send_replace(active);151
}156
}152
157
158
pub fn resend_activity(&self) {159
self.resend.notify_one();160
}161
153
/// Deletes the registration and closes the page-side socket.162
/// Deletes the registration and closes the page-side socket.154
pub async fn stop(mut self) {163
pub async fn stop(mut self) {155
if let Some(stop) = self.stop.take() {164
if let Some(stop) = self.stop.take() {@@ -1,8 +1,9 @@
1
use std::sync::Arc;
1
2
use std::time::Duration;
2
3
3
4
use serde_json::{Value, json};
4
5
use session::{App, Session, TabControl, TabEvents};
5
use tokio::sync::{mpsc, oneshot, watch};
6
use tokio::sync::{Notify, mpsc, oneshot, watch};
6
7
use tokio::time::{MissedTickBehavior, interval, sleep};
7
8
8
9
use super::RealtimeConfig;
@@ -62,6 +63,13 @@ impl PageScript {
62
63
)
63
64
}
64
65
66
fn resend_activity_expression(&self) -> String {
67
format!(
68
"window.{name} ? window.{name}.resendActivity() : null",
69
name = self.global_name
70
)
71
}
72
65
73
fn stop_expression(&self) -> String {
66
74
format!(
67
75
"window.{name} ? window.{name}.stop() : null",
@@ -123,6 +131,7 @@ pub(super) struct Runner {
123
131
host: String,
124
132
output: mpsc::UnboundedSender<RealtimeEvent>,
125
133
activity: watch::Receiver<bool>,
134
resend: Arc<Notify>,
126
135
force_refresh: bool,
127
136
last_error: Option<String>,
128
137
}
@@ -136,6 +145,7 @@ impl Runner {
136
145
output: mpsc::UnboundedSender<RealtimeEvent>,
137
146
callbacks: CallbackPipes,
138
147
activity: watch::Receiver<bool>,
148
resend: Arc<Notify>,
139
149
) -> Self {
140
150
Runner {
141
151
session,
@@ -145,6 +155,7 @@ impl Runner {
145
155
host,
146
156
output,
147
157
activity,
158
resend,
148
159
force_refresh: false,
149
160
last_error: None,
150
161
}
@@ -234,6 +245,10 @@ impl Runner {
234
245
}
235
246
}
236
247
_ = tick.tick() => self.ensure_and_report().await,
248
_ = self.resend.notified() => {
249
let expression = self.script.resend_activity_expression();
250
let _ = attached.control.evaluate(&expression).await;
251
}
237
252
changed = self.activity.changed() => {
238
253
if changed.is_ok() {
239
254
let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
@@ -336,6 +351,15 @@ mod tests {
336
351
);
337
352
}
338
353
354
#[test]
355
fn resend_goes_through_the_page_global() {
356
let script = PageScript::new(&RealtimeConfig::default());
357
assert_eq!(
358
script.resend_activity_expression(),
359
"window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"
360
);
361
}
362
339
363
#[test]
340
364
fn worker_reports_activity_on_change_only() {
341
365
let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
@@ -1,8 +1,9 @@1
use std::sync::Arc;1
use std::time::Duration;2
use std::time::Duration;2
3
3
use serde_json::{Value, json};4
use serde_json::{Value, json};4
use session::{App, Session, TabControl, TabEvents};5
use session::{App, Session, TabControl, TabEvents};5
use tokio::sync::{mpsc, oneshot, watch};6
use tokio::sync::{Notify, mpsc, oneshot, watch};6
use tokio::time::{MissedTickBehavior, interval, sleep};7
use tokio::time::{MissedTickBehavior, interval, sleep};7
8
8
use super::RealtimeConfig;9
use super::RealtimeConfig;@@ -62,6 +63,13 @@ impl PageScript {62
)63
)63
}64
}64
65
66
fn resend_activity_expression(&self) -> String {67
format!(68
"window.{name} ? window.{name}.resendActivity() : null",69
name = self.global_name70
)71
}72
65
fn stop_expression(&self) -> String {73
fn stop_expression(&self) -> String {66
format!(74
format!(67
"window.{name} ? window.{name}.stop() : null",75
"window.{name} ? window.{name}.stop() : null",@@ -123,6 +131,7 @@ pub(super) struct Runner {123
host: String,131
host: String,124
output: mpsc::UnboundedSender<RealtimeEvent>,132
output: mpsc::UnboundedSender<RealtimeEvent>,125
activity: watch::Receiver<bool>,133
activity: watch::Receiver<bool>,134
resend: Arc<Notify>,126
force_refresh: bool,135
force_refresh: bool,127
last_error: Option<String>,136
last_error: Option<String>,128
}137
}@@ -136,6 +145,7 @@ impl Runner {136
output: mpsc::UnboundedSender<RealtimeEvent>,145
output: mpsc::UnboundedSender<RealtimeEvent>,137
callbacks: CallbackPipes,146
callbacks: CallbackPipes,138
activity: watch::Receiver<bool>,147
activity: watch::Receiver<bool>,148
resend: Arc<Notify>,139
) -> Self {149
) -> Self {140
Runner {150
Runner {141
session,151
session,@@ -145,6 +155,7 @@ impl Runner {145
host,155
host,146
output,156
output,147
activity,157
activity,158
resend,148
force_refresh: false,159
force_refresh: false,149
last_error: None,160
last_error: None,150
}161
}@@ -234,6 +245,10 @@ impl Runner {234
}245
}235
}246
}236
_ = tick.tick() => self.ensure_and_report().await,247
_ = tick.tick() => self.ensure_and_report().await,248
_ = self.resend.notified() => {249
let expression = self.script.resend_activity_expression();250
let _ = attached.control.evaluate(&expression).await;251
}237
changed = self.activity.changed() => {252
changed = self.activity.changed() => {238
if changed.is_ok() {253
if changed.is_ok() {239
let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());254
let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());@@ -336,6 +351,15 @@ mod tests {336
);351
);337
}352
}338
353
354
#[test]355
fn resend_goes_through_the_page_global() {356
let script = PageScript::new(&RealtimeConfig::default());357
assert_eq!(358
script.resend_activity_expression(),359
"window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"360
);361
}362
339
#[test]363
#[test]340
fn worker_reports_activity_on_change_only() {364
fn worker_reports_activity_on_change_only() {341
let worker = PageScript::new(&RealtimeConfig::default()).worker_source;365
let worker = PageScript::new(&RealtimeConfig::default()).worker_source;