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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// 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.

#![deny(missing_docs)]

//! `fidl_fuchsia_update_installer_ext` contains wrapper types around the auto-generated
//! `fidl_fuchsia_update_installer` bindings.

pub mod state;
pub use state::{
    FailFetchData, FailStageData, FetchFailureReason, PrepareFailureReason, Progress,
    StageFailureReason, State, StateId, UpdateInfo, UpdateInfoAndProgress,
};

pub mod options;
pub use options::{Initiator, Options};

use {
    fidl::endpoints::{ClientEnd, ServerEnd},
    fidl_fuchsia_update_installer::{
        InstallerProxy, MonitorMarker, MonitorRequest, MonitorRequestStream,
        RebootControllerMarker, UpdateNotStartedReason,
    },
    fuchsia_url::AbsolutePackageUrl,
    futures::{
        prelude::*,
        task::{Context, Poll},
    },
    pin_project::pin_project,
    std::{fmt, pin::Pin},
    thiserror::Error,
    tracing::info,
};

/// Describes the errors encountered by UpdateAttempt.
#[derive(Debug, Error)]
pub enum UpdateAttemptError {
    /// Fidl error.
    #[error("FIDL error")]
    FIDL(#[source] fidl::Error),

    /// Install already in progress.
    #[error("an installation was already in progress")]
    InstallInProgress,
}

/// Describes the errors encountered by the UpdateAttempt's monitor stream.
#[derive(Debug, Error)]
pub enum MonitorUpdateAttemptError {
    /// Fidl error.
    #[error("FIDL error")]
    FIDL(#[source] fidl::Error),

    /// Error while decoding a [`fidl_fuchsia_update_installer::State`].
    #[error("unable to decode State")]
    DecodeState(#[source] state::DecodeStateError),
}

/// An update attempt.
#[pin_project(project = UpdateAttemptProj)]
#[derive(Debug)]
pub struct UpdateAttempt {
    /// UUID identifying the update attempt.
    attempt_id: String,

    /// The monitor for this update attempt.
    #[pin]
    monitor: UpdateAttemptMonitor,
}

/// A monitor of an update attempt.
#[pin_project(project = UpdateAttemptMonitorProj)]
pub struct UpdateAttemptMonitor {
    /// Server end of a fidl_fuchsia_update_installer.Monitor protocol.
    #[pin]
    stream: MonitorRequestStream,
}

impl UpdateAttempt {
    /// Getter for the attempt_id.
    pub fn attempt_id(&self) -> &str {
        &self.attempt_id
    }
}

impl UpdateAttemptMonitor {
    fn new() -> Result<(ClientEnd<MonitorMarker>, Self), fidl::Error> {
        let (monitor_client_end, stream) =
            fidl::endpoints::create_request_stream::<MonitorMarker>()?;

        Ok((monitor_client_end, Self { stream }))
    }

    /// Create a new UpdateAttemptMonitor using the given stream.
    pub fn from_stream(stream: MonitorRequestStream) -> Self {
        Self { stream }
    }
}

/// Checks if an update can be started and returns the UpdateAttempt containing
/// the attempt_id and MonitorRequestStream to the client.
pub async fn start_update(
    update_url: &AbsolutePackageUrl,
    options: Options,
    installer_proxy: &InstallerProxy,
    reboot_controller_server_end: Option<ServerEnd<RebootControllerMarker>>,
) -> Result<UpdateAttempt, UpdateAttemptError> {
    let url = fidl_fuchsia_pkg::PackageUrl { url: update_url.to_string() };
    let (monitor_client_end, monitor) =
        UpdateAttemptMonitor::new().map_err(UpdateAttemptError::FIDL)?;

    let attempt_id = installer_proxy
        .start_update(&url, &options.into(), monitor_client_end, reboot_controller_server_end)
        .await
        .map_err(UpdateAttemptError::FIDL)?
        .map_err(|reason| match reason {
            UpdateNotStartedReason::AlreadyInProgress => UpdateAttemptError::InstallInProgress,
        })?;

    info!("Update started with attempt id: {}", attempt_id);
    Ok(UpdateAttempt { attempt_id, monitor })
}

/// Monitors the running update attempt given by `attempt_id`, or any running update attempt if no
/// `attempt_id` is provided.
pub async fn monitor_update(
    attempt_id: Option<&str>,
    installer_proxy: &InstallerProxy,
) -> Result<Option<UpdateAttemptMonitor>, fidl::Error> {
    let (monitor_client_end, monitor) = UpdateAttemptMonitor::new()?;

    let attached = installer_proxy.monitor_update(attempt_id, monitor_client_end).await?;

    if attached {
        Ok(Some(monitor))
    } else {
        Ok(None)
    }
}

impl fmt::Debug for UpdateAttemptMonitor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UpdateAttemptMonitor").field("stream", &"MonitorRequestStream").finish()
    }
}

impl Stream for UpdateAttemptMonitor {
    type Item = Result<State, MonitorUpdateAttemptError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let UpdateAttemptMonitorProj { stream } = self.project();
        let poll_res = match stream.poll_next(cx) {
            Poll::Ready(None) => return Poll::Ready(None),
            Poll::Ready(Some(res)) => res.map_err(MonitorUpdateAttemptError::FIDL)?,
            Poll::Pending => return Poll::Pending,
        };
        let MonitorRequest::OnState { state, responder } = poll_res;
        let _ = responder.send();
        let state = state.try_into().map_err(MonitorUpdateAttemptError::DecodeState)?;
        Poll::Ready(Some(Ok(state)))
    }
}

impl Stream for UpdateAttempt {
    type Item = Result<State, MonitorUpdateAttemptError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let UpdateAttemptProj { attempt_id: _, monitor } = self.project();
        monitor.poll_next(cx)
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        assert_matches::assert_matches,
        fidl_fuchsia_update_installer::{
            InstallationProgress, InstallerMarker, InstallerRequest, MonitorProxy,
        },
        fuchsia_async as fasync,
        futures::stream::StreamExt,
    };

    const TEST_URL: &str = "fuchsia-pkg://fuchsia.com/update/0";

    impl UpdateAttemptMonitor {
        /// Returns an UpdateAttemptMonitor and a TestAttempt that can be used to send states to
        /// the monitor.
        fn new_test() -> (TestAttempt, Self) {
            let (monitor_client_end, monitor) = Self::new().unwrap();

            (TestAttempt::new(monitor_client_end), monitor)
        }
    }

    struct TestAttempt {
        proxy: MonitorProxy,
    }

    impl TestAttempt {
        /// Wraps the given monitor proxy in a helper type that verifies sending state to the
        /// remote end of the Monitor results in state being acknowledged as expected.
        fn new(monitor_client_end: ClientEnd<MonitorMarker>) -> Self {
            let proxy = monitor_client_end.into_proxy().unwrap();

            Self { proxy }
        }

        async fn send_state_and_recv_ack(&mut self, state: State) {
            self.send_raw_state_and_recv_ack(state.into()).await;
        }

        async fn send_raw_state_and_recv_ack(
            &mut self,
            state: fidl_fuchsia_update_installer::State,
        ) {
            let () = self.proxy.on_state(&state).await.unwrap();
        }
    }

    #[fasync::run_singlethreaded(test)]
    async fn update_attempt_monitor_forwards_and_acks_progress() {
        let (mut send, monitor) = UpdateAttemptMonitor::new_test();

        let expected_fetch_state = &State::Fetch(
            UpdateInfoAndProgress::builder()
                .info(UpdateInfo::builder().download_size(1000).build())
                .progress(Progress::builder().fraction_completed(0.5).bytes_downloaded(500).build())
                .build(),
        );

        let client_fut = async move {
            assert_eq!(
                monitor.try_collect::<Vec<State>>().await.unwrap(),
                vec![State::Prepare, expected_fetch_state.clone()]
            );
        };

        let server_fut = async move {
            send.send_state_and_recv_ack(State::Prepare).await;
            send.send_state_and_recv_ack(expected_fetch_state.clone()).await;
        };

        future::join(client_fut, server_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn update_attempt_monitor_rejects_invalid_state() {
        let (mut send, mut monitor) = UpdateAttemptMonitor::new_test();

        let client_fut = async move {
            assert_matches!(
                monitor.next().await.unwrap(),
                Err(MonitorUpdateAttemptError::DecodeState(_))
            );
            assert_matches!(monitor.next().await, Some(Ok(State::Prepare)));
        };

        let server_fut = async move {
            send.send_raw_state_and_recv_ack(fidl_fuchsia_update_installer::State::Fetch(
                fidl_fuchsia_update_installer::FetchData {
                    info: Some(fidl_fuchsia_update_installer::UpdateInfo {
                        download_size: None,
                        ..Default::default()
                    }),
                    progress: Some(InstallationProgress {
                        fraction_completed: Some(2.0),
                        bytes_downloaded: None,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
            ))
            .await;

            // Even though the previous state was invalid and the monitor stream yielded an error,
            // further states will continue to be processed by the client.
            send.send_state_and_recv_ack(State::Prepare).await;
        };

        future::join(client_fut, server_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn start_update_forwards_args_and_returns_attempt_id() {
        let pkgurl = "fuchsia-pkg://fuchsia.com/update/0".parse().unwrap();

        let opts = Options {
            initiator: Initiator::User,
            allow_attach_to_existing_attempt: false,
            should_write_recovery: true,
        };

        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let (_reboot_controller, reboot_controller_server_end) =
            fidl::endpoints::create_proxy::<RebootControllerMarker>().unwrap();

        let installer_fut = async move {
            let returned_update_attempt =
                start_update(&pkgurl, opts, &proxy, Some(reboot_controller_server_end))
                    .await
                    .unwrap();
            assert_eq!(
                returned_update_attempt.attempt_id(),
                "00000000-0000-0000-0000-000000000001"
            );
        };

        let stream_fut = async move {
            match stream.next().await.unwrap() {
                Ok(InstallerRequest::StartUpdate {
                    url,
                    options:
                        fidl_fuchsia_update_installer::Options {
                            initiator,
                            should_write_recovery,
                            allow_attach_to_existing_attempt,
                            ..
                        },
                    monitor: _,
                    reboot_controller,
                    responder,
                }) => {
                    assert_eq!(url.url, TEST_URL);
                    assert_eq!(initiator, Some(fidl_fuchsia_update_installer::Initiator::User));
                    assert_matches!(reboot_controller, Some(_));
                    assert_eq!(should_write_recovery, Some(true));
                    assert_eq!(allow_attach_to_existing_attempt, Some(false));
                    responder.send(Ok("00000000-0000-0000-0000-000000000001")).unwrap();
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };
        future::join(installer_fut, stream_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_install_error() {
        let pkgurl = "fuchsia-pkg://fuchsia.com/update/0".parse().unwrap();

        let opts = Options {
            initiator: Initiator::User,
            allow_attach_to_existing_attempt: false,
            should_write_recovery: true,
        };

        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let (_reboot_controller, reboot_controller_server_end) =
            fidl::endpoints::create_proxy::<RebootControllerMarker>().unwrap();

        let installer_fut = async move {
            let returned_update_attempt =
                start_update(&pkgurl, opts, &proxy, Some(reboot_controller_server_end))
                    .await
                    .unwrap();

            assert_eq!(
                returned_update_attempt.try_collect::<Vec<State>>().await.unwrap(),
                vec![State::FailPrepare(PrepareFailureReason::Internal)]
            );
        };

        let stream_fut = async move {
            match stream.next().await.unwrap() {
                Ok(InstallerRequest::StartUpdate { monitor, responder, .. }) => {
                    responder.send(Ok("00000000-0000-0000-0000-000000000002")).unwrap();

                    let mut attempt = TestAttempt::new(monitor);
                    attempt
                        .send_state_and_recv_ack(State::FailPrepare(PrepareFailureReason::Internal))
                        .await;
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };
        future::join(installer_fut, stream_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn start_update_forwards_fidl_error() {
        let pkgurl = "fuchsia-pkg://fuchsia.com/update/0".parse().unwrap();

        let opts = Options {
            initiator: Initiator::User,
            allow_attach_to_existing_attempt: false,
            should_write_recovery: true,
        };

        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let installer_fut = async move {
            match start_update(&pkgurl, opts, &proxy, None).await {
                Err(UpdateAttemptError::FIDL(_)) => {} // expected
                _ => panic!("Unexpected result"),
            }
        };
        let stream_fut = async move {
            match stream.next().await.unwrap() {
                Ok(InstallerRequest::StartUpdate { .. }) => {
                    // Don't send attempt id.
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };
        future::join(installer_fut, stream_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_state_decode_error() {
        let pkgurl = "fuchsia-pkg://fuchsia.com/update/0".parse().unwrap();

        let opts = Options {
            initiator: Initiator::User,
            allow_attach_to_existing_attempt: false,
            should_write_recovery: true,
        };

        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let (_reboot_controller, reboot_controller_server_end) =
            fidl::endpoints::create_proxy::<RebootControllerMarker>().unwrap();

        let installer_fut = async move {
            let mut returned_update_attempt =
                start_update(&pkgurl, opts, &proxy, Some(reboot_controller_server_end))
                    .await
                    .unwrap();
            assert_matches!(
                returned_update_attempt.next().await,
                Some(Err(MonitorUpdateAttemptError::DecodeState(
                    state::DecodeStateError::DecodeProgress(
                        state::DecodeProgressError::FractionCompletedOutOfRange
                    )
                )))
            );
        };

        let stream_fut = async move {
            match stream.next().await.unwrap() {
                Ok(InstallerRequest::StartUpdate { monitor, responder, .. }) => {
                    responder.send(Ok("00000000-0000-0000-0000-000000000002")).unwrap();

                    let mut monitor = TestAttempt::new(monitor);
                    monitor
                        .send_raw_state_and_recv_ack(fidl_fuchsia_update_installer::State::Fetch(
                            fidl_fuchsia_update_installer::FetchData {
                                info: Some(fidl_fuchsia_update_installer::UpdateInfo {
                                    download_size: None,
                                    ..Default::default()
                                }),
                                progress: Some(InstallationProgress {
                                    fraction_completed: Some(2.0),
                                    bytes_downloaded: None,
                                    ..Default::default()
                                }),
                                ..Default::default()
                            },
                        ))
                        .await;
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };
        future::join(installer_fut, stream_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_server_close_unexpectedly() {
        let pkgurl = "fuchsia-pkg://fuchsia.com/update/0".parse().unwrap();

        let opts = Options {
            initiator: Initiator::User,
            allow_attach_to_existing_attempt: false,
            should_write_recovery: true,
        };

        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let (_reboot_controller, reboot_controller_server_end) =
            fidl::endpoints::create_proxy::<RebootControllerMarker>().unwrap();

        let expected_states = vec![
            State::Prepare,
            State::Fetch(
                UpdateInfoAndProgress::builder()
                    .info(UpdateInfo::builder().download_size(0).build())
                    .progress(
                        Progress::builder().fraction_completed(0.0).bytes_downloaded(0).build(),
                    )
                    .build(),
            ),
        ];

        let installer_fut = async move {
            let returned_update_attempt =
                start_update(&pkgurl, opts, &proxy, Some(reboot_controller_server_end))
                    .await
                    .unwrap();

            assert_eq!(
                returned_update_attempt.try_collect::<Vec<State>>().await.unwrap(),
                expected_states,
            );
        };
        let stream_fut = async move {
            match stream.next().await.unwrap() {
                Ok(InstallerRequest::StartUpdate { monitor, responder, .. }) => {
                    responder.send(Ok("00000000-0000-0000-0000-000000000003")).unwrap();

                    let mut monitor = TestAttempt::new(monitor);
                    monitor.send_state_and_recv_ack(State::Prepare).await;
                    monitor
                        .send_raw_state_and_recv_ack(fidl_fuchsia_update_installer::State::Fetch(
                            fidl_fuchsia_update_installer::FetchData {
                                info: Some(fidl_fuchsia_update_installer::UpdateInfo {
                                    download_size: None,
                                    ..Default::default()
                                }),
                                progress: Some(InstallationProgress {
                                    fraction_completed: Some(0.0),
                                    bytes_downloaded: None,
                                    ..Default::default()
                                }),
                                ..Default::default()
                            },
                        ))
                        .await;

                    // monitor never sends a terminal state, but the client stream doesn't mind.
                    // Higher layers of the system (ex. omaha-client/system-update-checker) convert
                    // this situation into an error.
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };
        future::join(installer_fut, stream_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn monitor_update_uses_provided_attempt_id() {
        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let client_fut = async move {
            let _ = monitor_update(Some("id"), &proxy).await;
        };

        let server_fut = async move {
            match stream.next().await.unwrap().unwrap() {
                InstallerRequest::MonitorUpdate { attempt_id, .. } => {
                    assert_eq!(attempt_id.as_deref(), Some("id"));
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };

        future::join(client_fut, server_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn monitor_update_handles_no_update_in_progress() {
        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let client_fut = async move {
            assert_matches!(monitor_update(None, &proxy).await, Ok(None));
        };

        let server_fut = async move {
            match stream.next().await.unwrap().unwrap() {
                InstallerRequest::MonitorUpdate { attempt_id, monitor, responder } => {
                    assert_eq!(attempt_id, None);
                    drop(monitor);
                    responder.send(false).unwrap();
                }
                request => panic!("Unexpected request: {request:?}"),
            }
            assert_matches!(stream.next().await, None);
        };

        future::join(client_fut, server_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn monitor_update_forwards_fidl_error() {
        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let client_fut = async move {
            assert_matches!(monitor_update(None, &proxy).await, Err(_));
        };
        let server_fut = async move {
            match stream.next().await.unwrap() {
                Ok(InstallerRequest::MonitorUpdate { .. }) => {
                    // Close the channel instead of sending a response.
                }
                request => panic!("Unexpected request: {request:?}"),
            }
        };
        future::join(client_fut, server_fut).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn monitor_update_forwards_and_acks_progress() {
        let (proxy, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<InstallerMarker>().unwrap();

        let client_fut = async move {
            let monitor = monitor_update(None, &proxy).await.unwrap().unwrap();

            assert_eq!(
                monitor.try_collect::<Vec<State>>().await.unwrap(),
                vec![State::Prepare, State::FailPrepare(PrepareFailureReason::Internal)]
            );
        };

        let server_fut = async move {
            match stream.next().await.unwrap().unwrap() {
                InstallerRequest::MonitorUpdate { attempt_id, monitor, responder } => {
                    assert_eq!(attempt_id, None);
                    responder.send(true).unwrap();
                    let mut monitor = TestAttempt::new(monitor);

                    monitor.send_state_and_recv_ack(State::Prepare).await;
                    monitor
                        .send_state_and_recv_ack(State::FailPrepare(PrepareFailureReason::Internal))
                        .await;
                }
                request => panic!("Unexpected request: {request:?}"),
            }
            assert_matches!(stream.next().await, None);
        };

        future::join(client_fut, server_fut).await;
    }
}