1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use anyhow::Error;
use async_trait::async_trait;
use fidl::prelude::*;
use fidl_fuchsia_time_external::{
Properties, PushSourceRequest, PushSourceRequestStream, PushSourceWatchSampleResponder,
PushSourceWatchStatusResponder, Status, TimeSample,
};
use fuchsia_zircon as zx;
use futures::{
channel::mpsc::{channel, Receiver, Sender},
lock::Mutex,
StreamExt, TryStreamExt,
};
use std::sync::{Arc, Weak};
use tracing::warn;
use watch_handler::{Sender as WatchSender, WatchHandler};
#[derive(Clone, PartialEq, Debug)]
pub enum Update {
Sample(Arc<TimeSample>),
Status(Status),
}
impl From<Status> for Update {
fn from(status: Status) -> Self {
Update::Status(status)
}
}
impl From<TimeSample> for Update {
fn from(sample: TimeSample) -> Self {
Update::Sample(Arc::new(sample))
}
}
impl Update {
pub fn is_status(&self) -> bool {
match self {
Update::Sample(_) => false,
Update::Status(_) => true,
}
}
}
#[async_trait]
pub trait UpdateAlgorithm {
async fn update_device_properties(&self, properties: Properties);
async fn generate_updates(&self, sink: Sender<Update>) -> Result<(), Error>;
}
pub struct PushSource<UA: UpdateAlgorithm> {
internal: Mutex<PushSourceInternal>,
update_algorithm: UA,
}
impl<UA: UpdateAlgorithm> PushSource<UA> {
pub fn new(update_algorithm: UA, initial_status: Status) -> Result<Self, Error> {
Ok(Self { internal: Mutex::new(PushSourceInternal::new(initial_status)), update_algorithm })
}
pub async fn poll_updates(&self) -> Result<(), Error> {
let (sender, mut receiver) = channel(0);
let updater_fut = self.update_algorithm.generate_updates(sender);
let consumer_fut = async move {
while let Some(update) = receiver.next().await {
self.internal.lock().await.push_update(update).await;
}
};
let (update_res, _) = futures::future::join(updater_fut, consumer_fut).await;
update_res
}
pub async fn handle_requests_for_stream(
&self,
mut request_stream: PushSourceRequestStream,
) -> Result<(), Error> {
let client_context = self.internal.lock().await.register_client();
while let Some(request) = request_stream.try_next().await? {
client_context.lock().await.handle_request(request, &self.update_algorithm).await?;
}
Ok(())
}
}
struct PushSourceInternal {
clients: Vec<Weak<Mutex<PushSourceClientHandler>>>,
latest_sample: Option<Arc<TimeSample>>,
latest_status: Status,
}
impl PushSourceInternal {
pub fn new(initial_status: Status) -> Self {
PushSourceInternal { clients: vec![], latest_sample: None, latest_status: initial_status }
}
pub fn register_client(&mut self) -> Arc<Mutex<PushSourceClientHandler>> {
let client = Arc::new(Mutex::new(PushSourceClientHandler {
sample_watcher: WatchHandler::create(self.latest_sample.clone()),
status_watcher: WatchHandler::create(Some(self.latest_status)),
}));
self.clients.push(Arc::downgrade(&client));
client
}
pub async fn push_update(&mut self, update: Update) {
match &update {
Update::Sample(sample) => self.latest_sample = Some(Arc::clone(&sample)),
Update::Status(status) => self.latest_status = *status,
}
let mut client_arcs = vec![];
self.clients.retain(|client_weak| match client_weak.upgrade() {
Some(client_arc) => {
client_arcs.push(client_arc);
true
}
None => false,
});
for client in client_arcs {
client.lock().await.handle_update(update.clone());
}
}
}
struct PushSourceClientHandler {
sample_watcher: WatchHandler<Arc<TimeSample>, WatchSampleResponder>,
status_watcher: WatchHandler<Status, WatchStatusResponder>,
}
impl PushSourceClientHandler {
async fn handle_request(
&mut self,
request: PushSourceRequest,
update_algorithm: &impl UpdateAlgorithm,
) -> Result<(), Error> {
match request {
PushSourceRequest::WatchSample { responder } => {
self.sample_watcher.watch(WatchSampleResponder(responder)).map_err(|e| {
e.responder.0.control_handle().shutdown_with_epitaph(zx::Status::BAD_STATE);
e
})?;
}
PushSourceRequest::WatchStatus { responder } => {
self.status_watcher.watch(WatchStatusResponder(responder)).map_err(|e| {
e.responder.0.control_handle().shutdown_with_epitaph(zx::Status::BAD_STATE);
e
})?;
}
PushSourceRequest::UpdateDeviceProperties { properties, .. } => {
update_algorithm.update_device_properties(properties).await;
}
}
Ok(())
}
fn handle_update(&mut self, update: Update) {
match update {
Update::Sample(sample) => self.sample_watcher.set_value(sample),
Update::Status(status) => self.status_watcher.set_value(status),
}
}
}
struct WatchSampleResponder(PushSourceWatchSampleResponder);
struct WatchStatusResponder(PushSourceWatchStatusResponder);
impl WatchSender<Arc<TimeSample>> for WatchSampleResponder {
fn send_response(self, data: Arc<TimeSample>) {
let time_sample = TimeSample {
utc: data.utc.clone(),
monotonic: data.monotonic.clone(),
standard_deviation: data.standard_deviation.clone(),
..TimeSample::EMPTY
};
self.0.send(time_sample).unwrap_or_else(|e| warn!("Error sending response: {:?}", e));
}
}
impl WatchSender<Status> for WatchStatusResponder {
fn send_response(self, data: Status) {
self.0.send(data).unwrap_or_else(|e| warn!("Error sending response: {:?}", e));
}
}
pub struct TestUpdateAlgorithm {
receiver: Mutex<Option<Receiver<Update>>>,
device_property_updates: Mutex<Vec<Properties>>,
}
impl TestUpdateAlgorithm {
pub fn new() -> (Self, Sender<Update>) {
let (sender, receiver) = channel(0);
(
TestUpdateAlgorithm {
receiver: Mutex::new(Some(receiver)),
device_property_updates: Mutex::new(vec![]),
},
sender,
)
}
}
#[async_trait]
impl UpdateAlgorithm for TestUpdateAlgorithm {
async fn update_device_properties(&self, properties: Properties) {
self.device_property_updates.lock().await.push(properties);
}
async fn generate_updates(&self, sink: Sender<Update>) -> Result<(), Error> {
let receiver = self.receiver.lock().await.take().unwrap();
receiver.map(Ok).forward(sink).await?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use assert_matches::assert_matches;
use fidl::{endpoints::create_proxy_and_stream, Error as FidlError};
use fidl_fuchsia_time_external::{PushSourceMarker, PushSourceProxy};
use fuchsia_async as fasync;
use futures::{FutureExt, SinkExt};
struct TestHarness {
test_source: Arc<PushSource<TestUpdateAlgorithm>>,
tasks: Vec<fasync::Task<Result<(), Error>>>,
update_sender: Sender<Update>,
}
impl TestHarness {
fn new() -> Self {
let (update_algorithm, update_sender) = TestUpdateAlgorithm::new();
let test_source = Arc::new(PushSource::new(update_algorithm, Status::Ok).unwrap());
let source_clone = Arc::clone(&test_source);
let update_task = fasync::Task::spawn(async move { source_clone.poll_updates().await });
TestHarness { test_source, tasks: vec![update_task], update_sender }
}
fn new_proxy(&mut self) -> PushSourceProxy {
let source_clone = Arc::clone(&self.test_source);
let (proxy, stream) = create_proxy_and_stream::<PushSourceMarker>().unwrap();
let server_task = fasync::Task::spawn(async move {
source_clone.handle_requests_for_stream(stream).await
});
self.tasks.push(server_task);
proxy
}
async fn push_update(&mut self, update: Update) {
self.update_sender.send(update).await.unwrap();
}
async fn assert_device_properties(&self, properties: &[Properties]) {
assert_eq!(
self.test_source.update_algorithm.device_property_updates.lock().await.as_slice(),
properties
);
}
}
#[fuchsia::test(allow_stalls = false)]
async fn test_watch_sample_closes_on_multiple_watches() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
let first_watch_fut = proxy.watch_sample();
assert_matches!(
proxy.watch_sample().await.unwrap_err(),
FidlError::ClientChannelClosed { status: zx::Status::BAD_STATE, .. }
);
assert_matches!(
first_watch_fut.await.unwrap_err(),
FidlError::ClientChannelClosed { status: zx::Status::BAD_STATE, .. }
);
}
#[fuchsia::test(allow_stalls = false)]
async fn test_watch_status_closes_on_multiple_watches() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
assert_eq!(proxy.watch_status().await.unwrap(), Status::Ok);
let second_watch_fut = proxy.watch_status();
assert_matches!(
proxy.watch_status().await.unwrap_err(),
FidlError::ClientChannelClosed { status: zx::Status::BAD_STATE, .. }
);
assert_matches!(
second_watch_fut.await.unwrap_err(),
FidlError::ClientChannelClosed { status: zx::Status::BAD_STATE, .. }
);
}
#[fuchsia::test(allow_stalls = false)]
async fn test_watch_sample() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
let sample_fut = proxy.watch_sample();
harness
.push_update(Update::Sample(Arc::new(TimeSample {
monotonic: Some(23),
utc: Some(24),
standard_deviation: None,
..TimeSample::EMPTY
})))
.await;
assert_eq!(
sample_fut.await.unwrap(),
TimeSample {
monotonic: Some(23),
utc: Some(24),
standard_deviation: None,
..TimeSample::EMPTY
}
);
let sample_fut = proxy.watch_sample();
harness
.push_update(Update::Sample(Arc::new(TimeSample {
monotonic: Some(25),
utc: Some(26),
standard_deviation: None,
..TimeSample::EMPTY
})))
.await;
assert_eq!(
sample_fut.await.unwrap(),
TimeSample {
monotonic: Some(25),
utc: Some(26),
standard_deviation: None,
..TimeSample::EMPTY
}
);
assert!(proxy.watch_sample().now_or_never().is_none());
}
#[fuchsia::test(allow_stalls = false)]
async fn test_watch_sample_sent_to_all_clients() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
let proxy_2 = harness.new_proxy();
let sample_fut = proxy.watch_sample();
let sample_fut_2 = proxy_2.watch_sample();
harness
.push_update(Update::Sample(Arc::new(TimeSample {
monotonic: Some(23),
utc: Some(24),
standard_deviation: None,
..TimeSample::EMPTY
})))
.await;
assert_eq!(
sample_fut.await.unwrap(),
TimeSample {
monotonic: Some(23),
utc: Some(24),
standard_deviation: None,
..TimeSample::EMPTY
}
);
assert_eq!(
sample_fut_2.await.unwrap(),
TimeSample {
monotonic: Some(23),
utc: Some(24),
standard_deviation: None,
..TimeSample::EMPTY
}
);
let sample_fut = proxy.watch_sample();
let sample_fut_2 = proxy_2.watch_sample();
harness
.push_update(Update::Sample(Arc::new(TimeSample {
monotonic: Some(25),
utc: Some(26),
standard_deviation: None,
..TimeSample::EMPTY
})))
.await;
assert_eq!(
sample_fut.await.unwrap(),
TimeSample {
monotonic: Some(25),
utc: Some(26),
standard_deviation: None,
..TimeSample::EMPTY
}
);
assert_eq!(
sample_fut_2.await.unwrap(),
TimeSample {
monotonic: Some(25),
utc: Some(26),
standard_deviation: None,
..TimeSample::EMPTY
}
);
let proxy_3 = harness.new_proxy();
assert_eq!(
proxy_3.watch_sample().await.unwrap(),
TimeSample {
monotonic: Some(25),
utc: Some(26),
standard_deviation: None,
..TimeSample::EMPTY
}
);
}
#[fuchsia::test(allow_stalls = false)]
async fn test_watch_status() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
assert_eq!(proxy.watch_status().await.unwrap(), Status::Ok);
let status_fut = proxy.watch_status();
harness.push_update(Update::Status(Status::Hardware)).await;
assert_eq!(status_fut.await.unwrap(), Status::Hardware);
assert!(proxy.watch_status().now_or_never().is_none());
}
#[fuchsia::test(allow_stalls = false)]
async fn test_watch_status_sent_to_all_clients() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
let proxy_2 = harness.new_proxy();
assert_eq!(proxy.watch_status().await.unwrap(), Status::Ok);
assert_eq!(proxy_2.watch_status().await.unwrap(), Status::Ok);
let status_fut = proxy.watch_status();
let status_fut_2 = proxy_2.watch_status();
harness.push_update(Update::Status(Status::Hardware)).await;
assert_eq!(status_fut.await.unwrap(), Status::Hardware);
assert_eq!(status_fut_2.await.unwrap(), Status::Hardware);
let proxy_3 = harness.new_proxy();
assert_eq!(proxy_3.watch_status().await.unwrap(), Status::Hardware);
}
#[fuchsia::test]
async fn test_property_updates_sent_to_update_algorithm() {
let mut harness = TestHarness::new();
let proxy = harness.new_proxy();
let proxy_2 = harness.new_proxy();
proxy.update_device_properties(Properties::EMPTY).unwrap();
proxy_2.update_device_properties(Properties::EMPTY).unwrap();
fasync::Timer::new(fasync::Time::after(zx::Duration::from_nanos(1000))).await;
harness.assert_device_properties(&vec![Properties::EMPTY, Properties::EMPTY]).await;
}
}