input_testing/
input_reports_reader.rs

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
// Copyright 2020 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.

use anyhow::{format_err, Context as _, Error};
use fidl_fuchsia_input_report::{
    InputReport, InputReportsReaderRequest, InputReportsReaderRequestStream,
};
use futures::{StreamExt, TryStreamExt};
use std::convert::TryFrom as _;

/// Implements the server side of the `fuchsia.input.report.InputReportsReader`
/// protocol. Used by `modern_backend::InputDevice`.
pub(super) struct InputReportsReader {
    pub(super) request_stream: InputReportsReaderRequestStream,
    /// FIFO queue of reports to be consumed by calls to
    /// `fuchsia.input.report.InputReportsReader.ReadInputReports()`.
    pub(super) report_receiver: futures::channel::mpsc::UnboundedReceiver<InputReport>,
}

impl InputReportsReader {
    /// Returns a `Future` that resolves when
    /// * `self.reports` is empty, or
    /// * `self.request_stream` yields `None`, or
    /// * an error occurs (invalid FIDL request, failure to send FIDL response).
    ///
    /// # Resolves to
    /// * `Ok(())` if all reports were written successfully
    /// * `Err` otherwise
    ///
    /// # Corner cases
    /// If `self.reports` is _initially_ empty, the returned `Future` will resolve immediately.
    ///
    /// # Note
    /// When the future resolves, `InputReports` may still be sitting unread in the
    /// channel to the `fuchsia.input.report.InputReportsReader` client. (The client will
    /// typically be an input pipeline implementation.)
    pub(super) async fn into_future(self) -> Result<(), Error> {
        // Group `reports` into chunks, to respect the requirements of the `InputReportsReader`
        // protocol. Then `zip()` each chunk with a `InputReportsReader` protocol request.
        // * If there are more chunks than requests, then some of the `InputReport`s were
        //   not sent to the `InputReportsReader` client. In this case, this function
        //   will report an error by checking `reports.is_done()` below.
        // * If there are more requests than reports, no special-case handling is needed.
        //   This is because an input pipeline implementation will normally issue
        //   `ReadInputReports` requests indefinitely.
        let chunk_size = usize::try_from(fidl_fuchsia_input_report::MAX_DEVICE_REPORT_COUNT)
            .context("converting MAX_DEVICE_REPORT_COUNT to usize")?;
        let mut reports = self.report_receiver.ready_chunks(chunk_size).fuse();
        self.request_stream
            .zip(reports.by_ref())
            .map(|(request, reports)| match request {
                Ok(request) => Ok((request, reports)),
                Err(e) => Err(anyhow::Error::from(e).context("while reading reader request")),
            })
            .try_for_each(|request_and_reports| async {
                match request_and_reports {
                    (InputReportsReaderRequest::ReadInputReports { responder }, reports) => {
                        responder
                            .send(Ok(&reports))
                            .map_err(anyhow::Error::from)
                            .context("while sending reports")
                    }
                }
            })
            .await?;

        match reports.is_done() {
            true => Ok(()),
            false => Err(format_err!("request_stream terminated with reports still pending")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{InputReport, InputReportsReader};
    use anyhow::{Context as _, Error};
    use fidl::endpoints;
    use fidl_fuchsia_input_report::{InputReportsReaderMarker, MAX_DEVICE_REPORT_COUNT};
    use fuchsia_async as fasync;
    use futures::future;

    mod report_count {
        use super::*;
        use futures::pin_mut;
        use futures::task::Poll;

        #[fasync::run_until_stalled(test)]
        async fn serves_single_report() -> Result<(), Error> {
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            report_sender
                .unbounded_send(InputReport::default())
                .expect("sending empty InputReport");
            let reports_fut = proxy.read_input_reports();
            std::mem::drop(proxy); // Drop `proxy` to terminate `request_stream`.
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.

            let (_, reports_result) = future::join(reader_fut, reports_fut).await;
            let reports = reports_result
                .expect("fidl error")
                .map_err(zx::Status::from_raw)
                .expect("service error");
            assert_eq!(reports.len(), 1, "incorrect reports length");
            Ok(())
        }

        #[fasync::run_until_stalled(test)]
        async fn serves_max_report_count_reports() -> Result<(), Error> {
            let max_reports = usize::try_from(MAX_DEVICE_REPORT_COUNT)
                .context("internal error converting MAX_DEVICE_REPORT_COUNT to usize")?;
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            for _ in 0..max_reports {
                report_sender
                    .unbounded_send(InputReport::default())
                    .expect("sending empty InputReport");
            }
            let reports_fut = proxy.read_input_reports();
            std::mem::drop(proxy); // Drop `proxy` to terminate `request_stream`.
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.

            let (_, reports_result) = future::join(reader_fut, reports_fut).await;
            let reports = reports_result
                .expect("fidl error")
                .map_err(zx::Status::from_raw)
                .expect("service error");
            assert_eq!(reports.len(), max_reports, "incorrect reports length");
            Ok(())
        }

        #[test]
        fn splits_overflowed_reports_to_next_read() -> Result<(), Error> {
            let mut executor = fasync::TestExecutor::new();
            let max_reports = usize::try_from(MAX_DEVICE_REPORT_COUNT)
                .context("internal error converting MAX_DEVICE_REPORT_COUNT to usize")?;
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            for _ in 0..max_reports + 1 {
                report_sender
                    .unbounded_send(InputReport::default())
                    .expect("sending empty InputReport");
            }
            pin_mut!(reader_fut);

            // Note: this test deliberately serializes its FIDL requests. Concurrent requests
            // are tested separately, in `super::fidl_interactions::preserves_query_order()`.
            let reports_fut = proxy.read_input_reports();
            let _ = executor.run_until_stalled(&mut reader_fut);
            pin_mut!(reports_fut);
            match executor.run_until_stalled(&mut reports_fut) {
                Poll::Pending => panic!("read did not complete (1st query)"),
                Poll::Ready(res) => {
                    let reports = res
                        .expect("fidl error")
                        .map_err(zx::Status::from_raw)
                        .expect("service error");
                    assert_eq!(reports.len(), max_reports, "incorrect reports length (1st query)");
                }
            }

            let reports_fut = proxy.read_input_reports();
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.
            let _ = executor.run_until_stalled(&mut reader_fut);
            pin_mut!(reports_fut);
            match executor.run_until_stalled(&mut reports_fut) {
                Poll::Pending => panic!("read did not complete (2nd query)"),
                Poll::Ready(res) => {
                    let reports = res
                        .expect("fidl error")
                        .map_err(zx::Status::from_raw)
                        .expect("service error");
                    assert_eq!(reports.len(), 1, "incorrect reports length (2nd query)");
                }
            }

            Ok(())
        }
    }

    mod future_resolution {
        use super::*;
        use assert_matches::assert_matches;

        #[fasync::run_until_stalled(test)]
        async fn resolves_to_ok_when_all_reports_are_written() -> Result<(), Error> {
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            report_sender
                .unbounded_send(InputReport::default())
                .expect("sending empty InputReport");
            let _reports_fut = proxy.read_input_reports();
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.
            assert_matches!(reader_fut.await, Ok(()));
            Ok(())
        }

        #[fasync::run_until_stalled(test)]
        async fn resolves_to_err_when_request_stream_is_terminated_before_reports_are_written(
        ) -> Result<(), Error> {
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            report_sender
                .unbounded_send(InputReport::default())
                .expect("sending empty InputReport");
            std::mem::drop(proxy); // Drop `proxy` to terminate `request_stream`.
            assert_matches!(reader_fut.await, Err(_));
            Ok(())
        }

        #[fasync::run_until_stalled(test)]
        async fn resolves_to_err_if_request_stream_yields_error() -> Result<(), Error> {
            let (client_end, request_stream) =
                endpoints::create_request_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            report_sender
                .unbounded_send(InputReport::default())
                .expect("sending empty InputReport");
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.
            client_end
                .into_channel()
                .write(b"not a valid FIDL message", /* handles */ &mut [])
                .expect("internal error writing to channel");
            assert_matches!(reader_fut.await, Err(_)); // while reading reader request
            Ok(())
        }

        /* TODO(https://fxbug.dev/42075735): Re-enable this test
        #[fasync::run_until_stalled(test)]
        async fn resolves_to_err_if_send_fails() -> Result<(), Error> {
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            report_sender.unbounded_send(InputReport::default()).expect("sending empty InputReport");
            let result_fut = proxy.read_input_reports(); // Send query.
            std::mem::drop(result_fut); // Close handle to channel.
            std::mem::drop(proxy); // Close other handle to channel.
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.
            assert_matches!(reader_fut.await, Err(_)); // while sending reports
            Ok(())
        }
        */

        #[fasync::run_until_stalled(test)]
        async fn immediately_resolves_to_ok_when_reports_is_initially_empty() -> Result<(), Error> {
            let (_proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.
            assert_matches!(reader_fut.await, Ok(()));
            Ok(())
        }
    }

    mod fidl_interactions {
        use super::*;
        use assert_matches::assert_matches;
        use futures::pin_mut;
        use futures::task::Poll;

        #[test]
        fn closes_channel_after_reports_are_consumed() -> Result<(), Error> {
            let mut executor = fasync::TestExecutor::new();
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            report_sender
                .unbounded_send(InputReport::default())
                .expect("sending empty InputReport");
            let reports_fut = proxy.read_input_reports();
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.

            // Process the first query. This should close the FIDL connection.
            let futures = future::join(reader_fut, reports_fut);
            pin_mut!(futures);
            std::mem::drop(executor.run_until_stalled(&mut futures));

            // Try sending another query. This should fail.
            assert_matches!(
                executor.run_until_stalled(&mut proxy.read_input_reports()),
                Poll::Ready(Err(fidl::Error::ClientChannelClosed { .. }))
            );
            Ok(())
        }

        #[fasync::run_until_stalled(test)]
        async fn preserves_query_order() -> Result<(), Error> {
            let max_reports = usize::try_from(MAX_DEVICE_REPORT_COUNT)
                .context("internal error converting MAX_DEVICE_REPORT_COUNT to usize")?;
            let (proxy, request_stream) =
                endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
            let (report_sender, report_receiver) =
                futures::channel::mpsc::unbounded::<InputReport>();
            let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
            for _ in 0..max_reports + 1 {
                report_sender
                    .unbounded_send(InputReport::default())
                    .expect("sending empty InputReport");
            }
            let first_reports_fut = proxy.read_input_reports();
            let second_reports_fut = proxy.read_input_reports();
            std::mem::drop(proxy); // Drop `proxy` to terminate `request_stream`.
            std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.

            let (_, first_reports_result, second_reports_result) =
                futures::join!(reader_fut, first_reports_fut, second_reports_fut);
            let first_reports = first_reports_result
                .expect("fidl error")
                .map_err(zx::Status::from_raw)
                .expect("service error");
            let second_reports = second_reports_result
                .expect("fidl error")
                .map_err(zx::Status::from_raw)
                .expect("service error");
            assert_eq!(first_reports.len(), max_reports, "incorrect reports length (1st query)");
            assert_eq!(second_reports.len(), 1, "incorrect reports length (2nd query)");
            Ok(())
        }
    }

    #[fasync::run_until_stalled(test)]
    async fn preserves_report_order() -> Result<(), Error> {
        let (proxy, request_stream) =
            endpoints::create_proxy_and_stream::<InputReportsReaderMarker>();
        let (report_sender, report_receiver) = futures::channel::mpsc::unbounded::<InputReport>();
        let reader_fut = InputReportsReader { request_stream, report_receiver }.into_future();
        report_sender
            .unbounded_send(InputReport { event_time: Some(1), ..Default::default() })
            .expect("sending first InputReport");
        report_sender
            .unbounded_send(InputReport { event_time: Some(2), ..Default::default() })
            .expect("sending second InputReport");

        let reports_fut = proxy.read_input_reports();
        std::mem::drop(report_sender); // Drop `report_sender` to terminate `report_receiver`.

        assert_eq!(
            future::join(reader_fut, reports_fut)
                .await
                .1
                .expect("fidl error")
                .map_err(zx::Status::from_raw)
                .expect("service error")
                .iter()
                .map(|report| report.event_time)
                .collect::<Vec<_>>(),
            [Some(1), Some(2)]
        );
        Ok(())
    }
}