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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! The `pull_source` library defines an implementation of the `PullSource` API and traits to hook
//! in an algorithm that produces time updates.

use {
    anyhow::Error,
    async_trait::async_trait,
    fidl_fuchsia_time_external::{
        self as ftexternal, Properties, PullSourceRequest, PullSourceRequestStream, TimeSample,
        Urgency,
    },
    fuchsia_zircon as zx,
    futures::{lock::Mutex, TryStreamExt},
    tracing::warn,
};

/// An |UpdateAlgorithm| trait produces time samples on demand.
#[async_trait]
pub trait UpdateAlgorithm {
    /// Update the algorithm's knowledge of device properties.
    async fn update_device_properties(&self, properties: Properties);

    /// Produce a new time sample, taking into account `Urgency`.
    async fn sample(&self, urgency: Urgency) -> Result<TimeSample, SampleError>;

    /// Returns the monotonic time at which the next sample may be produced.
    async fn next_possible_sample_time(&self) -> zx::Time;
}

/// Reasons `sample()` may fail.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SampleError {
    /// An error occurred that cannot be classified as one of the more specific
    /// error statuses.
    Unknown,
    /// An internal error occurred. This usually indicates a bug in the
    /// component implementation.
    Internal,
    /// A local resource error occurred such as IO, FIDL, or memory allocation
    /// failure.
    Resource,
    /// A network error occurred.
    Network,
    /// Some hardware that the time source depends on failed.
    Hardware,
    /// A retriable error specific to the implemented time protocol occurred,
    /// such as a malformed response from a remote server.
    Protocol,
    /// Sampling failed in a nonretriable way. Examples include failed
    /// authentication, or a missing configuration.
    ProtocolUnrecoverable,
    /// The request was made too soon and the client should wait before making
    /// another request.
    RateLimited,
}

impl From<SampleError> for ftexternal::Error {
    fn from(e: SampleError) -> Self {
        match e {
            SampleError::Unknown => ftexternal::Error::Unknown,
            SampleError::Internal => ftexternal::Error::Internal,
            SampleError::Resource => ftexternal::Error::Resource,
            SampleError::Network => ftexternal::Error::Network,
            SampleError::Hardware => ftexternal::Error::Hardware,
            SampleError::Protocol => ftexternal::Error::Protocol,
            SampleError::ProtocolUnrecoverable => ftexternal::Error::ProtocolUnrecoverable,
            SampleError::RateLimited => ftexternal::Error::RateLimited,
        }
    }
}

/// An implementation of |fuchsia.time.external.PullSource| that routes time updates from an
/// |UpdateAlgorithm| to clients of the fidl protocol and routes device property updates from fidl
/// clients to the |UpdateAlgorithm|.
/// This implementation is based on assumption that there's only one client.
pub struct PullSource<UA: UpdateAlgorithm> {
    /// The algorithm used to obtain new updates.
    update_algorithm: UA,
}

impl<UA: UpdateAlgorithm> PullSource<UA> {
    /// Create a new |PullSource| that polls |update_algorithm| for time updates and starts in the
    /// |initial_status| status.
    pub fn new(update_algorithm: UA) -> Result<Self, Error> {
        Ok(Self { update_algorithm })
    }

    /// Handle a single client's requests received on the given |request_stream|.
    pub async fn handle_requests_for_stream(
        &self,
        mut request_stream: PullSourceRequestStream,
    ) -> Result<(), Error> {
        while let Some(request) = request_stream.try_next().await? {
            match request {
                PullSourceRequest::Sample { urgency, responder } => {
                    let sample = self.update_algorithm.sample(urgency).await;
                    responder.send(sample.as_ref().map_err(|e| (*e).into()))?;
                }
                PullSourceRequest::NextPossibleSampleTime { responder, .. } => {
                    responder.send(
                        self.update_algorithm.next_possible_sample_time().await.into_nanos(),
                    )?;
                }
                PullSourceRequest::UpdateDeviceProperties { properties, .. } => {
                    self.update_algorithm.update_device_properties(properties).await;
                }
            }
        }
        Ok(())
    }
}

/// An UpdateAlgorithm that is backed up by the samples, set up by a test.
/// This implementation allows other crates and integration tests to use an implementation of
/// `UpdateAlgorithm`.
pub struct TestUpdateAlgorithm {
    /// List of received device property updates
    device_property_updates: Mutex<Vec<Properties>>,

    /// Time Samples to be generated by `sample()`.
    samples: Mutex<Vec<(Urgency, Result<TimeSample, SampleError>)>>,
}

impl TestUpdateAlgorithm {
    /// Create a new instance of `TestUpdateAlgorithm` with empty collection of samples to be used.
    pub fn new() -> Self {
        let device_property_updates = Mutex::new(Vec::new());
        let samples = Mutex::new(Vec::new());
        TestUpdateAlgorithm { device_property_updates, samples }
    }
}

#[async_trait]
impl UpdateAlgorithm for TestUpdateAlgorithm {
    async fn update_device_properties(&self, properties: Properties) {
        self.device_property_updates.lock().await.push(properties);
    }

    async fn sample(&self, urgency: Urgency) -> Result<TimeSample, SampleError> {
        let mut samples = self.samples.lock().await;
        if samples.is_empty() {
            warn!("No test samples found.");
            return Err(SampleError::Internal);
        }
        let (expected_urgency, sample) = samples.remove(0);
        if urgency == expected_urgency {
            sample
        } else {
            warn!("Wrong urgency provided: expected {:?}, got {:?}.", expected_urgency, urgency);
            Err(SampleError::Internal)
        }
    }

    async fn next_possible_sample_time(&self) -> zx::Time {
        // TODO(https://fxbug.dev/42065019): Implement rate limiting.
        zx::Time::get_monotonic()
    }
}

#[cfg(test)]
mod test {
    use {
        super::*,
        fidl::endpoints::create_proxy_and_stream,
        fidl_fuchsia_time_external::{PullSourceMarker, PullSourceProxy},
        fuchsia_async as fasync,
        std::sync::Arc,
    };

    struct TestHarness {
        /// The `PullSource` under test.
        test_source: Arc<PullSource<TestUpdateAlgorithm>>,

        /// Task which handles requests from `PullSource` proxy client.
        _server: fasync::Task<Result<(), Error>>,
    }

    impl TestHarness {
        fn new() -> (Self, PullSourceProxy) {
            let update_algorithm = TestUpdateAlgorithm::new();
            let test_source = Arc::new(PullSource::new(update_algorithm).unwrap());
            let (proxy, stream) = create_proxy_and_stream::<PullSourceMarker>().unwrap();
            let server = fasync::Task::spawn({
                let test_source = Arc::clone(&test_source);
                async move { test_source.handle_requests_for_stream(stream).await }
            });
            (TestHarness { test_source, _server: server }, proxy)
        }

        async fn add_sample(&mut self, urgency: Urgency, sample: Result<TimeSample, SampleError>) {
            self.test_source.update_algorithm.samples.lock().await.push((urgency, sample));
        }

        async fn get_device_properties(&self) -> Vec<Properties> {
            self.test_source.update_algorithm.device_property_updates.lock().await.clone()
        }
    }

    #[fuchsia::test]
    async fn test_empty_harness() {
        let (_harness, client) = TestHarness::new();
        // Should generate an error here since there are no events set up.
        let result = client.sample(Urgency::Low).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Err(ftexternal::Error::Internal),);
    }

    #[fuchsia::test]
    async fn test_harness_expects_sample_urgency() {
        let (mut harness, client) = TestHarness::new();

        harness
            .add_sample(
                Urgency::Low,
                Ok(TimeSample {
                    monotonic: Some(12),
                    utc: Some(34),
                    standard_deviation: None,
                    ..Default::default()
                }),
            )
            .await;
        // Should generate an error here since there requested urgency doesn't match provided.
        let result = client.sample(Urgency::High).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Err(ftexternal::Error::Internal),);
    }

    #[fuchsia::test]
    async fn test_multiple_samples() {
        let (mut harness, client) = TestHarness::new();

        harness
            .add_sample(
                Urgency::Low,
                Ok(TimeSample {
                    monotonic: Some(12),
                    utc: Some(34),
                    standard_deviation: None,
                    ..Default::default()
                }),
            )
            .await;
        harness
            .add_sample(
                Urgency::High,
                Ok(TimeSample {
                    monotonic: Some(56),
                    utc: Some(78),
                    standard_deviation: None,
                    ..Default::default()
                }),
            )
            .await;

        assert_eq!(
            client.sample(Urgency::Low).await.unwrap().unwrap(),
            TimeSample {
                monotonic: Some(12),
                utc: Some(34),
                standard_deviation: None,
                ..Default::default()
            }
        );
        assert_eq!(
            client.sample(Urgency::High).await.unwrap().unwrap(),
            TimeSample {
                monotonic: Some(56),
                utc: Some(78),
                standard_deviation: None,
                ..Default::default()
            }
        );
    }

    #[fuchsia::test]
    async fn test_property_updates_sent_to_update_algorithm() {
        let (harness, client) = TestHarness::new();

        client.update_device_properties(&Properties::default()).unwrap();
        // Sleep here to allow the executor to run the task servicing the request.
        fasync::Timer::new(fasync::Time::after(zx::Duration::from_nanos(1000))).await;
        assert_eq!(harness.get_device_properties().await, vec![Properties::default()]);
    }
}